Posts

Showing posts from February, 2013

javascript - Google Maps - 2 maps on the same page not working -

i need have 2 google maps on same page. however, reason, first map seems displayed. i've tried this topic without success, problem persists. my code looks this function initialize() { var mylatlng = new google.maps.latlng(41.560655,-8.386545); var mylatlng2 = new google.maps.latlng(41.560655,-8.386545); var mapoptions = { zoom: 5, center: mylatlng, maptypeid: google.maps.maptypeid.roadmap } var mapoptions2 = { zoom: 8, center: mylatlng2, maptypeid: google.maps.maptypeid.roadmap } var map = new google.maps.map(document.getelementbyid('map-canvas'), mapoptions); var map2 = new google.maps.map(document.getelementbyid('room-canvas'), mapoptions2); } and html <div class="g_12"> <div class="widget_header">

c++ - How do reference_wrapper and std::ref work? -

i trying understand how std::ref works. #include <functional> #include <iostream> template <class c> void func(c c){ c += 1; } int main(){ int x{3}; std::cout << x << std::endl; func(x); std::cout << x << std::endl; func(std::ref(x)); std::cout << x << std::endl; } output : 3 3 4 in code above, think template parameter c third function call instantiated std::reference_wrapper<int> . while reading the reference , noticed there no += operator in std::reference_wrapper<int> . then, how c += 1; valid? how c += 1; valid? because reference_wrapper<int> implicitly convertible int& via conversion operator; , implicit conversions considered operands if there no suitable overload operand type itself.

sql - Error converting datetime from character string -

insert restaurants_final (datefield) values ('01/01/2000') this query keeps coming conversion failed when converting datetime character string. method has worked seemlessly me years. doing wrong? datefield set datetime format. insert these dates literal in language neutral manner, using format yyyymmdd this: insert restaurants_final (datefield) values ('20000101')

c++ - How can I change my system colors to default? -

in c++ application wrongly changed system color: const int val = color_highlighttext; const colorref color = rgb(255,0,0); ::setsyscolors(1, &val, &color); how can restore backwards default settings? the documentation on setsyscolors() @ http://msdn.microsoft.com/en-us/library/windows/desktop/ms724940%28v=vs.85%29.aspx says "the new colors not saved when system terminates." rebooting colours back. there example of how copy of colors getsyscolors() before changing them setsyscolors(), , shows how restore colors.

c# - How to Toast Notification when win app is closed in WP8? -

i want implement toast , tile notifications. notification must meet criteria, such needs able run when app closed. example, birthday reminder can run in background when app closed. sample found: shelltoast toast = new shelltoast(); toast.title = "toast title: "; toast.content = "test"; toast.show(); the above example works when app running. here code: private void startperiodicagent() { // variable tracking enabled status of background agents app. agentsareenabled = true; // obtain reference period task, if 1 exists periodictask = scheduledactionservice.find(periodictaskname) periodictask; // if task exists , background agents enabled // application, must remove task , add again update // schedule if (periodictask != null) { removeagent(periodictaskname); } periodictask = new periodictask(periodictaskname); periodictask.expirationtime

debugging a fastcgi++ applocation -

i'm starting fastcgi++ , i'm little bit surprised couldn't find information how debug , trace it. how can done? mean not ide runs apache (or other web-server) start process , handle correctly. now i'm using qt creator on gentoo writing , compiling , apache view results

c# - Entity Framework Object Context per request in ASP.NET? -

is considered practice use single objectcontext per request? read these objects should short lived , not extremely costly instantiate make case appealing 1 of them per request? if yes, there patterns implement this? yes accepted approach have objectcontext/dbcontext lifetimes per httprequest. here's sample have provided in answer. hoewever, it's better leave these lifetime managements ioc library. famous ones castle windsor , autofac . update: dispose context, can use application_endrequest method in global.asax. following code not tested you'll idea: protected virtual void application_endrequest() { var key = "mydb_" + httpcontext.current.gethashcode().tostring("x") + thread.currentcontext.contextid.tostring(); var context = httpcontext.current.items[key] mydbcontext; if (context != null) { context.dispose(); } }

html - remove Link Navigation from calendar Date -

i want remove link date gets displayed in sharepoint calendar list. if use developer's tool, not see anchor tag on can apply css disable. must achieve through css itself. the code given below sharepoint: <tr class="ms-acal-summary-dayrow"> //tr has class <td date="5/12/2013" evtid="day">//td dont know how fetching value , entire td has link has removed. <div> <nobr> text -12 //this text "12"has link </nobr> </div> </td> </tr> text-12 has link want remove. how achieve through css? you can remove link using css .active { pointer-events: none; cursor: default; } http://jsfiddle.net/7eqjp/

R with xts subsetting: start date plus setting range -

while subsetting xts set range between 2 dates/times e.g. df["t08:00/t16:59"] or df["2012-12-12/2012-12-12"] i wanna set start date , special period: e.g 14 days. how solve problem, calculating 2nd external variable. or possible set range of subset? example: df["2012-12-12/14days.."] thanks! try this first(df["2012-12-12/"], "14 days")

Cassandra ttl on a row -

i know there ttls on columns in cassandra. possible set ttl on row? setting ttl on each column doesn't solve problem can seen in following usecase: at point process wants delete complete row ttl (let's row "a" ttl 1 week). replacing existing columns same content ttl of 1 week. but there may process running concurrently on row "a" inserts new columns or replaces existing ones without ttl because process can't know row deleted (it runs concurrently!). after 1 week columns of row "a" deleted because of ttl except these newly inserted ones. , want them deleted. so there or there cassandra support use case or have implement on own? kind regards stefan there no way of setting ttl on row in cassandra currently. ttls designed deleting individual columns when lifetime known when written. you achieve want delaying process - instead of wanting insert ttl of 1 week, run week later , delete row. row deletes have following semantic

