Posts

Showing posts from 2014

c# - Download images using web browser control -

in web browser app windows phone 7, able see images, want download images web pages(using context menu) , save media library. web browser control named browsers . can me? in advance help? there errors in below codes- in "uri" , in "e" . private void menuitem_click(object sender, routedeventargs e) { httpwebrequest webrequest = httpwebrequest.createhttp(uri);>>>error in "uri" webrequest.begingetresponse((asynccallback) => { try { medialibrary library = new medialibrary(); library.savepicture(imagename, webrequest.endgetresponse(asynccallback).getresponsestream()); } catch (exception e)>>>>>error in "e" {} }, webrequest); } public string imagename { get; set; } tab , hold on image in browser control ... geta context menu saving image ?

Need answers to few javascript questions? -

https://stackoverflow.com/questions/1684917/what-questions-should-a-javascript-programmer-be-able-to-answer i need few answers questions posted here?. i'm iterating through array defined, has 3 elements in it.. numbers 1 2 , 3.. why on earth jack showing up? object.prototype.jack = {}; var = [1,2,3]; ( var number in ) { alert( number ) } why alert undefined when declared jack variable 'jack'? <script> (function() { var jack = 'jack'; })(); alert(typeof jack) </script> why object , not array? how detect if array? array = [1,2]; alert( typeof array ) i have 2 strings, second evaluation doesn't become true. potential bug? how come it's not true? alert( [typeof 'hi' === 'string', typeof new string('hi') === 'string' ] ) for first question, for-in construct in javascript intended iterate on object properties. since have added jack prototype of objects, appear. ...

named entity recognition - to tag NE on multiple files using Stanford NER -

i want use stanford ner tag name entity in multiple files. in documentation said can use option -testfiles list of test files separated commas not work in case like: java -cp stanford-ner.jar edu.stanford.nlp.ie.crf.crfclassifier -loadclassifier ner-model.ser.gz -testfiles test_file1.tsv,test_file2.tsv but works when input 1 file. does system have inline evaluation (for p, r) multiple files? wonder how works in case of multiple files. thanks in advance. khadaka

c# - Get all User-Created Classes in AppDomain.CurrentDomain -

i want loop on classes have added in project assembly[] foo = appdomain.currentdomain.getassemblies(); foreach(assembly in foo) { foreach(type t in a.gettypes()) { } } this tried want exclude assemblies provided .net, example "mscorlib" one common solution filter assemblies name, if of assemblies have common prefix (if have more or less unique prefix). var foo = appdomain.currentdomain.getassemblies() .where(a=>a.fullname.startswith("myproject.")); if interested in specific types, consider using attributes classes, or add 1 @ assembly level. example: create attribute: [attributeusage(attributetargets.assembly)] public class myassemblyattribute : attribute { } add following assemblyinfo.cs: [assembly: myassemblyattribute()] and filter assemblies looking at: var foo = appdomain.currentdomain .getassemblies() .where(a => a.getcu...

preg replace - PHP preg_replace regexp for dash -

i trying replace in string not letter, number, or dash "-". how modify line include dash? $link = preg_replace('/[^a-z0-9]/', "", strtolower($_post['link_name'])); do insert in there? $link = preg_replace('/[^a-z0-9-]/', "", strtolower($_post['link_name'])); you have escape - since it's special character regexes: $link = preg_replace('/[^a-z0-9\-]/', '', strtolower($_post['link_name']));

java - Caliper: why not use an annotation to define a benchmark? -

just found out caliper, , going through documentation - looks great tool (thanks kevin , gang @ google opensourcing it). question. why isn't there annotation-based mechanism define benchmarks common use cases? seems like: public class foo { // foo's actual code, followed by... @benchmark static int timefoobar(int reps) { foo foo = new foo(); (int = 0; < reps; ++i) foo.bar(); } } would save few lines of code , enhance readability. we decided use timefoo(int reps) rather @time foo(int reps) few reasons: we still have lot of junit 3.8 tests , consistency testfoo() scheme. no need import com.google.caliper.time we'll end reporting benchmark name time foo foo . easy, it's methodname.substring(4) . if used annotations we'd end more complicated machinery handle names @time timefoo(int reps) , @time benchmarkfoo(int reps) , @time foo(int reps) . that said, we're reconsidering caliper 1.0.

android - Is it possible to reuse an activity without destroying it? -

is possible reuse activity without destroying it? example, after press button, activity disappear , app returns previous activity. disappeared activity still in memory , can fast displayed without re-creating it. this reason why have such idea: use activity written others. found there memory leaks couldn't find them because have no source code. want find workaround. its possible if don't kill activity: open 1, 2, 3 activities 1 > 2 > 3 #2 // call startactivity 2, don't call finish() in 3 1 > 2 open #4 activity 1 > 2 > 4 #2 1 > 2 restore #3 activity // call startactivity 3 intent intent.setflags(intent.flag_activity_reorder_to_front); 1 > 2 > 3 here copy of activity 3 left it.

