Posts

Showing posts from May, 2012

messaging - Looking for message broker with a REST API -

we provide queues service (similar amazon sqs ) application requires inside company. before reinventing wheel we're looking product complies with: scales horizontally high availability on performance simple queue rest api (publish, deque, ack, nack) on advanced features backgrounds: use java/groovy , have experience in rabbitmq , activemq open product/language. i'd appreciate experience, product or broker adapter suggestion. first disclaimer - experience around sonicmq, activemq, , tibcorv. saw question opportunity spend time investigating rabbitmq has offer, have not used in anger date. here's information (propaganda?) came across rabbitmq... scales horizontally ( http://www.rabbitmq.com/distributed.html ) tries hard high availability ( http://www.rabbitmq.com/ha.html ) has experimental plugin called rabbitmq-json-rpc-channel allows send amqp json on http might meet rest api requirements https://github.com/rabbitmq/rabbitmq-jsonrpc-channe

Need to show and hide a div by clicking the same button in jquery -

i'm new @ query , simple : ) right it's setup show popup div when click on details button, works fine. i'm trying figure out how can hide popup div if user clicks again on same details button. appreciated! <script type="text/javascript"> $(document).ready(function() { $(".details").click(function() { $(this).parents('h1').next('.popup').fadein(1000); }); }); </script> <h1>we together<span class="details">details</span></h1> <div class="popup"> <ul> <li>852</li><!--square foot goes here--> <li>2</li><!--bedrooms goes here--> <li>1</li><!--bathrooms goes here--> <li>$134,900</li><!--price goes here-->

python - Grouping django objects using QuerySet API by shared text tags using two models with ForeignKey relationship -

hi trying write django webapp sits on top of legacy database , cannot control model fields , achieve functionality using new models. i have many documents user given comma-separated-tags . want group "related" documents based on shared tags. # model express legacy table class document(models.model): id = models.bigintegerfield(primary_key= true) metadata_id = models.charfield(max_length=384) tags_as_csv = models.textfield() # created new model tag_text extracted tags_as_csv class tagdb(models.model): tagid = models.bigintegerfield(primary_key=true) referencing_document = models.foreignkey(document) tag_text = models.textfield(blank=true) so document contain: document : id = 1 , metadata_id = "a1ee3df3600c6f77a6e851781f7e70c6" , tags_as_csv = "raw-data , high temperature , important" the tagdb have entries such as id , referencing_document , tag_text 1 , 1 , "raw-data" 2 , 1 , "high temperature&q

Start navigation or maps application on Windows Mobile -

is there way start maps or navigation application programmatically on windows mobile (6.5)? i looking similar android can pass location encoded uri view , system automatically start whatever application can handle uri. intent = new intent(intent.action_view, uri.parse("google.navigation:q=" + mlat + "," + mlon)); i.setflags(intent.flag_activity_new_task); startactivity(i); is there way similar in windows mobile? i have device both google maps , telenav gps installed, don't know how start either of them programmatically or how pass arguments. thanks information. as far google maps, should have start web browser right url. the trick find appropriate browser http://groups.google.com/a/googleproductforums.com/forum/#!category-topic/maps/google-maps-for-mobile/ueobwm2cndy

java - How do I get the default views for a ListView Section Headers and items? -