How do you unit test formsets in Django? -

ok, need unit test view, more precise form in view . create such unit test. class viewtest(testcase): fixtures = ['fixture.json'] def setup(self): self.client = client() def test_company_create(self): post_data = { 'form-0-user': '', 'form-0-share': '', 'form-total_forms': 1, 'form-initial_forms': 0, 'form-max_num_forms': 10 } resp = self.client.post('/company/create/', post_data) self.assertformerror (resp, 'shareholder_formset', 'share', 'this field required.') self.assertformerror (resp, 'shareholder_formset', 'user', 'this field required.') ofcourse error attributeerror: 'shareholderformformset' object has no attribute 'fields' because formset has forms in it, not fields..... correct way test formset? that's fun

php - How to get variable from url for .js file? -

example: suppose current page url(window.location.href) http://example.com/page.html html page source code is... <html><head></head><body> <script src="http://example.com/script.js?user=ankit&ptid=18"></script> </body></html> now need use 'src' variables in script.js , script file script.js should return var a="ankit" var b="18" can use echo $_get in php? found here . if you're using jquery, should helpful. function geturlparameter(name) { return decodeuri( (regexp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1] ); } this javascript function return value in url of parameter pass it. in case, call with var = geturlparameter("user"); var b = geturlparameter("ptid"); edit: misinterpreted original version of question asking getting parameters .html page being loaded. tested solution, , not work wit

bash - Using single variable to pass in reference to multiple field variables in awk? -

i'd pass reference number of field variables awk , have print out value each variable each line without using loop. for example, i'd like: var=$1":"$3":"$4 echo "aa bb cc dd" | awk -v var=$var '{print var}' i output of "aa:cc:dd." when try as-is, output of $1":"$3":"$4. possible number of field variables in var without doing loop? var='$1":"$3":"$4' echo "aa bb cc dd" | awk "{print $var}" this pass variables want literal awk print format i.e echo "aa bb cc dd" | awk {print $1":"$3":"$4}

How to catch SQL::Parser errors in Perl -

i have update statement parsing sql::parser update scott.emp set ename='sct%',emp_date=to_date('04/16/2011 00:00:00', 'mm/dd/yyyy hh24:mi:ss'),empno='15645' dept=20 , ename in(select ename emp empno='1111'); but since to_date function cannot parsed sql::parser hence throws error: incomplete set clause! @ ./post_audit.pl line 173 incomplete set clause! @ ./post_audit.pl line 173 how catch such errors? eval trick? did not find proper documentation same. code parse sql statements: +12 use sql::parser; +34 $statement = "update scott.emp set ename='sct%',emp_date=to_date('04/16/2011 00:00:00', 'mm/dd/yyyy hh24:mi:ss'),empno='15645' dept=20 , ename in(select ename emp empno='1111')"; +172 $parser = sql::parser->new('anydata', {raiseerror=>1} ); +173 $parser->parse($statement); error thrown @ line 173 while parsing statement. i don'

fonts - Applying a style to a Delphi XE4 Firemonkey StringGrid cell at runtime -