json - CherryPy & php: can't load class of data from pickle, but works from ssh on server -

i using cherrypy generate , parse data php webpage, getting error can't replicate locally or via ssh (logging server , running python script prompt works okay). the current sticky error message is: file "modules/flex.py", line 335, in convert ref_data = cpickle.load(f2) attributeerror: 'module' object has no attribute 'data' another pickle loads fine in previous line, , both pickles represent class objects variety of dictionaries , lists of lists. 1 of these works, , other doesn't. in general cherrypy, what's best way isolate error messages? can run /cp/ function it's url, , can @ webserver error log, these 2 don't give error message (or correct error). on other side, in php, using code retrieve json object representing python list of lists: $obj = file_get_contents($senddata); $sue = json_decode($obj); is acceptable method? what's best way pass , generate php arrays python data structures? i think have di...

charts - MSChart C# Error Bar Graph With Dynamic Upper and Lower Bounds -

i working mschart in c#. given simulation data manufacturing time of 3 different products. need create graph looks error bar graph contains 3 points, each point contains average time value, , upper , lower bounds of error bar @ each point maximum , minimum time values of simulation. problem have found mschart, error range static; same every point on graph. need error bar graph different minimum , maximum every point. have image of graph should like, of course, not allowed post images. i thought create workaround, inconvenient, creating 6 series in graph, 2 each point, add maximum 1 , minimum other, , hide respective lower , upper bound. trying this, however, makes graph big red x. wondering if capability not possible .net mschart. have @ third party libraries this? the following uses system.windows.forms.datavisualization.charting libraries think have been part of .net since 4.0. chart achart = new chart(); chartarea achartarea = new chartarea(); achart.chartare...

asp.net - GridButtonColumn custom handler -

i have 4 tables i've created using radgrid. each of them contains list of items have title of , id of. want have column "remove" link fire event handler in write code remove id db. each of tables has separate table in db need know table did fire handler , id correspond. another small question is, should include visual studio recognize gridcommandeventargs type? you question little bit confusing. can use deletecommand id of row , delete it. <telerik:radgrid id="radgrid1" runat="server" ondeletecommand="radgrid1_deletecommand" onneeddatasource="radgrid1_needdatasource"> <mastertableview datakeynames="id" commanditemdisplay="top"> <columns> <telerik:gridbuttoncolumn buttontype="imagebutton" confirmtext="are sure want delete?" commandname="delete" imageurl="~/images/delete.png" ...

android - how to use Activity in sub class -

conceptual problem here! want break down program simpler more focused classes. first 1 doing requires startactivityforresult() in turn depends on activity. i can pass activity class. there problem in caller when use getactivity() seems undefined class. why isn't getactivity documented way?

javascript - Facebook Login Button callback function -

i got problem facebook login on website. code below fb-connect code. commented part of code sign's me in website. problem when "reactivate" code logs me in instandly everytime visit page. want log user in when clicks "login facebook"-button. when clicks facebook login button popup shows , nothing happens.. can somehow call js function when click fb-connect button? <script> window.fbasyncinit = function() { fb.init({ appid : 'xxxxxxxxxxxxxxxxxx', // app id status : true, cookie : true, xfbml : true, oauth : true, }); var login = false; fb.getloginstatus(function(response) { if (response.status === 'connected') { console.log(...

python - How to tell the current shape of my cursor? -

when automating clicks , keystrokes, have wait until button finishes loading , becomes clickable. indicator of is, knowledge, shape of cursor. in programming language (preferably python), there way tell if has changed pointer hand? you take screenshot use pil imaging library combined current cursor position find out how wide mouse is. might not work if there white or black background though.

java - Android Static functions -

i'm wondering how can access return statement static function. have static function async , want return statement in class - know sounds complex but, i'm sure it's easy solution. login.class public class login extends activity { button login; @override protected void oncreate(bundle savedinstancestate) { // todo auto-generated method stub super.oncreate(savedinstancestate); setcontentview(r.layout.login); textview top = (textview) findviewbyid(r.id.textview2); final edittext user = (edittext) findviewbyid(r.id.etuser); final edittext pass = (edittext) findviewbyid(r.id.etpass); checkbox stay = (checkbox) findviewbyid(r.id.cbstay); button login = (button) findviewbyid(r.id.btlogin); login.setonclicklistener( new view.onclicklistener() { public void onclick(view v) { // todo auto-generated method stub string user1 = user.gettext().tostring(); ...

javascript - How does Facebook find out whether it's mobile device or not? -