i want replicate list of sidebar/action bar dropdown in gmail--namely, nice all-cap section headers , items faded number on right. know need create own spinneradapter, i've started. i'm stuck how these standard views , put desired text in right sub-views (with guess view.findviewbyid ). can point me in right direction? public view getdropdownview(int position, view convertview, viewgroup parent) { context context = parent.getcontext(); object item = getitem(position); layoutinflater inflater = (layoutinflater)context.getsystemservice (context.layout_inflater_service); if (item instanceof string) { string headertext = (string) item; // todo: inflate ics section header view, // populate headertext, , return } else { listitem listitem = (listitem) item; // todo: inflate ics text/number view, populate // listitem.gettext()/getnumber() , return } } here's visual reference

c++ - Convert radians to degrees like Google -

im trying convert radians degrees, im not getting same results google calculator , pi defined dosent output number. if type in google search: (1 * 180) / 3.14159265 57.2957796 , program outputting: 57.2958 , if type in google search pi get: 3.14159265 , mine dosent output rest, output: 3.14159 my code is: #include <iostream> #define show(x) cout << # x " = " << (x) << endl using namespace std; double pi_test = 3.14159265; float radian_to_degree(double enter) { double pi = 3.14159265; float degrees = (enter * 180) / pi; return degrees; } int main (int argc, char * const argv[]) { show( radian_to_degree(1) ); // 57.2958 not 57.2957795 google, why? show( pi_test ); // output 3.14159' not 3.14159265, why? return 0; } please me fix this, wrong? example? as stated here , may cout in c++ rounding number before displaying it. try this: #define show(x) cout << setprecision(some_number) << #

MAMP localhost not working -

i have problem mamp, when try , visit url such http://localhost/discoversolar not work. however if visit http://streetcrime/discoversolar works. may have set alias or have no idea how or did this. can point me in direction of changing localhost works? i have looked in /etc/hosts , /applications/mamp/conf/apache/httpd.conf , /applications/mamp/conf/apache/extra/httpd-vhosts.conf failed find anything. in /applications/mamp/conf/apache/httpd.conf states servername localhost:80 thanks help! i going through issue. couldn't localhost populate , remembered editing hosts file in /etc/hosts .. i had commented following out: 127.0.0.1 localhost 255.255.255.255 broadcasthost ::1 localhost fe80::1%lo0 localhost add host file , should work :) hope helps! regards! update: mamp works via port 8888 .. try http://locahost:8888

encoding - How can I use swedish letters with json_encode() in PHP? -

i have array this, json encode: $regulararray = array( array( "label" => "hello world", "value" => 1 ), array( "label" => "hej världen", "value" => 2 ) ); $jsonarray = json_encode( $regulararray ); ("hej världen" means hello world in swedish) when print $jsonarray this: [{"label":"hello world","value":1},{"label":null,"value":2}] why label null second item in array? know has word "världen" since contains non-standard letter. how can around this? json_encode function works utf-8 encoded data. may change input array data utf-8. encode input array data using utf8_encode , decode whenever need data using utf8_decode <?php $regulararray = array( array( "label" => "hello world", "value" => 1 ), array( "label" => &

bash - Print only parts that match regex -

echo "a b _c d _e f" | sed 's/[ ]*_[a-z]\+//g' the result a b d f . now, how can turn around, , print _c _e , while assuming nothing rest of line? if question "how can print substrings match specific regular expression using sed ?" hard achieve (and not obvious solution). grep more helpful in case: $> echo "a b _c d _e f" | grep -o -p "(\ *_[a-z]+)" _c _e and finally $> echo `echo "a b _c d _e f" | grep -o -p "(\ *_[a-z]+)"` _c _e

c++ Initialising 2 different iterators in a for loop -

possible duplicate: can declare variables of different types in initialization of loop? i'd have loop in c++ constructs 2 different kinds of vector iterator in initialisation. here rough idea of like: std::vector<double> dubvec; std::vector<int> intvec; double result = 0; dubvec.push_back(3.14); intvec.push_back(1); typedef std::vector<int>::iterator intiter; typedef std::vector<double>::iterator dubiter; (intiter = intvec.begin(), dubiter j = dubvec.begin(); != intvec.end(); ++i, ++j) { result += (*i) * (*j); } anyone know standard in situation? can't use vector of double intvec because i'm looking general solution. [i.e. might have function f takes int double , calculate f(*i) * (*j)] you declare std::pair first , second iterator types: for (std::pair<intiter, dubiter> i(intvec.begin(), dubvec.begin()); i.first != intvec.end() /* && i.second != dubvec.end() */; ++i.first, ++i.second

Find lowest array from attr and do action with jQuery -

<li data-meter='2231'> <img src="http://placehold.it/100x100/"> </li> <li data-meter='0'> <img src="http://placehold.it/100x100/000"> </li> <li data-meter='622'> <img src="http://placehold.it/100x100/000"> </li> how can use $("li").attr('data-meter'); , find lowest action ? http://jsfiddle.net/4pmzh/ using min on array john resig try : $(document).ready(function(){ // function min value in array array.min = function( array ){ return math.min.apply( math, array ); }; var meter= $('li').map(function() { return $(this).data('meter'); }).get(); // alert minimum value alert("min meter: " + array.min(meter)); // or jquery object $('li[data-meter="'+array.min(meter)+'"]') }); docs .data() , working example

c# - How the property isCompleted of IAsyncResult is updated? -

when call method asynchronously (using pattern beginxxx/endxxx), iasyncresult result after calling beginxxx. how property "iscompleted" (in returning result variable) updated if neither method beginxxxx or endxxx have reference result variable? ex: // create delegate. asyncmethodcaller caller = new asyncmethodcaller(ad.testmethod); // initiate asychronous call. iasyncresult result = caller.begininvoke(3000, out threadid, null, null); // poll while simulating work. while(result.iscompleted == false) { thread.sleep(250); console.write("."); } begininvoke returning iasyncresult have reference it. internally created , sent you. for example, beginread in filestream creates filestreamasyncresult , returns it: private unsafe filestreamasyncresult beginreadcore(byte[] bytes, int offset, int numbytes, asynccallback usercallback, object stateobject, int numbufferedbytesread) { nativeoverlapped* overlappedptr; filestreamasyncresult a

Android - Intent "putExtra" -

i have next code: ´ arraylist<integer> vc = new arraylist<integer>; vc.add(1); vc.add(2); intent myintent = new intent(class1.this, class2.class); myintent.putintegerarraylistextra("key", vc); ´ class2 receive correctly arraylist, but... after use next code: (basically same) ´ arraylist<integer> vc = new arraylist<integer>; vc.add(10); vc.add(20); intent myintent = new intent(class1.this, class2.class); myintent.putintegerarraylistextra("key", vc); ´ my second class received again first arraylist 1 , 2 values any idea? i think problem not instantiating arraylist arraylist<integer> vc = new arraylist<integer>(); using old values

wpf - 2 elements in a grid cell -

i replace dynamically label dropdownlist , checkbox in cell in grid this private sub replaceuielementingrid(byval newuielement uielement, byval uielementtoreplace uielement, byval gridtoaddnewuielement grid) if gridtoaddnewuielement.children.contains(uielementtoreplace) grid.setrow(newuielement, grid.getrow(uielementtoreplace)) grid.setcolumn(newuielement, grid.getcolumn(uielementtoreplace)) dim pos integer = gridtoaddnewuielement.children.indexof(uielementtoreplace) gridtoaddnewuielement.children.removeat(pos) gridtoaddnewuielement.children.add(newuielement) try dim label label = directcast(uielementtoreplace, label) if (label.name.contains("activity")) dim checkbox checkbox checkbox = new checkbox() checkbox.content = "direction" checkbox.horizontalalignment = window

java - How do I instruct ArrayAdapter to redraw all its elements? -

i have list of items in (subclass of) arrayadapter, , when 1 of items in arrayadapter changed, need update view. (for context, bulk pricing model, more things buy, cheaper else gets, , want update price of when add cart) from reading documentation, expected notifydatasetchanged() trick, isn't doing want. should doing? as requested, here getview function. totalprice() method of orderchoice 1 changes depending on else selected. @override public view getview(int position, view convertview, final viewgroup parent){ final editingorderchoiceadapter adapter = this; view choiceview = convertview; if (choiceview == null){ layoutinflater choiceviewinflater = (layoutinflater)getcontext().getsystemservice(context.layout_inflater_service); choiceview = choiceviewinflater.inflate(r.layout.order_choice_row, null); } final orderchoice orderchoice = choices.get(position); if (orderchoice != null){ textview choicename = (textview)choiceview

c# - Change Color For Parts of an Image -

i trying find solution allow me change color parts of image. for example lets picture of chair. chair can have different frame or cushion colors. intend let users select frame or cushion , update image. can upload 1 chair image. any idea appreciated! detecting parts of image modified detecting objects on images programatically not simplet thing ;). suppose 1 of solutions problem suggested collin o'dell in comment question. suggested use few images manually separated parts of image want recolor. then, can compose final image few different layers. however, can keep main image objects , manually make additional images, keep masks of objects (i.e. white pixels in places object is). can check pixels should recolored. allow paint directly on 1 image , avoid compositing. calculating color when want recolor photograph, want able keep shading effects etc. rather covering same solid color. in order achieve this, can use hsv color space instead of rgb . use metho

security - Modifing CheckAccessCore(ctx) to permit WCF Help pages w/o authentication -

i need apply different set of security policies "help" urls on wcf service. how can full url of wcf service.. namely session or session.svc ? http://localhost:62302/session.svc/help http://localhost:62302/session.svc/help/operations/getsession http://localhost:62302/session/help http://localhost:62302/session/help/operations/getsession since security-related, need vet come against community. the author here suggests check if string ends in "help" , blindly permit query (which incorrect) code snip public class apikeyauthorization : serviceauthorizationmanager { protected override bool checkaccesscore(operationcontext operationcontext) { if (this.ishelppage(operationcontext.requestcontext.requestmessage) || isvalidapikey(operationcontext)) { return true; } else { string key = getapikey(operationcontext); // send html reply createerrorreply(operationcontex

JavaScript / jQuery setting a content to <div> not sticking after postback -

this code: <asp:button id="btnsave" runat="server" onclick="save" cssclass="stylizedbutton" resourcekey="btnsave" /> <div id="lbltot"></div> javascript code: $(document).ready(function() { $("#<%= btnsave.clientid %>").click(function() { var functionreturn = true; var focuselement = null; var tot = $("<%= lbltotal.clientid %>").val(); var txt1 = $("<%= txt1.clientid %>").val(); var txt2 = $("<%= txt2.clientid %>").val(); var txt3 = $("<%= txt3.clientid %>").val(); var txt4 = $("<%= txt4.clientid %>").val(); var cal = parseint(txt1) + parseint(txt2) + parseint(txt3) + parseint(txt4); if (cal == 100) { return t

html - Select element not working inside nested divs -

my html is <div id="div1"> <div id="div2"></div> <div id="div3"> <div id="div4"> <select><several options></select> </div> </div> </div> </div> the div s nested , select element won't work. using css in external file, wanted ask if html layout, itself, cause problems. understanding ie6/7 can cause z-index issues, using chrome. if wants take time review css happily post it, wanted first see if answerable on own. edit here css. note, div#2 semi-transparent background. other divs supposed positioned on top of it. #div1{ width:100%; height:8em; position:relative; margin-top:3em; margin-bottom:3em; border-style:solid; border-width:thin; border-color:black; border-radius:4px; z-index:10; #div2{ width:80%; height:100%; position:absolute; margin-top:5%; left:0%; background-image:url(images/calenda

javascript - How to prevent JQuery script from repeating in a custom infinite scroll script -

i'm using latest jquery. problem if user scrolls fast script fires twice in row. if user scrolls @ normal speeds or slowly, script works normally. have js @ bottom of page. added timeout when calling function, wait timeout , repeats script twice. repeating doesn't happen time. have setting call function @ -10px of scroll height. also, attempt i've made put loading gif doesn't seem work, delay on loading gif. there way prevent happening? <body> <div class="contentholderwrap"></div> <div id="dataresult"></div> </body> <script type="text/javascript"> $(document).ready(function(){ function lastpostfunc(){ var endid = $(".contentholderwrap:last").attr("id"); if (endid != "1000000000000") { $.post("main.php?lastid="+$(".contentholderwrap:last").attr("id"), function(data) {

algorithm - Matlab image analysis, trying to detect direction of movement -

Image
i'm trying solve problem i'm facing in detecting direction of movement of image. so have video i'm trying analyze, composed of contracting objects (continuaslly shrink , expand) , i'm trying able detect if current frame of move shrinked or expand ! here example of 2 frames 1 objects there expanded , other shrinked note: can't see deference when on top of each other, try save , view 1 after other on computer. so there way can detect direction of movement in video ? (inward of outward ?) thanks lot this can solve "optical flow" has been studied several decades now. the classical method horn-schnuck http://en.wikipedia.org/wiki/horn%e2%80%93schunck_method can download here: http://www.mathworks.com/matlabcentral/fileexchange/22756-horn-schunck-optical-flow-method . it's fast not accurate way solve problem tends blur regions interested in detecting since minimizes l2 norm of gradients. here's got on images using horn-schnuck

c - How does const pointer arguments optimized when calling functions? -

how compilers optimizes theese 4 types of function definitions. there optimization done in sense of argument passing? int check_collision(const sdl_rect const *a,const sdl_rect const *b) { ... } int check_collision(sdl_rect const *a,sdl_rect const *b) { ... } int check_collision(const sdl_rect *a, sdl_rect const *b) { ... } int check_collision(sdl_rect *a, sdl_rect *b) { ... } and if matters, think preferable way of passing read arguments function in cases these argument might inefficent copy when calling funcion? use const in of these cases indicate purpose of usage more , writing more readable code, modern day compilers efficient , smart enough apply required optimization's whether pass function argument const or not. in short, use const in case readability & preventing usage errors, & not compiler optimization, compiler smart enough take care of that.

django - Internal Server error while using Python OpenId with Google Authentication -

i have installed askbot.org on local machine , when tri use google openid, following error. here full apache log. (i have replaced hex strings) http://bit.ly/apache_log can explain me problem ? from log, seems big issue: [wed mar 07 22:58:13 2012] [error] received "invalidate_handle" server from answer question on invalidate_handle , looks bug in "relying party". double-check configuration.

java - Appearing a Notification for each specific Time android Application -

how can program variable in android application causes appearance of notification each 8 minutes, , after 2 hour should stop ! in advance , you should use service http://www.vogella.de/articles/androidservices/article.html

actionscript 3 - AS3 listing references of an object -

does know if it's possible list references object has in actionscript3 (e.g. listeners, children etc)? i'm trying clear object memory ready garbage collection reason it's hanging around. thanks. if have flash builder, profiling app should give pretty need. otherwise,you should able make simple profiler of own using flash.sampler.* api.

c# - Inherits from DataGridView with custom properties -

i've written own grid inherits datagridview class , has custom properties , columns. like : public class foo : datagridview { private system.windows.forms.datagridviewtextboxcolumn c1; public foo() { initializeclass(); } void initializeclass() { this.autogeneratecolumns = false; c1 = new datagridviewtextboxcolumn(); this.c1.datapropertyname = "c1"; this.c1.headertext = "column 1"; this.c1.name = "c1"; } } the program runs well, visual studio creating mess code! in initializecomponent() vistual studio creates again datagridviewcolumns properties :s is there way avoid behavior. thnks! update : autogeneratecolumns set false you either create columns @ runtime, think checking system.componentmodel.licensemanager.usagemode works, or hide columns property designerserializationvisibility attribute.

Inserting into two table simultaneously using hibernate save -

i have dto reference table table_1 , have has element collection table_2 using @collectiontable(name=" _ ", joincolumns=@joincolumn(name=" _ __ ")) i defined way because when updating table_1 want update table_2 too. i defined procedures , correctly. can me in regard, thankful. the usual way use @onetomany ( as described in documentation ). if add elements collection, hibernate automatically persist these if save table_1

osgi - Using Felix within a Servlet 3.0 server (like Tomcat 7) -

i'm converting application osgi environment. application uses asynchronous servlets (so servlet 3.0.0+) detach incoming requests thread, , queue requests. as far can see, servlet bridged felix packages use servlet 2.x, can not use servlet 3.0 specific stuff. is true? there way use asynchronous servlets in felix? if not, planned? i've tried both felix , equinox. felix turned out pretty easy, it's matter of injecting servlet 3.0 package framework, on there aren't servlet 2.0 dependencies. note examples on felix site aren't date. anyway: i've shared example on github, maybe it's useful somebody: https://github.com/flyaruu/felix-bridge

ios - Can a ViewController presented modally use the NavigationController's toolbar -

i'm trying present modally uitableviewcontroller view controller in navigation controller hierarchy. modal view should display toolbar. can navigation controller's managed toolbar used in view controllers presented modally or should implement own toolbar these? if present controller modally [self.navigationcontroller presentmodalviewcontroller:filtervc animated:yes]; no toolbar displayed. if pushed controller with: [self.navigationcontroller pushviewcontroller:filtervc animated:yes]; toolbar displayed. here method run init method of uitableviewcontroller. -(void)configuretoolbar { [self.navigationcontroller settoolbarhidden:no animated:yes]; //toolbaritem done uibarbuttonitem *doneitem = [[uibarbuttonitem alloc] initwithbarbuttonsystemitem:uibarbuttonsystemitemdone target:self action:@sele

licensing - MySQL licencing -

can use mysql community edition in commercial product free? product not open source. need acquire kind of license or not, in order use mysql? thanks mysql licensed under gpl linking exception. means can link own program against mysql libs without licensing under gpl well. but have obey other terms of gpl, such providing license info mysql, providing source code of (and more, see gpl license text ). depending on product can either acceptable or want buy license rid of gpl requirements.

regex - Replace a word which contains a $ character in PHP -

i'm having issues replacing tag within message tag begins $ character. here's code i'm trying use: $tag = '$tag'; $message = '..text $tagd d$tag $tag text..'; $pattern = '/\b\\'.$tag.'\b/'; echo $pattern."<br/>"; echo preg_replace($pattern, "replaced", $message); output: /\b\$tag\b/ ..text $tagd dreplaced $tag text.. i want replace last occurance of $tag since it's 1 not obstructed additional characters. keeps replacing 2nd 1 no matter try. some variations i've tried: skipping $tag variable string concatination $message = '..text $tagd d$tag $tag text..'; $pattern = '/\b\$tag\b/'; echo $pattern."<br/>"; echo preg_replace($pattern, "replaced", $message); output: /\b\$tag\b/ ..text $tagd dreplaced $tag text.. removing backslash before $ $message = '..text $tagd d$tag $tag text..'; $pattern = '/\b$tag\b/'; echo $pattern."<

linux - C++ clean pointer arithmetic -

whats cleanest way perform pointer arithmetic in c++? trying add n bytes address. int *foo; foo = static_cast<int*> (static_cast<unsigned int>(foo) + sizeof(t)) later recast , use foo differently char* somestr = reinterpret_cast<char*>(foo) is enough? understand pointer implementation dosent guarantee pointers ( char* , int* ) implemented of same size. not sure if int* (should foo* ) , using unsigned int math cleanest solution. also, has work on both 32 , 64 bit. nevermind why im doing this. not unusual though. run issue anytime youre working stream (or bytepool) of data interpreted dynamically different types. the cleanest way of doing pointer arithmetic not via numbers of bytes, typed. don’t treat int array else, offset directly: int* next = foo + n; or: int* next = &foo[n]; both superior casting solution. in cases work on byte buffer, use char* , not (never!) int* . is, char* buffer = get_the_buffer(); // pointer arithmeti

Keeping integrity between two separate data stores during backups (MySQL and MongoDB) -

i have application designed relational data sits , fits naturally mysql. have other data has evolving schema , doesn't have relational data, figured natural way store data in mongodb document. issue here 1 of documents references mysql primary id. far has worked without issues. concern when production traffic comes in , start working backups, there might inconsistency when document changes, might not point correct id in mysql database. way guarantee degree shutdown application , take backups, doesn't make sense. there has other people deploy similar strategy. best way ensure data integrity between 2 data stores, particularly during backups? mysql perspective all mysql data have use innodb. make snapshot of mysql data follows: mysqldump_options="--single-transaction --routines --triggers" mysqldump -u... -p... ${mysqldump_options} --all-databases > mysqldata.sql this create clean point-in-time snapshot of mysql data single transaction. for ins

javascript - Turn off Bootstrap's CSS3 transitions on progress bars -

anyone know way disable bootstrap's css3 transitions on progress bars? i'm updating them via javascript/jquery , don't want them doing animating. this looked promising couldn't work: turn off css3 animation jquery? info on progress bars: http://twitter.github.com/bootstrap/components.html#progress you can turn off transition effects setting css transition rule none , so: .progress .bar { -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none; transition: none; }​

javascript - Rangy Modules Not Supported In Chrome? -

i trying use rangy in chrome, , seems serializer , wrappedselection modules not supported chrome. unsure if did not init() rangy properly, or if did other mistake. ran console.log(rangy.modules) how found out serializer , wrappedselection unsupported. i have created empty chrome extention, , in manifest.js included 7 required rangy js files, , jquery.js. below contents of script.js: function rangytest() { rangy.init(); console.log(rangy.modules); var value; $("body").append( "<input type=\"button\" id=\"serializebutton\" value=\"serialize selection\">" ); $("body").append( "<input type=\"button\" id=\"deserializebutton\" value=\"restore selection\">" ); $('#serializebutton').click(function() { value = rangy.serializeselection(); }); $('#deserializebutton').click(function() { rangy.deserializeselectio

windows phone 7 - Unable to create folder and display Image using WP7 Emulator -

i new wp7 development trying simple example ie.. i have image control , 2 buttons 1 loading image , displaying in image control , other saving image new folder need create. i have below code , not getting errors problem unable create directory , save existed image folder. i unable see directory image after saving it. can see folder in emulator(or)it possible can see created directory on windows phone? imports system.io imports microsoft.phone.tasks imports system.io.isolatedstorage imports system.windows.media.imaging partial public class page1 inherits phoneapplicationpage public sub new() initializecomponent() photochoosertask = new photochoosertask() addhandler photochoosertask.completed, addressof photochoosertask_completed end sub dim photochoosertask photochoosertask private sub photochoosertask_completed(sender object, e photoresult) dim bmp system.windows.media.imaging.bitmapimage = new system.windows.media.ima

javascript - Why this code is valid: "(1,eval)('this')" -

why next code valid javascript code? var global = (1,eval)('this'); alert(global); that's because comma operator returns second operand (and evaluates both). the code in question equivalent to: 1; var global = eval('this'); alert(global);

php doesn't disable functions -

i call php commandline, -c argument load php.ini file, this: php -c my_ini_file.ini test.php so in disabled_functions added echo function. in test.php, echo works, , don't know why. phpinfo() shows echo disabled function. echo not function, built-in command. cannot disabled. echo() not function (it language construct), not required use parentheses it. echo() (unlike other language constructs) not behave function, cannot used in context of function. additionally, if want pass more 1 parameter echo(), parameters must not enclosed within parentheses.

vba - How do you split part of an excel cell into another cell? -

there's list of cells looks [a-z ]* [1-9.]* . want split numric part adjacent cell. how can this? for formula approach, try extract numeric part of a1: =mid(a1,min(find({0,1,2,3,4,5,6,7,8,9},a1&"0123456789")),255)

ruby on rails - Devise confirmable, how to resend a confirmation email on click? -

i'm using devise confirmable. want give user link click , resend confirmation email. problem is, when user clicks link, isn't going devise controller. there i'm missing in routes.rb file? here setup: routes.rb devise_for :users, :controllers => { :registrations => "registrations", :sessions => "sessions", :omniauth_callbacks => "authentications" } user.rb devise :omniauthable, :database_authenticatable, :registerable, :confirmable, :recoverable, :rememberable, :trackable, :validatable the view: <a href="/users/confirmation/new" data-remote="true" data-method="post">resend confirmation</a> thanks as see on https://github.com/plataformatec/devise/blob/master/app/controllers/devise/confirmations_controller.rb#l2 , http method confirmation#new get, not post. try remove 'data-method="post"' , see if works.

javascript - how to put ... if string length is over 12 -

facebook_user_name=facebook_info[0].url[j]; if(facebook_user_name.length>12) { } how put ... if string length on 12. example, name aaaaaaaa bbbbbbb result should aaaaaaaa bbb... thank in advance. var substring = facebook_user_name.substr(0, 12) + '...';

Fibonacci numbers with memoization runs slow in Python? -

def fib(n): if n == 1: return 0 if n == 2: return 1 return fib(n-2) + fib(n-1) def memo(f): cache = {} def memoized(n): if n not in cache: cache[n] = f(n) return cache[n] return memoized fib1 = memo(fib) this code runs slow on laptop, if change name fib1 fib, works fine...anyone know reason ? thanks! fib recurses fib , not fib1 . if memoized version has different name won't used.

mmap - Reading in a huge matrix from file -

i have huuugee matrix (500,000 * 98 floats) in file on disk, , need perform inverse (or pseudo-inverse more precise) on matrix. how read in file? if use mmap(), performance opposed using fread()? p.s.: homework problem. please not post code. guidance , comments great!

sql - MySQL regexp much slow than like -

this question has answer here: regexp performance (compare “like” , “=”) 3 answers select data test col regexp "asdf_[0-9]+" limit 1 ...1 row in set (1 min 43.12 sec) select data test col "asdf_%" limit 1 ...1 row in set (0.01 sec) regexp can give me exact result, have filter data if use like sql. there way improve? btw: test has 2 million rows , grow up. try changing regexp string "^asdf_[0-9]+" . like anchored (ie like 'asdf_%' says "a string starting asdf_"), whereas regexp not ( regexp 'asdf_[0-9]+' looks anywhere within string). note doing regexp 'asdf_[0-9]+' saying like '%asdf_%' . i think regexp still bit slower like , start of line anchor speed up.

Listing information about all database files in SQL Server -

is possible list information files (mdf/ldf) of databases on sql server? i'd list showing database using files on local disk. what tried: exec sp_databases databases select * sys.databases shows lot of information each database - unfortunately doesn't show files used each database. select * sys.database_files shows mdf/ldf files of master database - not other databases you can use sys.master_files . contains row per file of database stored in master database. single, system-wide view.

cordova - Override Android Backbutton behavior only works on the first page with PhoneGap -

i using phonegap 1.5.0, jquery 1.7.1 , jquery mobile 1.0.1 , trying override backbutton in android stated here or here . document.addeventlistener("deviceready", ondeviceready, false); // phonegap loaded function ondeviceready() { console.log("phonegap ready!"); // waiting button document.addeventlistener("backbutton", handlebackbutton, false); } // handle button function handlebackbutton() { console.log("back button pressed!"); navigator.app.exitapp(); } but works on first page of app. after changing different page backbutton nothing @ all. app consists of tabview this: <body> <div data-role="page" id="pilottab"> <div data-role="header"> <h1>pilot</h1> </div> <div data-role="content" id="pilotcontent"> content here ;) </div> <div data-role="footer" data-position="fixed"> <

javascript - Calling a function and pass it a json object -

Image
i have json object named data below and have function denomination in string below test name of function call , pass json object data. here test function: test = function (data) { alert('i test function'); } i try: eval(func(data)); it doesn't work. any idea? thanks. while eval() 1 possible solution, awful. instead, interrogate window find function want , run there: function test() { alert("test") } var func = $("#confirm-remove").data("success"); var data = {}; // object var fn = window[func]; if (typeof fn === 'function') { fn(data); } example fiddle this assumes function has global scope.

c - Getting the environment of a process running under a different user -

assume have process pid 1234 running in background under user a. if run following program user a, succeeds. if run user b, fails open: permission denied . this makes sense, environ file owned user , has read permission a. if make program set-user-id user , run user b, fails read: permission denied . doesn't seem happen regular file having same permissions. doesn't happen if root. any ideas why? there other way environment of process works around issue? #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> int main(int argc, const char *argv[]) { unsigned char ch = 0; int fd = -1; int read_result = -1; setresuid(geteuid(), geteuid(), geteuid()); fd = open("/proc/1234/environ", o_rdonly); if (-1 == fd) { perror("open"); return exit_failure; } read_result = read(fd, &ch, 1); if (-1 == read_result) { perror("read");

c - Mutual exclusion isn't exclusive -

i have following code runs in 2 threads started init call main thread. 1 writing device, 1 reading. app called other threads add items queues. pop_queue handles locking, push_queue . whenever modify req r , lock it's mutex. q->process function pointer 1 of either write_sector , read_setor . need guard against simultaneous calls 2 function pointers, i'm using mutex on actual process call, not working. according text program, making parallel calls process functions. how possible given lock immediatly before , unlock afterwards? the following error valgrind --tool=helgrind might help? ==3850== possible data race during read of size 4 @ 0xbea57efc thread #2 ==3850== @ 0x804a290: request_handler (diskdriver.c:239) line 239 r->state = q->process(*device, &r->sd) +1 void * request_handler(void *arg) { req *r; queue *q = arg; int writing = !strcmp(q->name, "write"); for(;;) { /* * wait request */

locking - Use Android Pattern Lock -

is there way of using excisting pattern lock or password android security, , "modify" each time pattern/password have been drawned wrong 5. time show toast on screen ? or have create own pattern/password application ? you might able implement deviceadminreceiver from it's description should notified of failed password attempts it's not clear description if includes lock screen attempts. if did work service or might able launch toast though. [edit] found better resource

Why would I want to use java.io.Console over standard streams? -

i realize may duplicate question, such as, why use java.io.console? . however, wanted more detailed answer (pros/cons, applications, more). forgive me if misunderstanding this. ran program using eclipse , received error message "no console", let go , ran via terminal instead. however, little unclear why console object doing (i think it's because returns null, wanted more detailed answer). various reads, seems various ides such netbeans , eclipse haven't "implemented" properly. leads me question, , since first time seeing java.io.console , why want use on standard streams? examples applications using console appreciated , preferred! programs written interactive shells in mind provide lot of conveniences command line users tab completion history tracking password input secure against shoulder surfers colored , formatted output using preferred pager paging text console allows java programs invoked via command line present user-exper

tabular - Displaying tables in C++ console window -

cout<<" name\t" <<"cat\t" <<"barcode\t" <<"price\t" <<"manufa\t" <<"stock\t" <<"sold\t" <<"exdate\t " <<"disc"<<endl; (unsigned int i=0; < _storage.size(); i++) { cout <<i <<":"; _storage[i]->showdata(); cout<<endl; } i trying display data in aligned manner.i using `t` character result in misalignment if data in 1 of variable long. how display data in table form in c++? you can use setfill , setw set fill char , width of columns. problem going have limit columns right.

c++ - Rendering 3D Models With Textures That Have Alpha In OpenGL -

Image
so im trying figure out best way render 3d model in opengl when of textures applied have alpha channels. when have depth buffer enabled, , start drawing triangles in 3d model, if draws triangle in front of triangle in model, not render triangle when gets it. problem when front triangle has alpha transparency, , should able seen through triangle behind it, triangle behind still not rendered. disabling depth buffer eliminates problem, creates obvious issue if triangle opaque, still render triangles behind on top if rendered after. for example, trying render pine tree cones stacked on top of each other have transparent base. following picture shows problem arises when depth buffer enabled: you can see how can still see outline of transparent triangles. the next picture shows looks when depth buffer disabled. here can see how of triangles on of tree being rendered in front of rest of tree. any ideas how address issue, , render pine tree properly? p.s. using shaders

json - How to Bind jqGrid with asmx webservice C# -

please need in how bind jqgrid asmx webservice c# , found topics in how convert asmx webservice json it's not clear me regards first of should define webmethod provide data jqgrid. if plan implement server side sorting , paging webmethod should have @ least following parameters public jqgriddata testmethod (int page, int rows, string sidx, string sord) where jqgriddata class defined example like public class tablerow { public int id { get; set; } public list<string> cell { get; set; } } public class jqgriddata { public int total { get; set; } public int page { get; set; } public int records { get; set; } public list<tablerow> rows { get; set; } } there other different options how 1 can fill grid, it's first important understand @ least 1 way. it's important, return json data web method you don't need convert returned data manually json . need return object data , asmx web service serialize object xml or json

php - Generating unique filename -

i want generate unique filename uploaded files. should 5 characters in length, , have following characters only: abcdefghijklmnopqrstuvwxyz0123456789 . code: $chars = 'abcdefghijklmnopqrstuvwxyz0123456789'; $length = 5; $filename = ''; for($i = 0; $i < $length; $i++) { $filename += $chars[mt_rand(0, 36)]; } echo $filename; but end 1 or 2 character long integers, never string characters. if run code: $chars = 'abcdefghijklmnopqrstuvwxyz0123456789'; $length = 5; $filename = ''; for($i = 0; $i < $length; $i++) { echo $chars[mt_rand(0, 36)]; } it works fine, , following output: 8iwzf . what doing wrong here? thanks! you adding (+=). want concatenate string using dot. $filename .= $chars[mt_rand(0, 36)];

Facebook chat on android with XMPP -

what way correctly establish connection facebook chat in android using xmpp? tried searching working sample code couldn't find 1 anywhere... thanks you should first start xmpp library work on android. asmack (based on popular java smack library seems best choice. should able follow tutorial library choose, , enter in settings facebook's servers.

php - Cross-domain AJAX request error on HTTP 200 -

i'm writing basic facebook app, i'm encountering issue cross-domain ajax requests (using jquery). i've written proxy page make requests graph via curl i'm calling via ajax. can visit page in browser , see has correct output, requesting page via causes jquery fire error handler callback. so have 2 files: proxy, curl request <?php //do curl requests, manipulate data //return json print json_encode($data); ?> the facebook canvas, contains ajax call $.getjson("http://mydomain.com/proxy.php?get=stuff", function(json) { alert("success"); }) .error(function(err) { alert("err"); }); inspecting call firebug shows returns http code 200 ok , error handler fired, , no content returned. this happens whether set content-type: application/json or not . i have written json-returning apis in php before using ajax , never had trouble. what ca

twitter - How to send tweet from Google Chrome Extension? -

i following google oauth tutorial. , having trouble authorizing user. i sending user twitter authorization. chrome extension , there no callback. dont know how send tweet on behalf of user. how doing things: i have background page has code of authorizing user twitter. on time when user install extension, background page send user twitter authorization. authorization method getting called call back. dont know if having make tweet. now when user click on extension icon, popup.html appear. , on page want user send tweet. how? following code: manifest.json { "name": "tweetchrome", "version": "1.0", "description": "tweet chrome", "browser_action": { "default_icon": "images/share.png", "popup": "popup.html" }, "permissions": [ "tabs", "http://ajax.googleapis.com", "*://*.twitter.com/*", "clipboardwrite" ], "

php - Basic mysql optimizations -

i'm new mysql. hit scaling problem queries taking as 15 seconds solve on simulations when added 7k accounts. 7k isn't much. so, got few questions. what tradeoff between making 1 big query database (multiple joins reqd) , multiple smaller queries(which require no joins)? also, (this basic) select * work slower select <column> because more columns returned caller (php)? thanks.

java - Reading ints into a multidimensional array -

my problem occurs during loops read in values file scores array. program reads in , prints first 6 values or 2 lines of ints, arrayindexoutofboundsexception: 2 i have no idea why stopping there. if have j<1000, read 17 values. anyway, file i'm reading in below (wasn't sure formatting text file). any appreciated andy matt tom 3 2 3 4 4 5 3 3 2 2 2 2 2 4 2 2 3 2 4 4 5 2 3 3 4 3 5 3 3 6 2 2 5 3 3 3 3 3 2 3 2 4 3 2 6 3 4 3 2 3 2 2 2 2 50 52 62 public static void main( string args[] ) { try { if (args.length<1) { system.out.printf("\n...you must enter name of file\n"); system.exit(0); } scanner infile = new scanner ( new file(args[0]) ); int par= 3; int play= 18; string[] players= new string[play]; int k=0; int scores[][]= new int[play-1][par-1]; while(infile.hasnext()) { players[k]=i

Python - splitting a list then loop through to find an ip address -

i'm required analyse system log. i've been told should split list , iterate through find ip address. small part of log. there duplicate entries therefore must take notice of lines contain words "failed password root". jan 10 09:32:07 j4-be03 sshd[3876]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=218.241.173.35 user=root jan 10 09:32:09 j4-be03 sshd[3876]: failed password root 218.241.173.35 port 47084 ssh2 jan 10 09:32:17 j4-be03 sshd[3879]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=218.241.173.35 user=root jan 10 09:32:19 j4-be03 sshd[3879]: failed password root 218.241.173.35 port 47901 ssh2 jan 10 09:32:26 j4-be03 sshd[3881]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=218.241.173.35 user=root jan 10 09:32:29 j4-be03 sshd[3881]: failed password root 218.241.173.35 port 48652 ssh2 here code far, bit of psuedo code aswell.