i trying apply style xe4 fm stringgrid @ runtime, unable find correct syntax this. the stringgrid inherits 'textcellstyle' (the default) have created @ design time, , display cells in stringgrid according style. what ideally change colour of fonts in specific cells (negative=red, positive=green etc) @ runtime, cannot work out how this, unable access stylelookup @ cell level. please remember query relates tstringgrid, , not tgrid, our application requires allocate memory grid dynamically @ run-time, , easier stringgrid. any appreciated, , in advance. i have been attempting learn how tgrid, , mike sutton's have managed this. [see changing ttextcell background colour @ runtime xe4 background.] having managed right, attempted similar logic on tstringgrid , worked fine. stringgrid doesn't use grid1getvalue, hard-coded random numbers grid in formcreate. [in code below have style called textcellstyle; 'background' component of textcellstyle

sql server - Escaping colon in SQL DELETE LIKE -

i trying delete rows in second column contains hour 23:59:00. int datetime |1 | 2 | 125 2010-12-27 00:00:00 120 2011-12-27 00:00:00 84 2012-12-26 00:00:00 108 2013-12-26 00:00:00 139 2013-12-26 23:59:00 73 2014-12-26 00:00:00 140 2014-12-26 23:59:00 i have tried command delete date '%23:59:00' but isn't working. have escape colon or should find way of identifying rows? this should work: ...where datepart(hh, [date]) = 23 , datepart(mi, [date]) = 59 reference

tfs2010 - Where is the TFS 2010 API DLL Microsoft.TeamFoundation.Framework.Server.dll? -

this dll needed reference corresponding namespace microsoft.teamfoundation.framework.server . dll doesn't seem included either visual studio 2010 team explorer or visual studio 2010 team foundation server sdk. this file can copied server team foundation server 2010 installed in folder c:\program files\microsoft team foundation server 2010\application tier\web services\bin .

ruby - Pass arbitrary connection options to Farday -

i'm trying convert project have using excon faraday excon adapter, i'm not having luck. the issue need pass through arbitrary connection options excon api interfacing uses client side ssl certs authentication. to make connection straight excon using this: @connection = excon.new("some_url", client_cert: file.expand_path(@some_cert), client_key: file.expand_path(@some_key)) according faraday documention, should able this:s @connection = faraday::connection.new(url: "some_url", client_cert: file.expand_path(@some_cert), client_key: file.expand_path(@some_key)) |faraday| faraday.adapter :excon end when try (with 0.9 rc5 github), undefined method client_cert= error, leads me believe documentation out of date. know how pass arbitrary connection options through adapter? you have pass ssl options hash. should work: ssl_opts = { client_cert: file.expand_path(@some_cert), client_key: file.expand_path(@some_key) } @connection =

android - Activity lifecycle strange behavior in sleep mode (libGDX game) -

i have strange behavior of activity in libgdx game - when play game , press power button sending device sleep mode. i've added logs activity's callback methods , that's see: 05-14 16:32:51.694: i/bp(32656): onpause() 05-14 16:32:51.704: i/bp(32656): onstop() 05-14 16:32:51.854: i/bpapplication(32656): bpapplication.onconfigurationchanged() 05-14 16:32:51.854: i/bp(32656): bp.onconfigurationchanged() at point goes right way. further strange begins: 05-14 16:40:42.774: i/bp(32656): onrestart() 05-14 16:40:42.774: i/bp(32656): onstart() 05-14 16:40:43.064: i/bp(32656): onresume() 05-14 16:40:44.566: i/bp(32656): bp.onconfigurationchanged() 05-14 16:40:44.566: i/bpapplication(32656): bpapplication.onconfigurationchanged() 05-14 16:40:49.761: i/system.out(32656): screen resize w = 480, h=800 // libgdx callback 05-14 16:40:49.911: i/system.out(32656): game resumed... // libgdx callback 05-14 16:40:50.471: i/system.out(32656): screen resize w = 800, h=480 /

java - String formatting, how to give equal width to 'iiii' and 'wwww' -

i want make output of jconsole similar of table. concatenate strings form 'rows'. in order resemble real table (sub)strings form row should have equal physical length. something this: aaa aaa aaa bbb bbb bbb ccc ccc ccc i use following method set length of string. private string fillwithspace(string s){ if(s == null){ s = " null "; } while(s.length()<constant_length){ s = s + " "; } return s; } but not me if letters have different width. there clever way give iii , www same physical width? you should use monospaced font.

Why php print "b1" in such code -

this question has answer here: echo , print statement 4 answers <?php print("a")."b".print("с"); ?> result: сab1 why php print "b1" in code equates to: print("c").... output value "c" , return value of 1 indicate success print "a", concatenated "b", concatenated result of print("c") (which "1") giving cab1

angularjs - what is the difference between ngSwitch and ngInclude? -

what difference between ngswitch , nginclude? i need understand difference, can continue on project. does ngswitch hides dom elements? you may find v1.1.4 documentation more helpful (just ignore stuff animations if not using 1.1.4): ngswitch ngswitch conditionally adds/removes dom elements ( ng-show/hide alters css). nginclude can fetch partials/external html fragments. both create new child scopes prototypically inherit parent scopes. (a new child scope created each ng-switch-when/default .) you can use nginclude ngswitch : https://stackoverflow.com/a/12584774/215945 use nginclude when want (or can) reuse html fragments, such client ui ( https://stackoverflow.com/a/13005658/215945 ).

Spring MVC keep value of unexposed property model -

i have model class: public class user{ public string title; public string username; /* setter getter here */ public string tostring(){ /* output title , username */ } } controller : @requestmapping("/dummy") public class dummycontroller { private log = logger.getlogger(this.getclass().getname()); @requestmapping(value="binder") public string binderinput(model model){ userlogin userinit=userlogin.finduserlogin(1l); model.addattribute("userlogin",userinit); return "binderinput"; } @requestmapping(value="binderresult") public string binderresult(@modelattribute("userlogin") userlogin userlogin,bindingresult br){ log.debug("userlogin:"+userlogin); return "binderresult"; } } and views (jspx) binderinput: <form:form action="dummy/binderresult" method="post"

How to force a certain TLS version in a PHP stream context for the ssl:// transport? -

how can force tlsv1.0 in php stream context when trying access https url? i’m looking along lines of this: $context = stream_context_create( array( 'ssl' => array( 'protocol_version' => 'tls1', ), )); file_get_contents('https://example.com/test', false, $context); background actually i’m facing an issue in ubuntu 12.04 when working php’s soapclient . unfortunately, server i’m trying connect support sslv3.0/tlsv1.0 , fails on default tlsv1.1 negotiation. therefore i’d explicitly set protocol of ssl:// transport tlsv1.0. php 5.6+ users this new feature documented on php 5.6 openssl changes page . at time of writing this, php5.6 in beta1 , isn't overly useful. people of future - lucky you! the future upon us. php 5.6 thing , use should encouraged. aware deprecates used things mysql_* functions care should taken when upgrading. everyone else @toubsen correct in answer - isn't directly possib

Looking for script to delete iframe malware from linux server -

i'm looking script delete following iframe malware linux server: <iframe width="1px" height="1px" src="http://ishigo.sytes.net/openstat/appropriate/promise-ourselves.php" style="display:block;" ></iframe> it has infected hundreads of files on server on different websites. tried grep -rl ishigo.sytes.net * | sed 's/ /\ /g' | xargs sed -i 's/<iframe width="1px" height="1px" src="http://ishigo.sytes.net/openstat/appropriate/promise-ourselves.php" style="display:block;" ></iframe>//g' but outputs: sed: -e expression #1, char 49: unknown option `s' appreciate :) cheers dee unescape backslashes url in sed regex.

map - Android API1 signed key issue -

i have used android map api1 don't have option generate api key signed key. meanwhile api2 using fragment , have recode completely. there quick solution this. thanks in advance. you should try , use google maps android api v2 . if here , can see v1 deprecated , not supporting more.

javascript - Unable to run paper.js from .html file -

dear didn't find normal explanation decided ask help. want create paper.js project in html file. problem cannot connect them tried use var scope = new paper.paperscope(); scope.setup(mycanvas); but didn't work out. here code taken paper.js web site <!doctype html> <html> <head> <!-- load paper.js library --> <script type="text/javascript" src="paper.js"></script> <!-- define inlined javascript --> <script type="text/javascript"> // executed our code once dom ready. var scope = new paper.paperscope(); scope.setup(mycanvas); var mypath = new path(); mypath.strokecolor = 'black'; // function called whenever user // clicks mouse in view: function onmousedown(event) { // add segment path @ position of mouse: mypath.add(event.point); } </script> </head> <body> <canvas id="mycanvas" resize></canvas> </body>

android - Encrypt/Decrypt pdf file with Java -

i want encrypt/decrypt pdf file on android (but it's java common issue) i have code generate key : public static byte[] getrawkey(byte[] seed) throws exception { keygenerator kgen = keygenerator.getinstance("aes"); securerandom sr = securerandom.getinstance("sha1prng"); sr.setseed(seed); kgen.init(128, sr); secretkey skey = kgen.generatekey(); byte[] raw = skey.getencoded(); return raw; } my code write encrypted file : instream = new bufferedinputstream(conn.getinputstream()); outfile = new file(path + filename); outstream = new bufferedoutputstream(new fileoutputstream(outfile), 4096); byte[] data = new byte[4096]; string seed = "password"; byte[] rawkey = utils.getrawkey(seed.getbytes()); secretkeyspec skeyspec = new secretkeyspec(rawkey, "aes"); cipher cipher = cipher.getinstance("aes"); cipher.init(cipher.encrypt_mode, skeyspec); int bytesread = 0; while((bytesread = in

html - Javascript function not returning a value -

i have javascript function check value text box , if text box not blank outputs statement. text box take numeric value, want include numeric value output html. here html <br><label id="cancelphonelabel">1-800-555-1111</label> <br><label id="mdamountlabel">monthly donation: <td> <input type="text" id="mdamountbox" style="width:50px;" name="md_amt" value="" placeholder="monthly" onkeyup="monthlycheck()" autocomplete="off"> <br><label id="mnthlychkdiscolabel">&nbsp;</label> and javascript function monthlycheck() { var mnthchk = document.getelementbyid("mdamountbox").innerhtml; <---i want pass value of box var cancelphone = document.getelementbyid("cancelphonelabel").innerhtml; if (mnthchk.value != "") { var newhtml = "<span style='color:#

regex - Indexing every occurrence of a key in an array of strings with perl -

i have array of strings @sentences , trying find best way index each occurrence of every word respect line number on. thought nested loop , 2 dimensional array have had no luck. assuming words space-delimited (adjust needed) my $index = {}; $line=0; $s (@sentences) { $line++; $w (split $s) { push @{$index->{$w}},$line; } } this creates hash keys words , values arrayrefs containing lists of line numbers in words appear.

What is the proper naming convention for Maven 3 dependency version properties? -

my company uses properties specify version number dependencies in our maven 3 poms: <properties> <???>1.2.3-snapshot</???> </properties> ... <dependency> <groupid>com.company</groupid> <artifactid>my-awesome-dependency</artifactid> <version>${???}</version> </dependency> we haven't defined naming convention , result inconsistent.

objective c - Can Delphi XE4 import iOS ObjC Class ? ( Static Library *.a ) -

can delphi xe4 import ios objc class ? ( static library *.a ) objc code : test.a // test.h --------------------------------------------------------------- #import <foundation/foundation.h> @interface mycalc : nsobject { bool busy; } - (int) calc : (int) value; @end // test.m -------------------------------------------------------------- #import "test.h" @implementation mycalc -(int) calc:(int)value { busy = true; return ( value + 1); } @end delphi xe4 code "unit1.pas" testing unit1; interface uses system.sysutils, system.types, system.uitypes, system.classes, system.variants,system.typinfo, fmx.types, fmx.controls, fmx.forms, fmx.dialogs, fmx.stdctrls, // posix.dlfcn, macapi.objectivec,macapi.objcruntime, iosapi.cocoatypes,iosapi.foundation,iosapi.uikit,iosapi.coregraphics; {$link libtest.a} // <-- objc static library (3 architectures included) // compiled binary size same,

javascript - Set Viewport Meta Parameters Based on the Width of Browser Window -

i want set different parameters viewport meta tag, depending on current browser window, , able change them on resize (removing current viewport meta tag(s) first , replacing new one. have script think should that, reason script nothing. i'm missing something, can't quite figure out what. here's script: <script type="text/javascript"> var width = window.clientwidth; var meta = document.createelement("meta"); var head = document.getelementsbytagname("head")[0]; if (width < 960) { meta.setattribute("name", "viewport"); meta.setattribute("content", "width=device-width, initial-scale=0.5"); head.appendchild(meta); } else { meta.setattribute("name", "viewport"); meta.setattribute("content", "width=device-width, initial-scale=1"); head.appendchild(meta); }; window.onresize = function(event) { width = window.clientwidth;

android - How to clean variables in an Activity? -

in application when on pressing on button returning previous activity, variables still set , containing values, question how can reset variables in activity, act when first launched? if helps, i'm having app contains 3 activities; in activity 1: putting bundle.putextras() string send next activity ... in activity 2: putting strings in bundle , sends activity 3 ... your non-static variables cleared , reset defaults when go activity . your static variable can reset in ondestroy() method of activity , although doing defeats purpose of making them static in first place. edit: see talking previous activity . in case, override onresume() of previous activity clearing of variables, although fail see why need that.

c++ - How to map 2 char* arrays directly into std::map<std::string,std::string> -

i have 2 char arrays "const char *arr1[arrsize] = {"blah1", "wibble1", "shrug1"};". putting them vector found nice quick solution: void fillvectest() { const int arrsize = 3; const char *arr1[arrsize] = {"blah1", "wibble1", "shrug1"}; const char *arr2[arrsize] = {"blah2", "wibble2", "shrug2"}; std::vector<std::string> vec1(arr1, arr1+arrsize); std::vector<std::string> vec2(arr2, arr2+arrsize); std::vector<std::string>::iterator l_it1vec1; std::vector<std::string>::iterator l_it = vec1.end(); l_it = find(vec1.begin(), vec1.end(), std::string("blah1")); if(l_it != vec1.end()) { size_t l_pos = l_it - vec1.begin(); printf("found %s, pos=%u val: %s\n", l_it->c_str(),l_pos, vec2[l_pos].c_str()); } } now thought should possible put both directly map arr1 key , arr2 value. tried ways d

C SHA1 hash not working -

trying take character arracy (new c) , encode in sha1. the following bit of code not working. returning '\x10' char encode[1000]; strcpy(encode, "get\n\n\n"); strcat(encode, tim); strcat(encode, "\n"); strcat(encode, uri); size_t length = sizeof(encode); unsigned char hash[sha_digest_length]; sha1(encode, length, hash); return hash; at end of day, have base64 representation of hash. thanks!!! most likely, problem you're returning locally declared memory lifetime equal function's scope. non-existent outside of scope. should allow user pass in buffer of own hold hash: /* requires buffer size of @ least sha_digest_length bytes. */ void do_hash(unsigned char* buffer) { /* code */ sha1(encode, length, buffer); } example of usage: unsigned char* hash = malloc(sizeof(unsigned char) * sha_digest_length); do_hash(hash); /* whatever want */ free(hash);

Define object of a class derived from a string variable -

following use case: invoker class (with main method) public class invoker { public static void main(string[] args) { string class_file="batch_status"; } } class invoked (with same method name of class name, e.g. in case batch_status) import java.util.*; public class batch_status { public static void batch_status(string args) { ...... ......code goes here ...... } } now problem not able define object such test in invoker class using value of string class_file such class_file test = new class_file(); above snippet, in production code values in string variable vary , each value, different class file (the name of class file same of value of string variable). please suggest. regards this code demonstrates being able retrieve class instance given string: string classstring = "com.rbs.testing.test"; try { class c = class.forname(classstring); test test = (test) c.newinstance

Sorting Scripture References -

i'm working on csci capstone focusing on text-searching through bible and, because of nature of program, returning unordered list of scripture references formatted such: "nameofbook chapnum: versenum". after list of references, need sort them on 3 fields: name, chapter, , verse, in order, , i'm hoping avoid using o(n^3) algorithm. have code sorts each reference on book name, o(n), don't know go here... suggestions? edit: i'm working in java arrays , looking @ storing sorted data text file can accessed later on. if want have single sort name, chapter, , verse, can either set sort uses 3 of things key sorting, or can use "stable sort" , sort verse, chapter, name. here's pseudocode in python. it's real python code except don't have definitions parse_code() , get_name() , get_chapter() , or get_verse() . lst = [] x in parse_code(input_file): name = get_name(x) chapter = get_chapter(x) verse = get_verse(

ios - Add thumbnail to an MKPinAnnotation -

i have custom mkpinannotation wich need add image(like thumbnail). should able open image fullscreen tapping it. best way go around doing this? a couple of thoughts. if don't want pin on map, rather custom image, can set map's delegate , write viewforannotation like: - (mkannotationview *)mapview:(mkmapview *)mapview viewforannotation:(id <mkannotation>)annotation { if ([annotation iskindofclass:[customannotation class]]) { static nsstring * const identifier = @"mycustomannotation"; // if need access custom properties custom annotation, create reference of appropriate type: customannotation *customannotation = annotation; // try dequeue annotationview mkannotationview* annotationview = [mapview dequeuereusableannotationviewwithidentifier:identifier]; if (annotationview) { // if found one, update annotation appropriately annotationview.annotation = ann

Lifetime of default function arguments in python -

this question has answer here: “least astonishment” , mutable default argument 29 answers i started learning python, got struck default argument concept. it mentioned in python doc default argument value of function computed once when def statement encountered. makes large difference between values of immutable , mutable default function arguments. >>> def func(a,l=[]): l.append(a) return l >>> print(func(1)) [1] >>> print(func(2)) [1, 2] here mutable function argument l retains last assigned value (since default value calculated not during function call in c) is lifetime of default argument's value in python lifetime of program (like static variables in c) ? edit : >>> lt = ['a','b'] >>> print(func(3,lt)) ['a', 'b', 3] >>> print(func(4)) [1, 2, 4] her

javascript - Node.js chat client on browser -

i have node.js chat server developed ios client, develop client usable on browser. don't want use socket.io or similiar, pure tcp socket. code of server: // load tcp library net = require('net'); //var sys = require('sys'); // keep track of chat clients var clients = []; // start tcp server net.createserver(function (socket) { // identify client socket.name = socket.remoteaddress + ":" + socket.remoteport // put new client in list clients.push(socket); // send nice welcome message , announce socket.write("welcome " + socket.name + "\n"); broadcast(socket.name + " joined chat\n", socket); socket.write(tools.foo); // handle incoming messages clients. socket.on('data', function (data) { broadcast(socket.name + " >> " + data+"\n", socket); }); // remove client list when leaves socket.on('end', function () { clients.splice(clients.indexof(socket), 1); broadcast(socket.name +

openmp - What is Parallel for usage in different for loops? -

i have code fragments here think correct not given answer. need clarify this. dotp=0; (i=0;i<n;i++){ dotp+= a[i]+b[i]; } given answer parallelizing code : dotp=0; #pragma omp parallel reduction(+:dotp) (i=0;i<n;i++){ dotp+= a[i]+b[i]; } i think needs dotp added firstprivate visible inside loop dotp=0; #pragma omp parallel reduction(+:dotp) firstprivate(dotp) (i=0;i<n;i++){ dotp+= a[i]+b[i]; } if not correct why not have use firstprivate ? the reduction clause marks dotp shared , performs final summation. the initial value of each shared dotp within loop 0. final step in summation add previous version (original) value of dotp , in case 0. value. you not (and should not) need first private, enforce initial zeroing of dotp .

c++ - Sort objects in descending order when the < comparator is defined? -

i have class a , < comparator. how can use them sort array of a in descending order? class { ... }; class lessa { bool operator()(const a& a1, const a& a2) const { ... } } vector<a> v; sort(v.begin(), v.end(), ???); i suppose should replace ??? based on lessa , can't figure out should go in there. thought of using lambda function, looking shorter. if want sort according relation defined lessa comparator, pass instance of lessa third argument (and, since using c++11, prefer global std::begin() , std::end() functions): std::sort(std::begin(a), std::end(a), lessa()); // ^^^^^^^ now if lessa() expresses < relation , want sort according opposite criterion, do: std::sort(std::begin(a), std::end(a), [] (a const& a1, const& a2)) { return lessa()(a2, a1); } another thing let custom comparator accept argument determines how should perform comparison: class compa { bool

linux - deleting some undesirable rows -

i have file below , want delete rows don't have value in fourth column. experiment replica module mean general1 0 scenario.host[229].app general1 1 scenario.host[229].app 0.00235355 general1 2 scenario.host[229].app general1 3 scenario.host[229].app 0.0783413 general1 4 scenario.host[229].app general3 0 scenario.host[229].app general3 1 scenario.host[229].app 0.540335 general3 2 scenario.host[229].app general3 3 scenario.host[229].app general3 4 scenario.host[229].app general1 0 scenario.host[229].app try following: awk 'nf>3' file edit: added per @adrianfrühwirth's request: whenever find writing requirements in negative terms (e.g. "i want delet rows doesn't have ...") take second see if can express in positive way (e.g. "i want select rows have ...") , you'll find easier come solution , avoid risk of introducing double negatives make comprehension far more difficult.

javascript - AngularJS - Refresh ngRepeat Array Data at Event -

i'm migrating jquery app angularjs. what need do, change data array when scroll occurred, how can this? i have code jquery @ plunk: http://plnkr.co/edit/jdwxh5pmyecuwtsrutro?p=preview when scroll div, list visible elements index show. what want do, set directive or filter ( ng-check-visibility ) @ ng-repeat element, like: <div ng-repeat="item in data" ng-check-visibility> {{item.name}} </div> and directive change item setting value item.visible=true when element visible, otherwise, set false. can angular? ideas? here's way directive: var app = angular.module('myapp', []); app.controller('mainctrl', function($scope) { arr = []; for(var i=0; i<500; i++){ arr.push({id: i, name: 'name'+i}); } $scope.data = { items: arr, visible: [] }; }); app.directive('checkvisibility', function() { return { scope: { data: '=che

c++ - UnsatisifiedLinkError - Unable to load dependent libraries -

Image
i have developed java applet loads c++ dll through loadlibrary function. there, applet calls native methods implemented in c++ code. have created installshield installer puts c++ dll in required location on client computers. everything works fine on development pc, when try testing on "fresh" client computer not have jre installed, getting unsatisfiedlinkerror: can't find dependent libraries . don't know if there else need include. checked using dependencywalker , below saw. is there out of ordinary fresh windows install not include? else can determine dependency dll cannot find on client?

Visual Studio 2012 disassembly error dialog -

this general error visual studio 2012 has come recently. while debugging c++ application , after hitting break-point, clicking "go disassembly" produce following error dialog: disassembly cannot displayed source location. uncaught exception thrown method called through reflection. i've tried reinstalling , repairing vs2012 no effect. simplest console application show same error, it's not specific project , has problem system configuration. @ point i'm clueless module visual studio failing load - google hasn't provided solutions either. the possible link recent removal of older .net framework redistributable packages (since i've got .net 4.5 sdk , multi-target pack, figured older ones weren't necessary) . i need disassembly view working (it worked quite before) , hoping has come across problem. solved: after downloading visual studio 2012 update 2 , problem solved itself. guess bug vanilla release.

ruby - when calling instance_eval(&lambda) to pass current context got error 'wrong number of arguments' -

to clear - code running - code proc but if instead change proc.new lambda, i'm getting error argumenterror: wrong number of arguments (1 0) may because instance_eval wants pass self param, , lambda treats method , not accept unknown params? there 2 examples - first working: class rule def get_rule proc.new { puts name } end end class person attr_accessor :name def init_rule @name = "ruby" instance_eval(&rule.new.get_rule) end end second not: class rule def get_rule lambda { puts name } end end class person attr_accessor :name def init_rule @name = "ruby" instance_eval(&rule.new.get_rule) end end thanks you correct in assumption. self being passed proc , lambda being instance_eval 'ed. major difference between procs , lambdas lambdas check arity of block being being passed them. so: class rule def get_rule lambda { |s| puts s.inspect; puts name; } en

java - How do I read the attachment content on a Defect -

using rally java rest api , after attachmentcontent object, how bytes hold content? you may find following example useful wanting do. it's user story rather defect process identical defect. import com.google.gson.jsonarray; import com.google.gson.jsonelement; import com.google.gson.jsonobject; import com.rallydev.rest.rallyrestapi; import com.rallydev.rest.request.createrequest; import com.rallydev.rest.request.deleterequest; import com.rallydev.rest.request.getrequest; import com.rallydev.rest.request.queryrequest; import com.rallydev.rest.request.updaterequest; import com.rallydev.rest.response.createresponse; import com.rallydev.rest.response.deleteresponse; import com.rallydev.rest.response.getresponse; import com.rallydev.rest.response.queryresponse; import com.rallydev.rest.response.updateresponse; import com.rallydev.rest.util.fetch; import com.rallydev.rest.util.queryfilter; import com.rallydev.rest.util.ref; import java.io.fileoutputstream; import java.io.

compress/minify an ajax/json script -

is there way minify/ compress ajax/json script removes unnecessary whitespaces leave rest on place, like <?php } else { ?> ecc. should stay there is. the script 47 kb, 1 page. i've tried online tools, none of them working, because don't recognize content of code if not work can replace php code unique string, minify javascript , replace string original code.

json - Parsing an enumerated array of arrays from a string in javascript -

i using google charts , trying switch out data using javascript. the data generated on server sql database. formatted string (i can format want) , given browser in response ajax requests. unfortunately haven't been able use json create array matches format used google charts. example of way write variable if being generated directly in javascript: ["united states of america", 7.0287],["canada", 7.3005],["australia", 6.8945] so, array of arrays, , both arrays enumerated rather associative. json seems work better associative arrays enumerated ones. i've tried using jquery's parsejson() function, json2.js library. var sourcedata = '["united states of america", 7.0287],["canada", 7.3005]'; //(the source data pulled ajax, comes in format) var resultarray = new array(); resultarray = json.parse(sourcedata); //doesn't work resultarray = $.parsejson(sourcedata); //doesn't work any ideas? th

ios - How To Show Scrollbar Always On UICollectionView -

i have uicollectionview added uiview in app working on. displayed in uicollectionview have set of images pulled core data. vertical scrolling works fine scrollbar not display until user touches uicollectionview. how can make sure scrollbar @ right visible indication given user scrollable? you can't make them visible. instead, can flash them once, when user first presented collection view notify them, view can scrolled. since uicollectionview subclass of uiscrollview can this: [mycollectionview flashscrollindicators]; check out settings app instance. when go settings list longer screen, scroll indicator flashed once.

c - How are char ** objects saved? -

today, asked me, how char ** objects saved in memory or in binary files. tested following code snippet: char **array = (char *)malloc(3 * sizeof(char *)); array[0] = "foo"; // length: 3 array[1] = "long string"; // length: 11 array[2] = "bar"; // length: 3 => full length: 17 int length = 17; i write array file: file *file = fopen(...); fwrite(array, length, 1, file); fclose(file); the great thing when read again array file following code, string lengths read without saving more 17 bytes. file *file = fopen(...); int length = 17; char **array = (char *)malloc(length); int index = 0; int parsedlength = 0; while (parsedlength < length) { char *string = array[index]; int stringlength = strlen(string); printf("%i: \"%s\" (%i)\n", index, string, stringlength); parsedlength += stringlength; ++index; } i output equals: 0: "foo" (3) 1: "long s

javascript - Can you at least get the domain of the https referer? -

i've noticed if foreign https: site links non-https site, don't in http referer header @ all. i've experienced access.log , presume same happens javascript's document.referrer , too. so, if referrer https, there no way information it? not hostname / domain name? or possible somehow @ least domain, javascript? also, presume running own site https isn't going solve issue me, correct? you should check answer : get referrer url - visitors coming paypal (https) in case site uses http (not https) , referer uses https, there no referrer being sent! http rfc - 15.1.3 encoding sensitive information in uri's states: clients should not include referer header field in (non-secure) http request if referring page transferred secure protocol. so way referrer use https on site.

How to get the parent of an element in webdriver -

<div class="field select-container invalid" data-tooltip="error message." "name="birthdate"> <div class="stack-wrap gutter-col-wrap-1"> <div class="stack size1of3"> <div class="gutter-col-1"> <div class="form-selectbox full-width"> <select name="day"> <option value="">giorno</option> <option value="01">1</option> when used webelement el = browser.switchto().activeelement(), focus on "name" attribute. need find parent "data-tooltip" in order error message on screen. please help. if understand question correctly, want find data-tooltip's text div.select-container for <select name="day">' only here's how in java xpath's ancestor selector (untested code): webelement selectdaycontainer = driver.findelement(by.xpath("//select[@nam

android - Error When Calling Data From SQLDatabase to ListView -

i have been trying find error in project still have no luck.as new programming can't pin point error. have list view within dialog in main project , doing here trying call data mysql database browser list view. have made new project code don't want mess main project code. package com.pdb.projectdb; import java.util.arraylist; import android.app.listactivity; import android.database.cursor; import android.database.sqlite.sqlitedatabase; import android.os.bundle; import android.view.view; import android.widget.adapterview; import android.widget.adapterview.onitemclicklistener; import android.widget.arrayadapter; import android.widget.listview; import android.widget.textview; import android.widget.toast; public class main1activity extends listactivity { private static final string db_name = "yourdb.sqlite3"; //a practice define database field names constants private static final string table_name = "friends"; private static fi