i've run myself problem while implementing fb pay dialog external site. for displaying dialog, use fb.ui method according documentation: https://developers.facebook.com/docs/reference/dialogs/pay/ but url generated js contains display=popup parameter, works on mobile devices only. it's not case: need payments work on both mobiles , desktops. so, decided use js fb.ui method mobiles , simple url desktops. here questions: 1) correct decision or there better way make fb pay dialog work on both mobiles , desktops? 2) if it's best way, how can find out whether it's mobile device or not? internally, in our site use list of mobile user agents guessing, it's not fb way. so, what's fb way?

php - Fatal error: Undefined class constant 'EXCEPTION_NO_ROUTE' in Zend framework -

i have downloaded zend latest version(zend framework 1.11), created project using command line tool. also i've created controller in created project. in created controller i've added new method, <?php class usercontroller extends zend_controller_action { public function init() { /* initialize action controller here */ } public function indexaction() { // action body } public function chataction() { echo 'test'; } } then tried access in browser http://localhost/user/chat i got following error fatal error: undefined class constant 'exception_no_route' in f:\xampp\htdocs\z_app\application\controllers\errorcontroller.php on line 16 thanks in advance. you have wrong zend library included. check version via echo zend_version::version; in index.php , die() before bootstrapping (as mvc broken). you may need update include path correct location of 1.11 zend framework library. have multiple versions (i.e. zend studio c...

java - How to deal with error applying BeanValidation relational constraints? -

i've got problems making onetomany relation in spring + hibernate 4.1 application entities classes. every user_role record has fk user record. can't find useful on internet. @entity @table( name = "users" ) public class user { long id; string login; string password; string name; string surname; gregoriancalendar birthdate; string email; gregoriancalendar joindate; string randomkey; list<userrole> userroles = new arraylist<userrole>(); public user(){ } //javabean hibernate requirement @id @generatedvalue(generator="increment") @genericgenerator(name="increment", strategy = "increment") @column(name="user_id", unique=true, nullable=false) public long getid() { return id; } public void setid(long id) { this.id = id; } ... @onetomany(mappedby = "user", fetch = fetchtype.lazy) public list<u...

html - Flat sharp corner or beveled corners -

is there way create sharp flat corner css , html? something this: ____ / \ | | \____/ here solution, using css shapes chris coyier. http://jsfiddle.net/ddejan/xss9l/ 4 divs inserted via javascript (well, jquery actually) each of containers want shaped way. these divs positioned absolutely in corners of it's parent, , styled accordingly described in link posted sven bieder

java - Searching through multiple files does not work -

ok, have function, use search specific text in file, when finds text in file, should return lines in files contain text so, have function that...but have function little bit different, not return anything, , sure file contains searched text... so, here function work: public void searchtext(string text, commandsender p) { file[] searchfiles = new file[files.size()]; searchfiles = files.toarray(searchfiles); filereader filereader = null; bufferedreader br = null; for(file searchfile : searchfiles) { try { filereader = new filereader(searchfile); br = new bufferedreader(filereader); string line = ""; while ((line = br.readline()) != null) { if (line.indexof(text) >= 0) { p.sendmessage(line); } } } catch (exception e) { if((filereader != null) && (br != null)) { try...

rspec - Spork and db:test:prepare -

simple question hope has clever answer. i use spork run specs , features. works great. however, if update database migration, can't update test database without stopping both of spork servers. there anyway can spork let me drop , recreate database without shutting down? the reason ask because can run migrations while dev server runs, , seems me i'm doing exact same thing. had same issue , found this: https://github.com/sporkrb/spork/issues/188 per recommendation there added: activerecord::base.remove_connection to end of spork.prefork block in both spec_helper.rb , env.rb

iphone - Should I authenticate a user's password for every server request? -

i apologize if may common sense some, i'm still learning. have ios app syncs files web server. once user logs in on device, remains logged in unless signs out. currently, whenever user initiates server request, such adding, updating, or deleting files, send user's email , not password server, since user authenticated on device. should sending user's stored password each time makes request , have server authenticate before proceeding request? why or why not? you should send session identifier, rather email address. the session identifier large number (128 bits sufficient) chosen cryptographic random number generator when user authenticated. set "cookie" in user's web device , sent each request on secure channel (tls). email addresses public. can authenticate requests secrets, password or session identifier.

regex that matches URL to image than replaces characters -

hi long time reader first time poster regex question i have rewrite rules in xml file this notation <rule> <from></from> <forward></forward> </rule> in node, looking match url has image extension @ end , dash "-" characters in name. if matches, in forward node replace dash "-" characters underscore characters "_" for example longurl/test-image.jpg go longurl/test_image.jpg you can try on top of .htaccess rewriterule ^(.*)(\-|%2d)(.*)$ /$1_$3

Posting to a Java Servlet from JQuery demoForm -

i using form wizard , want post java sevlet http:\myip\javaservet. i think have use ajax submit in form. have tried various options - nothing works. does know how can performed? thxs! here form: <form id="demoform" method="post" action="json.html" class="bbq"> <div id="fieldwrapper"> <span class="step" id="first"> <span class="font_normal_07em_black">first step - name</span><br /> <label for="firstname">first name</label><br /> <input class="input_field_12em" name="firstname" id="firstname" /><br /> <label for="surname">surname</label><br /> <input class="input_field_12em" name="surname" id="surname" /><br /> </span> <span id="finland" class="step"> <span class="font_normal_07em_blac...

java - Error exporting a document in google docs api -

i'm trying retrieve document this: client.setauthsubtoken(token); string contenturi = "https://docs.google.com/feeds/download/documents/export?docid="+ entry.getdocid() + "&exportformat=txt&format=txt"; mediacontent mc = new mediacontent(); mc.seturi(contenturi); mediasource ms = client.getmedia(mc); inputstream instream = ms.getinputstream(); but getting next error: com.google.appengine.repackaged.org.apache.http.impl.client.defaultrequestdirector handleresponse advertencia: authentication error: unable respond of these challenges: {authsub=www-authenticate: authsub realm="https://www.google.com/accounts/authsubrequest"} do not why if client authenticated, hope 1 can help, in advance. maybe help: replace docid parameter id parameter contenturi = "https://docs.google.com/feeds/download/documents/export/export?id=" + entry.getdocid() + "&exportformat=txt...

asp.net mvc 4 - Cannot save to Azure table -

i dataservicerequestexception exception when try save entity azure table. happens @ line _mycontext.savechangeswithretries(); i've tried google see problem be. not find answer it. anyone kow problem be? storage creator public cloudtableclient getmusicclient() { //retrieve connection string settings cloudstorageaccount storageaccount = cloudstorageaccount.parse( roleenvironment.getconfigurationsettingvalue("storageconnectionstring")); //create table client cloudtableclient tableclient = storageaccount.createcloudtableclient(); //create table if doesn't exist string tablename = "music"; tableclient.createtableifnotexist(tablename); return tableclient; } webapi public music postmusic(string genre, string artist, string random) { cloudtableclient _mytableclient = _mytablerepo.getmusicclient(); tableservicecontext _mycontext = _mytableclient.getdataservicecontext(); music m...

java - Portable persistance queue -> uploader -

Image
i need implement disk-backed queue can accept real-time profiling data multiple threads , upload data on potentially faulty transports. targeted @ java long-term need use same mechanism in objective-c, flash, javascript. targeted @ android java desktop. this contained within single process, mq solution out. performance point of significant consideration, meaning we'd trade reliability performance. i'm curious 2 things: given above architecture, there available technology that'll or partially solve problem? given goal of re-implementing or ideally re-using mechanism in different platforms, there way build in way can used in both objective-c & android java? how's architecture look? in case want keep limited amount of data (circular log), , able reserve fixed amount of persistent memory it, effective solution memory-mapped buffers . persister cache of several buffers, serving both profiling queue , uploader. when reimplementing on other platf...

linux - Script on bash, can you? -

there string $string , in syllables written spaces. if variable $word have @ least 1 syllable in string, report of in way. your solution checks see if $word exists in $string when should other way around. try this: string="run walk stand" word=walking if echo "$string" | sed -e 's/ /\n/g' | grep -fqif - <(echo "$word") echo "match!" fi as can see, can test result of grep without having save output in variable. by way -n same ! -z .

asp.net - ImageButton not firing -

i have following button: <asp:imagebutton id="imgbtneditinfo" runat="server" imageurl="~/images/editinformation.png" alternatetext="editinformation" commandname="editdetails" commandargument="<%# container.dataitemindex %>" onclick="lnkedit_click" enabled="true" /> i have following method looks not hitting method: protected sub lnkedit_click(byval sender object, byval e system.eventargs) end sub wondering if missing something. put breakpoint on protected sub lnkedit_click on click of imagebutton not go there. you're working data controls (gridview or datalist etc). respond button/linkbutton/imagebutton events, must have handle parent - data control's events.

jquery - Catch the side slide effect on iPad -

is possible, jquery or alike, catch (detect) finger side slide possible on fx ipad? it nice able make onfingersideslide effect change page or on website, when viewed on ipad or tablet. if possibility exists fun try creative. thanks in advance. there several jquery plugins made purpose. swipejs one. find here on github . go swipejs.com on ipad try out.

asp.net mvc 3 - jQuery dialog for a partial view is not opening modal -

i have built jquery dialog show partial view entering data. i have built action link: @html.actionlink("add new service provider", "partialnewcust", "customer", null, new { @class = "addserviceproviderlink" }) i have controller action: public actionresult partialnewcust() { return partialview(); } and div / jquery code: <div id="addserviceprovdialog" title="add service provider"></div> <script type="text/javascript"> var linkobj; $(function () { $(".addserviceproviderlink").button(); $('#addserviceprovdialog').dialog( { autoopen: false, width: 400, resizable: false, modal: true, buttons: { "add": function () { $("#addproviderform").submit(); }, "cancel": function () { $(this).d...

objective c - Crash With iOS Private API Call -

this call: [uikeyboardimpl(shortcutconversionsupport) _shortcutconversioncandidateforinput:] is crashing app. googling , looking through apple's api documentation brings no results. have never seen call being made anywhere in app. put break-point @ location believe getting called at. here crash report: (fyi, crash log not symbolicated when using correct dsym file. no idea why) last exception backtrace: 0 corefoundation 0x327e188f __exceptionpreprocess + 163 1 libobjc.a.dylib 0x34837259 objc_exception_throw + 33 2 corefoundation 0x327e1789 +[nsexception raise:format:] + 1 3 corefoundation 0x327e17ab +[nsexception raise:format:] + 35 4 corefoundation 0x3273bf5b -[__nscfstring substringwithrange:] + 103 5 buffer 0x000fa061 0xd6000 + 147553 6 uikit 0x32348137 -[uikeyboardimpl(shortcutconversionsupport) _shortcutconversioncandi...

c - Fast method to initialize my array -

i have array of int , have initialize array value -1. use loop: int i; int myarray[10]; for(i = 0; < 10; i++) myarray[i] = -1; there faster ways? the quickest way know value -1 (or 0 ) memset : int v[10]; memset(v, -1, 10 * sizeof(int)); anyway can optimize loop in way: int i; for(i = 10; i--;) v[i] = -1;

asp.net mvc - MVC3 (Razor) Json Get deserialized data in the Controller -

i need again asp.net mvc (razor view engine). in view (index) have @model ienumerable<movie> i want pass model controller: stringify model in way: <script type="text/javascript"> function postdata(){ var urlact='@url.action("createdoc")'; var model ='@html.raw(json.encode(model)); $.ajax({ data: json.stringify(model), type:"post", url:urlact, datatype:"json", contenttype:"application/json; charset=utf-8" }); } </script> everything seems work, cause know stringified data is: '[{"id":1,"title":"the lord of rings: fellowship of ring","releasedate":"\/date(1007938800000)\/","genre":"fantasy","price":93000000.00},{"id":2,"title":"the lord of rings: 2 towers","releasedate":"\/date(1039042800000)\/","genre":"fantasy","pric...

xml - XSLT Forum: Displaying additional data from members on topic replies -

i'm building forum xslt , symphony, , i'm having trouble getting additional member data (role/rank, avatar, example) displayed next member's username in topic replies. now let me show 2 xml documents , i'll explain how i'm using them , i'm having problems. seems long, it's have clear picture. this xml topic replies looks like. example containing 2 replies topic titled "test topic". important bit here author/item : <topic-replies> <section id="10" handle="topic-replies">topic replies</section> <entry id="66"> <parent-forum> <item id="7" handle="general" section-handle="forums" section-name="forums">general</item> </parent-forum> <parent-topic> <item id="62" handle="test-topic" section-handle="forum-topics" section-name="forum top...

c - Synchronize two processes using two different states -

i trying work out way synchronize 2 processes share data. basically have 2 processes linked using shared memory. need process set data in shared memory area, process b read data , act on it. the sequence of events looking have is: b blocks waiting data available signal a writes data a signals data available b reads data b blocks waiting data not available signal a signals data not available all goes beginning. in other terms, b block until got "1" signal, data, block again until signal went "0". i have managed emulate ok using purely shared memory, either block using while loop consumes 100% of cpu time, or use while loop nanosleep in misses of signals. i have tried using semaphores, can find way wait zero, not one, , trying use 2 semaphores didn't work. don't think semaphores way go. there numerous processes accessing same shared memory area, , processes need notified when shared memory has been modified. it's trying emulat...

Android: how to close app if no Internet connection available? -

i developing game on android, , requires internet connection played. know how check whether connection available or not, not sure in case connection not available. my idea display "no connection available" dialog user, "exit' button right below it, can close app dialog , fix connection. doing system.exit(0) command. however i've read in many places shouldn't use command or close app, , instead let os handle this. but how can solve situation without using system.exit(0)? i believe drawsomething game checks internet connection , presents "exit" button in case don't have one. not sure method using close app though. but how can solve situation without using system.exit(0)? check internet connection in first activity, , call finish() rid of activity if there no internet connection (or, more accurately, after user clicks on confirmation dialog).

uibutton - Add UILongPressGestureRecognizer to multiple buttons inside a UIScrollView -

i have 5-10 diffrent buttons inside uiscrollview . i want add uilongpressgesturerecognizer buttons inside uiscrollview . -(ibaction)checkifuserwantstodosomething:(id)sender { holdtimer = [nstimer scheduledtimerwithtimeinterval:1.2 target:self selector:@selector(doaction:) userinfo:nil repeats:no]; } -(void)doaction:(id)sender { [holdtimer invalidate]; //my code... } you can uiscrollview 's subviews , , filter out uibutton 's so: for (uibutton *button in myscrollview.superview.subviews) { if ([button iskindofclass[uibutton class]]) { } } then can create , add uilongpressgesturerecognizer buttons. uilongpressgesturerecognizer *holdrecognizer = [[uilongpressgesturerecognizer alloc] initwithtarget:self action:@selector(doaction:)]; [holdrecognizer setminimumpressduration:2]; [button addgesturerecognizer:holdrecognizer];

asp.net - RequiredFieldValidator not Validating -

i have control on asp.net page required field validator. problem when go change pages via page buttons doesn't cause validation. here code, can see what's wrong? <asp:label id="lbld_year" runat="server" borderstyle="none" text="fiscal year" cssclass="h2"></asp:label>&nbsp;&nbsp;&nbsp; <asp:dropdownlist id="ddld_year" runat="server" width="100px" tabindex="8" autopostback="true" cssclass="box" causesvalidation="true"> <asp:listitem value="0" selected="true">select year</asp:listitem> </asp:dropdownlist> <asp:requiredfieldvalidator id="rfvd_year" runat="server" controltovalidate="ddld_year" dis...

python - How does IPython's magic %paste work? -

i want copy indented python code / whole functions , classes ipython. everytime try indentation screwed , following error message: indentationerror: unindent not match outer indentation level (<ipython-input-23-354f8c8be51b>, line 12) if want paste code ipython, try %paste , %cpaste magic functions. you can't copy ipython directly. steps: copy lines want copy ipython clipboard enter %paste ipython press enter profit!

interpret a negative number as unsigned with BigInteger java -

is possible parse negative number unsigned value java's biginteger? so instance, i'd interpret -1 ffffffffffffffff . is possible? thanks if thinking of two's complement, must specify working bit length. java long has 64 bits, biginteger not bounded. you this: // two's complement reference: 2^n . // in case, 2^64 (so emulate unsigned long) private static final biginteger two_compl_ref = biginteger.one.shiftleft(64); public static biginteger parsebigintegerpositive(string num) { biginteger b = new biginteger(num); if (b.compareto(biginteger.zero) < 0) b = b.add(two_compl_ref); return b; } public static void main(string[] args) { system.out.println(parsebigintegerpositive("-1").tostring(16)); } but implicitly mean working bigintegers in 0 - 2^64-1 range. or, more general: public static biginteger parsebigintegerpositive(string num,int bitlen) { biginteger b = new biginteger(num); if (b.compareto...

php - How to return null rows from mysql_num_rows? -

i have following mysql query returns data in json. what's best way check if there 0 records, , return fact? $row_num = mysql_num_rows($rslt); $data = array(); while ( $row = mysql_fetch_row($result) ) { $data[] = $row; } echo json_encode( $data ); $row_num = mysql_num_rows($rslt); $data = array(); while ( $row = mysql_fetch_row($result) ) { $data[] = $row; } if(!$data){ echo "this government. have removed database!"; } else { echo json_encode( $data ); }

file - Reading Freebase data dump in python, read to few lines? -

i trying use freebase data dump, seams have problems reading files python. looks program cant read lines. def test2(): count=0 line in open(freebase_topic): count+=1 return count def test3(): count=0 line in open(freebase_quad): count+=1 return count if __name__ == "__main__": print "freebase topic - nr lines:",test2() print "freebase quad - nr lines:",test3() results in this: freebase topic - itr time: 1.21000003815 freebase topic - nr lines: 1643010 freebase quad - iter time: 0.797000169754 freebase quad - nr lines: 3155131 this can all. looks to few lines contain whole freebase. , cant see how possible iterate on 1 33gb file , 5gb file in 2 seconds. what wrong? downloading files again in case went wrong during download process, takes decades connections, asking ere in mean time. file size correct, , have printed of lines , correct. there problem occurred me: open('file',...

c# - SHA256.Create() always returns null -

whenever use sha256.create() method returns null value. here method have encrypting password ... private string encryptpassword(string password) { sha256 sha = sha256.create(password); return bitconverter.tostring(sha.hash); } the debugger shows variable sha null. have tried putting in own method in controller still system.nullreferenceexception public string index() { return bitconverter.tostring(sha256.create("hello world").hash); } i lost. there doing wrong? yes, create() isn't meant message, specifies sha256 implementation. i suspect want use implementation class sha256managed instead. http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha256managed.aspx example: using (var sha256 = new sha256managed()) { byte[] raw = encoding.default.getbytes(password); return sha256.computehash(raw); }

Android Sqlite3 database: Cursor in SQLite is not returning null? -

could advise me why getting true result, though record not exist in database? for clarification, in table, _id telephone number. here's code: public boolean checkifexists(string number){ string[] columns = new string[]{"_id"}; string[] wehreargs = new string[]{number}; this.opendatabase(); if (mydatabase.query("mytable", columns, "_id=?", wehreargs, null, null, null)==null){ mydatabase.query("mytable", columns, "_id=?", wehreargs, null, null, null).close(); this.close(); return false; } else { mydatabase.query("mytable", columns, "_id=?", wehreargs, null, null, null).close(); this.close(); return true; } } as @dougcurrie mentions: query returning non-null cursors only: revised code: public boolean checkifexists(string number){ string[] columns = new string[]{"_id"}; string[] wehreargs = new string[]{number...

iphone - Navigation bar and UIWebview -

i having slight issue , trying fix can't find easiest answer towards it. have navigation bar, taking top pixels away, , hence webview content last 44 px if not wrong goes under bounce , hides content. hence problem have submit button, , since needs clicked, goes under bounce condition , doesn't let me select button. quick solution problem appreciate. thanks make sure uiwebview has autoresizingmask set flexible in height , width. can in interface builder or in code.

objective c - How to differentiate the mouseDown event from mouseDragged in a Transparent NSWindow -

have transparent nswindow simple icon in can dragged around screen. code is: .h: @interface customview : nswindow{ } @property (assign) nspoint initiallocation; .m @synthesize initiallocation; - (id) initwithcontentrect: (nsrect) contentrect stylemask: (nsuinteger) astyle backing: (nsbackingstoretype) bufferingtype defer: (bool) flag{ if (![super initwithcontentrect: contentrect stylemask: nsborderlesswindowmask backing: bufferingtype defer: flag]) return nil; [self setbackgroundcolor: [nscolor clearcolor]]; [self setopaque:no]; [nsapp activateignoringotherapps:yes]; return self; } - (void)mousedragged:(nsevent *)theevent { nsrect screenvisibleframe = [[nsscreen mainscreen] visibleframe]; nsrect windowframe = [self frame]; nspoint neworigin = windowframe.origin; // mouse location in window c...

jquery - Preventing UI from freezing due to ajax calls -

the commented out code @ https://github.com/djangocoder/djangogui/blob/master/templates/base.html on lines 192, 193, 196, 197, 199, , 205 freezing ui up. barely use text editor. want uncomment lines. there way without freezing ui? site @ http://198.144.178.112:8000 you need set async true. that's purpose of async parameter allow happen in background while browser continues on rest of code. edit: sorry, here's more information. starting @ line 173, should change async parameter in initialization of ajax function true. this: function testconnection() { $.ajax({ url: "/", cache: false, async : true, error: function(xmlhttprequest, textstatus, errorthrown) { $('#errorbar').css({'height': ($('#header').height()) + 'px'}).show(); }, success: function(html){ $('#errorbar').hide(); } }); }

iphone - Understanding setNeedsDisplay/drawRect with Blocks -

i'm trying understand how things work in regards concurrent programming , calling setneedsdisplay. have 3 objects. main view - container different uiview objects, main 1 being uiscrollview small map view - small uiview draws miniature version of 1 of other uiview items on screem processor - delegate of main view calculates what's on screen , calls main view what's in view. so simple use case of what's going on user touches scrollview , processor updates what's in view of scrollview (like calculating coordinates, center point, etc) using blocks , asynchronously. posts notification mainview object. when mainview receives notification, calls [smallmap setneedsdisplay]; // example 1 i put logs around call, , see gets called right away. however, drawrect: of function not called right away. gets called after 2 seconds or so. i remember reading setneedsdisplay marks view redraw happen on next event of run loop. but if add code instead: // exa...

Android App that activates other apps on the device according to time and/or location events -

like create app following -- in background active -- can have list of other 3rd party apps on phone -- can activate them -- can send messages them -- can triggered users location would have links code examples above? or otherwise comment above? (0) active (though in background, possible?), while in background mode described in points (2), (3), (4), , (5) in background. look background services http://developer.android.com/reference/android/app/service.html (1) sees other apps on phone (which type of apps possible?). following points (2) , (3) possible if (1) possible. how list of installed android applications , pick 1 run 2) can activate apps/activities seen in (1) . (according user configuration in app abc) example can app create incomming request app startups zygot. please provide code examples of this. @ link ! launches other apps. how harvest list of 3rd party apps? can apps started parameter input? not quite sure asking sorry (3) sends messages b...

c# - Initializing a Nullable Type with Initobj Opcode in IL -

Image
why doesn't c# compiler call default implicit parameterless .ctor instead of intobj null assigned nullable value types? lets have such code: nullable<int> ex1 = new nullable<int>(); nullable<int> ex2 = null; nullable<int> ex3 = new nullable<int>(10); the il output these 2 lines this: it call .ctor last statement , why cannot have instance 2 first statements zeroed fields? why doesn't c# compiler call default implicit parameterless .ctor instead of intobj null assigned nullable value types? because nullable<t> (or other value type) doesn't have parameterless constructor. can verify looking @ in decompiler or using reflection (e.g. typeof(nullable<>).getconstructors() ). if write new t() value type t in c#, looks invokes parameterless constructor (and c# spec calls constructor too), that's not happens, because there no parameterless .ctor method on value types.

php - regex to parse a string with known string seprarators -

i'm trying split concatenated string of key1value1key2value2 problem can't know in order are $k = preg_split("/(name|age|sex)/", "namejohnage27sexm"); var_dump($k); $k = preg_split("/(sex|name|age)/", "age27sexm"); var_dump($k); so can't know if age or name 1st or 2nd index of $k, don't know if "name" key in string, there can limited set of key how do? edit : solved this, tx mario for ($i=1, $n=count($k)-1; $i<$n; $i+=2) { $s[$k[$i]] = $k[$i+1]; } var_dump($s); this clumsy pattern return key-value list: /(?:(name|age|sex)(.+?(?=(?:name|age|sex|\z))))/g thus preg_match using above on "namejohnage27sexm" should return array ["name", "john", "age", "27", "sex", "man"] this makes possible create array ["name" => "john", ...] iterating on elements above.

How to filter / exclude posts by id in list of posts in WordPress Dashboard / Admin -

so, trying filter list of posts (mine custom post type) in wordpress dashboard id. i checking area (custom widget) see if user can edit given post (not, intentionally dodging wordpress roles, etc), if cannot want filter/exclude post list. i want take list: see image: https://lh6.googleusercontent.com/-nqldupohuig/t84suxwqndi/aaaaaaaab1o/fzzvcksjawi/w678-h533-k/list_of_posts.png ...and filter out post id's function returns okay, i've answered own question. here code on how did it. function exclude_list_per_function( $query ) { global $wpdb; //gets post id's, know bit of hack $querystr = " select $wpdb->posts.id $wpdb->posts "; $post_ids = $wpdb->get_results($querystr, object); //go through each post , pass function returns true if user_can, , false if user_can't foreach($post_ids $post_obj){ if(!can_user_other_function_view_this_post(get_post($post_obj->id))){ ...

How to get the embed url for google docs presentation? -

it looks there has been slight change on embedding published google docs presentation. the url iframe embed changed from: https://docs.google.com/present/embed?id=[doc_id] to: https://docs.google.com/presentation/embed?id=[doc_id] looks old documents still require old embed url, , new documents require new url. given doc_id there way (using api) embed url should using? update : after poking around, looks revision, old doc has link tag rel=http://schemas.google.com/docs/2007#publish , contains https://docs.google.com/present/embed?id=[doc_id] , on new doc value https://docs.google.com/feeds?xoauth_requestor_id=[user_email] . so question can assume if link rel=http://schemas.google.com/docs/2007#publish contains https://docs.google.com/feeds?xoauth_requestor_id=[user_email] need use url https://docs.google.com/presentation/embed?id=[doc_id] ? or api didn't include correct value in revision? (because think happened quite recently). the embed link has r...

Convert MySQL script to SQL Server -

i have large mysql set of commands in file (script) , need execute on microsoft sql server 2008. know there few differences in both languages, despite fact base sql same. is there way how convert mysql script 1 executable on sql server? or there migration app can take whole mysql server , replicate on sql server 2008? thanks advice. i tried full convert enterprise quite big success. fast, easy , did job. give try may you

Specificity of Jackson vs Json OR "Why is this a good reply?" -

i'm pretty new jackson & json have worked already, using object mappers, defining own classes , working object oriented. recently, decided teach myself android programming , - in the process - query data 3rd party webservice uses json encoding replies. 1 of replies confounds me. i query number of objects, , this: json: [ {"num":"2","total":"2"}, {"id":"1234", ...more fields...}, {"id":"1235", ...more fields...} ] this doesn't parse standard jackson approches, since, way read it, indicates start of array first element being of different type of following elements. unable model pojo allow standard jackson mapping. (and speaking, didn't think correct syntax) can still work around basic string editing, figure must have misunderstood something. pardon me if silly question. appreciate , i'm looking forward responses. edit 1: hot licks , confirmed self doubts =). can suggest ...