Posts

Showing posts from August, 2015

zipcode - Is it possible to send a zip code to maps V3 API to return a map centered on that zip code? -

i need display map on web page - have user's address info, security purposes need map centered on centroid point of zip code or city, not specific address. is possible submit zip code google maps v3 api , have return map of postal code / zip-code? or have first geocode zip code , submit lat/long? this how doing using yahoo... //assign zipcode database zipcode variable zipcode = ouser("zipcode") <script type="text/javascript" src="http://api.maps.yahoo.com/ajaxymap?v=3.8&appid=x"> </script> // create container <div id="map" class="map"> <script type="text/javascript"> // create map object var map = new ymap(document.getelementbyid('map')); // display map centered on zipcode map.drawzoomandcenter("<%=zipcode%>", 5); </script> if go google.com/maps , enter 5 digit zip code, website return map centered on central point of zip code. script above

flash - How to programatically inject texts into a SWF file -

i'm using dynamic text fields in swf , reading values external text file, i'm able use same swf "template" on , on again different texts. great if somehow wrap swf , variables file 1 swf file programatically, don't need mess 2 files per instance (or inject texts , create static swf instance, long done without manual intervention , result 1 swf file, solution fine). real plus able processing on linux server. if external file xml, can embedded in class such as: public class data { [embed(source='data.xml', mimetype="application/octet-stream")] public static const xml:class; } ...and instantiated as: var xml:xml = new xml(new data.xml); or, xml can pasted class, such as: public class data { public static var xml:xml = <root> <menu> <item>waffles</item> <item>belgian

jquery - Issue with toggle -

i have following code html <div class="menu_head"> <p class="menu_head_open"> <img style="vertical-align:middle;" src="http://oi44.tinypic.com/dyz2r.jpg" alt="">administration </p> </div> <div class="menu_body" style="display: none;"> <table class="plan_table" cellspacing="0" cellpadding="0"> <tbody> <tr> <td class="plan_ta_txt" style="width:40%">moderators</td> <td>1</td> <td>1</td> <td style="width:10%">3 </td> <td style="width:10%">5 </td> <td style="width:10%">10 </td> <td style="width:10%;border-right:none;"> <img style="width:20px; height:17px; padding-left:5px" src="right.gif" alt=&quo

php - URL Routing using RewriteRule -

i trying create own php mvc framework learning purpose. have following directory structure: localhost/mvc: .htaccess index.php application controller model view config/ routes.php error/ error.php inside application/config/routes.php have following code: $route['default_controller'] = "mycontroller"; now trying achieve when user visits root directory using browser want value of $route['default_controller'] route.php file , load php class inside folder controller matches value . and if user tries visit application using url this: localhost/mvc/cars , want search class name cars inside controller folder , load it. in case there no class called cars want take user error/error.php i guess achieve above targets have work .htaccess file in root directory. please tell me code there? if there other way achieve please suggest me. i have tried use .htaccess codes here , not working me it sounds , buzzword standpoint, me little c

Getting perl's executable absolute path with keeping symlinks -

how cleaned-up absolute path perl's executable keeping symlinks? (from $^x variable or anyhow) example perl executable: $ ls -l /opt/local/bin/perl lrwxr-xr-x 1 root admin 8 18 nov 02:46 /opt/local/bin/perl -> perl5.12 i want /opt/local/bin/perl in script regardless how run perl interpreter. the testing code (changesbang.pl): use strict; use warnings; use cwd; use file::spec; use config; $fmt = "%-25s: %s\n"; printf $fmt, "the value of ^x", $^x; printf $fmt, "cwd::realpath", cwd::realpath($^x); printf $fmt, "cwd::abs_path", cwd::abs_path($^x); printf $fmt, "file::spec->cannonpath", file::spec->canonpath($^x); printf $fmt, "file::spec->rel2abs", file::spec->rel2abs($^x); printf $fmt, "config{perlpath}", $config{perlpath}; now when run above as $ ../../../../../opt/local/bin/perl changesbang.pl value of ^x : ../../../../../opt/loc

javascript - how to stop setInterval() on slidetoggle() then restart again? -

i have looked @ other answers similiar question can't make them fit scenario. i have page has sidebar contains 15 results auto refreshes, fine. there link loads external page div overlay. new div full list of results auto refreshes whilst open. (don't want both divs auto-refreshing in background uneccesarily) in full list div each result has jquery slidetoggle() function display more information. what trying(and failing) make auto refresh stop whilst slidetoggle displaying information, cos otherwise when page refreshes goes display:none . here latest attempt: html main page has div load into... <div id="full_list"> loading... </div> external page full list <div class="events_list"> <!--container events --> <ul><li> <div class="full_event"> <!--each event in list--> #1<b> 500 m race </b> <!--this bit seen

ios - How to make an iphone application that should not give user permission to delete itself. Is there any way to do so? -

i in organization going provide ipad installed our app. on particular ipads sales staff want app should not deletable ipad. there way programatically in xcode? app not going on app store. please if has answers? you can't within code of app. can implementing mdm solution.

hadoop - hdfs - ls: Failed on local exception: com.google.protobuf.InvalidProtocolBufferException: -

i trying use below list dirs in hdfs... ubuntu@ubuntu:~$ hadoop fs -ls hdfs://127.0.0.1:50075/ ls: failed on local exception: com.google.protobuf.invalidprotocolbufferexception: protocol message end-group tag did not match expected tag.; host details : local host is: "ubuntu/127.0.0.1"; destination host is: "ubuntu":50075; here /etc/hosts file 127.0.0.1 ubuntu localhost #127.0.1.1 ubuntu # following lines desirable ipv6 capable hosts ::1 ip6-localhost ip6-loopback fe00::0 ip6-localnet ff00::0 ip6-mcastprefix ff02::1 ip6-allnodes ff02::2 ip6-allrouters hi use hdfs:// list dirs? i using couldera 4.3 on ubuntu 12.04 hdfs not running @ 50075. check hdfs port use following command in linux hdfs getconf -confkey fs.default.name you output like hdfs://hmaster:54310 and correct url accordingly

actionscript 3 - How do I reference two dynamic objects when checking for collision? -

i can't figure out how information on slot letter dropped above, letters snaps last slot, because it's 1 referenced properly. can tell me method check object(slot) letter dropped above? 2 kinds of movieclips create background letter , slot drop in. var myformat:textformat = new textformat(); myformat.color = 0xffffff; myformat.font = "verdana"; myformat.size = 35; myformat.bold = true; myformat.align = textformatalign.center; var mystring:string = "firefly" mystring = mystring.touppercase(); var myarray:array = mystring.split(''); for(var i:number = 0; < mystring.length; i++) { var mybogstav:bogstav = new bogstav(); var mybogstavslot:bogstavslot = new bogstavslot(); var mytext:textfield = new textfield(); mytext.selectable = false; mytext.width = 50; mytext.height = 50; addchild(mybogstavslot); addchild(mybogstav); mybogstav.addchild(mytext); mytext.defaulttextformat = myfor

Missing paramenter when I use map (Scala) -

i'm having irritating error can't find explanation for. have code here below: async{ ws.url(url).get().map{ response => //response here giving me error. ok("response: " + (response.json \ "media_count").as[string]) } } and gives me error saying: missing parameter type on response. where should define parameter type? or error saying more specific? i think using play.libs.ws meant java api. the ws.url(...).get() ws class returns promise object of type: promise . map function class takes function instance, not same function1 scala. causing compiler error. if you're working in scala should use play.api.libs.ws.ws meant work scala library. replace import play.libs.ws import play.api.libs.ws.ws in program , error should go away.

iphone - How Core Data save NSNnumber data without rounding the decimal part in Objective-C -

i trying save decimal number core data nsnumber object decimal value had saved rounding digits when enter 5 digit number decimal part. if enter 9999,999 getting save same value database in case of 5 digit (e.g.,10000.999) save 10001 in database. chargefloat=10000.999; value.fees = [nsnumber numberwithfloat:chargefloat];//value entity object //fees nsnumber but in database showing value 10001 . i need solution. floats give 6 9 significant digits, doubles give 15 17 significant digits , nsdecimal gives 38 significant digits. suggest either use doubles of nsdecimals.

android - Row background changes due recyclation. getView() implementation doesn't fix this -

i've been looking lot guides, tutorials , answers here on stack, still can't figure 1 out. i have custom drawable state. if click on row in listview , gets highlighted , updates information in database. (that task (habit) has been performed). works great until start scrolling. i've learnt, required override getview() method , getitemviewtype() getviewtypecount() . how this? code habitscursoradapter getview() , other mentioned methods @ moment looks this. public class habitscursoradapter extends cursoradapter { private layoutinflater inflater; private context context; public static final int performed = 1; public static final int not_performed = 0; public habitscursoradapter(context context, cursor c) { super(context, c, 0); inflater = layoutinflater.from(context); this.context = context; } @override public void bindview(view view, context context, cursor cursor) { string habitname = cursor.getstring(cu

c# - Check whether a link to a file is a txt -

i have varaible urllist holds directory of supposed entered in text box, want though, check whether given directory file text file or not, user gets prompted either cancel actions or give in correct file. code snippet: public static string urllist = @"c:\users\gbbb\desktop\url.txt"; private string[] _urlrows; and method sorta started, , realised need for private void loadurls() { if (urllist == system.text-file) _urlrows = system.io.file.readalllines(@urllist); } if understand clearly, need use path.getextension method. returns extension of specified path string. string ext = path.getextension(@"c:\users\gbbb\desktop\url.txt"); if(ext == ".txt") { string[] readtext = file.readalllines(@"c:\users\gbbb\desktop\url.txt"); }

curl - Getting the URL of redirected page - PHP -

i have url i'm trying redirected page: http://www.hotukdeals.com/visit?m=1650&q=1542029 i tried: $ch1 = curl_init("http://www.hotukdeals.com/visit?m=1650&q=1542029"); curl_setopt($ch1, curlopt_followlocation, true); curl_setopt($ch1, curlopt_nobody, true); curl_exec($ch1); $curl_url = curl_getinfo($ch1, curlinfo_effective_url); echo $curl_url; i'm getting response, same url: http://www.hotukdeals.com/visit?m=1650&q=1542029 how can work? thank you. this should work in cases, unless redirect made javascript. print_r(get_headers('http://www.hotukdeals.com/visit?m=1650&q=1542029'));

JavaFX 2 and 3D -

i read java fx has hardware accelerated 3d support. graphics card intel 945g directx acceleration, directdraw acceleration, agp texture acceleration , open gl capabilities. but still.. system.out.println(platform.issupported(conditionalfeature.scene3d)); gives me false. x axis , y axis rotation not work. is there way make work? software based solution?

mysql - how can i search having search key of multiple values from the column of a table containing multiple values -

i want create mysql search can take multiple values dropdown(multiple) , search , match them in 1 column containing multiple values. sample :- column containing multiple values (in row)= abc pqr xyz and multiple dropdown menu containing abc xyz pqr def user can select these values in order so problem how can create search search key should match of values in column. first of there no "drop downs" in mysql. mysql database, , drop down user interface item. in order search database multiple items can this: select * mytable mycolumn = 'value1' or mycolumn = 'value2' or can way, typically slower: select * mytable mycolumn in ('value1','value2','value3') as far creating drop down, topic question. doing on webpage or application? language? question open ended.

hadoop - Mapreduce job: combiner without reducer -

i noticed if set number of reducer 0, combiner won't work. possible use combiner without reducer? thanks. no it's not. specified reducer, combiners not guaranteed used. combiners strictly optimizations can be, not necessarily, called before reducers. without reducer these never called.

Facebook FQL query to get user's sent messages since a timestamp -

i'm not familiar facebook fql. i'm looking way see users have received message. know need ask extended permissions read_mailbox for instance see if message "hello" has been sent after 2013-05-02 14:00 , recipient userids has been sent to. input query message "hello" , timestamp "2013-05-02 14:00" current timestamp. output query list of userids have been sent message "hello" since timestamp 2013-05-02 14:00 after trial , error found solution: nsstring *query = [nsstring stringwithformat: @"{" @"'query1':'select thread_id message thread_id in " @"(select thread_id thread folder_id = 1 , updated_time >= \"%.f\") " @"and author_id = me() , body = \"%@\"," @"'query2':'select recipients, thread_id thread thread_id in (select thread_id #query1)'" @"}", self.sendtime, self.facebooktext];

android - Trigger event when AsyncTask is complete using Listener -

i'm having confusion on how use listeners pass information between classes , activities. the scenario this: have task reads data sqlite database , puts data arraylist passed adapter displays on screen. the question: app crashes when attempt update listener interface value. doesnt show in logcat...it hangs app. kindly point out i'm going wrong. - thanks details: have database processing done class called datbaseroutines , within inner method doing heavy lifting. method using asynctask not hog main thread. i have created , interface single method public interface databaseprocesslistener { public void processingisdone(boolean blnprocessisfinished); } in databaseroutines class creating private variable private databaseprocesslistener dbprocesslistener; along setter public void setdbprocesslistener(databaseprocesslistener dbprocesslistener) { this.dbprocesslistener = dbprocesslistener; } when processing done, use postexecute method update li

Magento pass and save additional details from cart page into orders table -

i need pass additional parameters along eith products cart page , save order table whenever order being placed.for example parameterscould custom price or anything. i have created db field in table "sales_flat_order_item". which best way accomplish above requirement ? 1) save additional parameters when order being placed using "sales_order_place_before" event 2) save details in quote before proceeding checkout moreover event used if save details before proceeding checkout ? i can not think of best way achieve this. please help. thanks in advance. take @ http://www.magentocommerce.com/boards/viewthread/19344/ in config.xml ... <global> <fieldsets> <sales_convert_quote> <cs_aoc_webid><to_order>*</to_order></cs_aoc_webid> </sales_convert_quote> <sales_convert_order>

java - custom actionbar title in android -

hey guys want in setting current activity title in custom actionbar. my on create function: protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); final actionbar actionbar = getactionbar(); actionbar.setcustomview(r.layout.actionbar_custom_view_home); actionbar.setdisplayshowtitleenabled(false); //i guess line below wrong actionbar.settitle(this.gettitle()); actionbar.setdisplayshowcustomenabled(true); actionbar.setdisplayuselogoenabled(false); actionbar.setdisplayshowhomeenabled(false); } actionbar_custom_view_home.xml <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/linearlayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center" > <imageview

regex - How to match lines not ending (-1)\r\n -

i'm trying match first 5 lines, , last line, in sample: -- 2012-09-20 rep +6 = 184 1 12532070 (2) 2 12531806 (5) 2 12531806 (5) -- 2012-09-21 rep +12 = 196 3 125xxxxx (-1) 3 125xxxxx (-1) 16 12557052 (2) leaving following unmatched: 3 125xxxxx (-1) 3 125xxxxx (-1) i've tried following regular expressions: ^.*[^(-1)\r\n].* ^.*[^(-1)].*\r\n ^.*[^\(-1\)\r\n].* ^.*[^\(\-1\)\r\n].* ^.*[?!\(-1)\r\n].* ^(!?.*-1.*\r\n) but none of them want (mostly matching all lines). my regex skills not brilliant - can point me in right direction? you can use negative lookahead ^(?!.*\(-1\)$).*$\r\n

django - Quering date and time field and render in template -

views.py def new_report(request): user = request.user reports = report.objects.filter(user=user) today = datetime.datetime.today() reports_today = reports.filter(created_date_time__year=today.year, created_date_time__month=today.month, created_date_time__day=today.day) num_today = len(reports_today) + 1 num_today = str(num_today).zfill(3) reportform = reportform() if request.method == 'post': reportform = reportform(request.post) if reportform.is_valid(): report = reportform.save(commit=false) report.user = user report.created_date_time = today return render(request, 'incident/new_report.html', { 'newreport_menu': true, 'reports': reports, 'reportform':reportform, }) models.py class report(models.model): user = models.foreignkey(user, null=false) inci

linux - Shell file parsing to automate youtube uploads -

i writing small script mass upload videos youtube.. looks this: #! /bin/sh python --version file in ./*.mp4 ; export title=$(basename "$file" ".mp4") echo $title "for" $file youtube-upload -m mail@mailer.com -p pass -c category -t "$title" -d "description" "$file" done where youtube-upload cli based python uploader.. my question can see i'm taking title file name path, , description same :(. want write description text or xml file parse it, , upload proper description each file.. how using shell commands in context? thanks suggestions have 1 file containing of filename->description mappings: my file.mp4 description file2.mp4 description last file.mp4 description ilied.mp4 description and grab line beginning filename , use rest of line: #! /bin/sh python --version file in ./*.mp4 ; export title=$(basename "$file" ".mp4") echo $title

c# 4.0 - retrieve image from MS Access -

i want retrieve image ms access database showing in picturebox code code this: private void button1_click(object sender, eventargs e) { oledbconnection myconnection = new oledbconnection(configurationmanager.connectionstrings["connectionstring"].connectionstring); myconnection.open(); oledbcommand cmd = new oledbcommand("select * [images] id=1", myconnection); oledbdataadapter da = new oledbdataadapter(cmd); datatable dt = new datatable(); da.fill(dt); if (dt.rows.count > 0) { if (dt.rows[0]["aimage"] != dbnull.value) { picturebox.image = bytearraytoimage((byte[])dt.rows[0]["aimage"]); } } myconnection.close(); } bitmap bytearraytoimage(byte[] b) { memorystream ms = new memorystream(); byte[] pdata = b; ms.write(pdata, 0, convert.toint32(pdata.length));

c# - mysqldump.exe not taking full backup of mysql database -

i have procedure backing mysql database.and have different mysql servers. procedure works on of mysql servers.but on of servers won't works proper , create backup file size of 1kb. code public void databasebackup(string exelocation, string dbname) { try { string tmestr = ""; tmestr = dbname + "-" + datetime.now.tostring("hh.mm.ss.ffffff") + ".sql"; tmestr = tmestr.replace("/", "-"); tmestr = "c:/" + tmestr; streamwriter file = new streamwriter(tmestr); processstartinfo proc = new processstartinfo(); string cmd = string.format(@"-u{0} -p{1} -h{2} {3}", "uid", "pass", "host", dbname); proc.filename = exelocation; proc.redirectstandardinput = false; proc.redirectstandardoutput = true; proc.arguments = cmd; proc.useshellexecute = false; proc.createnowindow =

java - Changing an Icon in a JLabel dynamically -

i having bit of problem changing , icon in jlabel dynamically. first of all, trying simulating screen sharing operation. on client side, taking screenshots every second, sending them server. on server side, trying open these pictures in simple gui. i able send pictures without problem , able them without problem well. however, gui code have written cannot open pictures. more specifically, if there picture, able open it, not open picture has come. what doing in server side is, picture gets server, saving predetermined name. , able open picture windows' own picture photo viewer. in fact, new picture comes, photo viewer updates , shows new screenshot. however, having trouble opening screenshots in jframe. have written program take screenshots in jpg format, send them server , open them in gui. having problems opening in gui part. have understood, not open files coming client. below codes, appreciated. server side, package screencap; /* * change template, choose tool

c# - How do I access a control inside a XAML DataTemplate? -

i have flipview: <flipview x:name="models_list" selectionchanged="selectionchanged"> <flipview.itemtemplate> <datatemplate> <grid x:name="cv"> <image x:name="img1" source = "{binding modelimage}" stretch="fill" tag="{binding modeltag}"/> </grid> </datatemplate> </flipview.itemtemplate> i want find img1 of selected index. while searching found method on post here: private dependencyobject findchildcontrol<t>(dependencyobject control, string ctrlname) { int childnumber = visualtreehelper.getchildrencount(control); (int = 0; < childnumber; i++) { dependencyobject child = visualtreehelper.getchild(control, i); frameworkelement fe = child frameworkelement; // not framework element or null if (fe == nu

css - Regarding div size -

basically, on 1 of pages of website, have div 60% width, in of content stored. my problem is, when try site on different, lower resolution monitors, of content in div ends being cut out. i don't want increase width, have no ideas on how fix issue without doing so. you can use media queries change style rules based on factors device-width , resolution: https://developer.mozilla.org/en-us/docs/css/media_queries for example, adjust font-size in div based on size of viewport

c# - Windows Phone App: Is there a way to have a button start dialing a phone number from my app? -

i creating app, , want have button can click dial phone number. phone number chosen me. possible? you can that, using phonecalltask var phonecalltask = new phonecalltask(); phonecalltask.phonenumber = "123456789"; phonecalltask.show(); just put code in button's event handler.

qt - How to fire an event on correct sequence of multiple key sequence? -

hi have created event based on secret sequence of key. if user presses ctrl+alt+o event. running code snippet act = new qaction(this); act->setshortcut(qkeysequence(qt::ctrl + qt::alt + qt::key_o)); connect(act, signal(triggered()), this, slot(slotclose())); now wish extend secret key. want user press 2 sequences. ctrl+alt+to ctrl+alt+y. if these 2 sequences fired in order event fired. i doubt qkeysequences work. sure, can!! all need path constructor: act->setshortcut(qkeysequence(qt::ctrl + qt::alt + qt::key_o , qt::ctrl + qt::alt + qt::key_y));

How can I get data from a field name when the name changes dynamically in Javascript? -

i have following code: switch (entitytype) { case "exam": entityid = formdata.examid; idcolumn = 'examid'; break; case "subject": entityid = formdata.subjectid; idcolumn = 'subjectid'; break; } it's repeated more times showing 2 case values here. believe it's possible values idcolumn getting lowercase of entitytype , adding id. there way extract value in formdata field based on entitytype without having manually code many times. you can replace whole with idcolumn = entitytype.tolowercase()+'id'; entityid = formdata[idcolumn]; i'd suggest read mdn's working objects .

How to replace all new lines of string with `<BR>` in php? -

there confusion \n , \r. there lot's of questions in stack differences between \n , \r. in nut shell confusions/questions are: is \r\n equal \n\r? is \r\n cause 2 new lines? is \r cause new line in output? how can replace new lines <br> tag in php? not strings has \r or \n explicitly . suppose have textarea , user inputs characters including enter of keyboard. no \r or \n entered new lines exist. how remove new lines? microsoft windows / ms-dos: \r\n acorn bbc , risc os spooled text output: \n\r apple macintosh os 9 , earlier: \r unix (e.g., linux), apple os x , higher: \n replace -> nl2br more on here if new lines exists in textarea \n,\r or \r\n present! these control characters not outputted. to remove them try: $string = str_replace(array("\r\n", "\n\r", "\r", "\n"), "", $string);

Alternative to heap allocated strings in C (with long lifetimes) -

is possible use "temporary string objects" in c program? for example, have reasonably large array of char * objects (part of struct), using heap allocated memory. have opportunity reduce program's memory usage, since of these names can determined without using explicit character array (although not of them can). in c++, i'd create api returns std::string object (by value) , done it. in c, can come no solutions i'm thrilled about. advice? here's code, requeted: struct foo { char *name; ... }; extern foo* global_foo_array; /* in .h file */ void setup_foo(void) { int i; global_foo_array = (foo*) malloc ( get_num_foo() * sizeof(foo) ); (i = 0; < get_num_foo_with_complex_name(); ++i) { global_foo_array.name[i] = malloc ( ... ); } (i = get_num_foo_with_complex_name(); < get_num_foo(); ++i) { char buf[100]; sprintf( buf, "foo #%d", ); global_foo_array[i].name = strdup( b

c++ - operator<< doesn't find match -

class shape { virtual void out() = 0; }; std::ostream& operator<<(std::ostream& os, shape& a) { return os << a.out(); } i want create abstract base class , able use cout << triangle/square etc. later on, triangle, square being derived classes shape. it works fine if return os << "test"; i'm guessing it's a.out() not getting called properly, can't seem pinpoint problem. the out member function returns void , doesn't return object pass std::ostream::operator<< . perhaps want return std::string ?

android - can some 1 point out the null pointer exception -

i have edited code , null pointer error pointing inside loop less errors before still dont't know why nullpointer called. public class searchlist extends listactivity { @override protected void oncreate(bundle savedinstancestate) { // todo auto-generated method stub super.oncreate(savedinstancestate); new loadsomestuff().execute(); } public class loadsomestuff extends asynctask<string, integer, string[]> { progressdialog dialog; protected void onpreexecute() { dialog = new progressdialog(searchlist.this); dialog.setprogressstyle(progressdialog.style_spinner); dialog.setmax(100); dialog.show(); } @override protected string[] doinbackground(string... arg0) { // todo auto-generated method stub for(int =0; i<20; i++) { publishprogress(5); try { thread.sleep(80); } catch(interruptedexception e) { e.printstacktrace();

php - Would this shorthand work within a function for the return? -

would below work? i'm not able test it, , wondering (as use little shorthand coding techniques) if you're able use shorthand return within function? can't think of reason why not work, couldn't find online verify. function isonline($ip, $port, $timeout = 1) { return (($fp = fsockopen($ip, $port, $i, $j, $timeout)) ? fclose($fp) : false); } the fclose() function should return true, primary return true, correct? of course can accomplish proper way, learning new ways things.

Get path and query string from URL using javascript -

i have this: http://127.0.0.1:8000/found-locations/?state=--&km=km i want this: found-locations/?state=--&km=km how do in javascript? i tried window.location.href giving me whole url tried window.location.pathname.substr(1) giving me found-locations/ use location.pathname , location.search : (location.pathname+location.search).substr(1)

Spring MVC- Page Not Found error -

Image
i'm trying implement variant of muliple file upload tutorial, , having issue getting application run. i created spring mvc project in eclipse using template. the controller has been implemented by @controller public class fileuploadcontroller { @requestmapping(value = "/show", method = requestmethod.get) public string displayform() { return "uploadform"; } @requestmapping(value = "/save", method = requestmethod.get) public string save(@modelattribute("uploadform") fileuploadform uploadform, model map) { //get file name , copy server location return "uploadsuccess" } where uploadform , uploadsuccess jsp pages within views my web.xml file defined as <display-name>samplefileupload</display-name> <servlet> <servlet-name>spring</servlet-name> <servlet-class> org.springframework.web.servlet.dispatcherservlet </se

json - encode/replace blob with base64 in php array -

iam building html5 app gets data json encoded php webservice. have small images stored in database , return them base64 encoded json result. currently mysql field , return json this: $query = "select * `news` "; $posts = array(); if(mysql_num_rows($result)) { while($post = mysql_fetch_assoc($result)) { $posts[] = array('post'=>$post); } } header('content-type: text/javascript'); echo json_encode(array('posts'=>$posts)); i have field called picture. convert picture data in array posts[] base64 can return data json without http request picture. my php skills not thought like: $posts['picture'] = base64_encode($posts['picture']); but need convert every picture base64, maybe better put in while loop: while($post = mysql_fetch_assoc($result)) { if($post == 'picture'){ $post = base64_encode($post); } $posts[] = array('post'=>$post); } can work? or there other/better

python - Writing more compact version of my function -

i have code below in more compact way ( 1 or 2 lines ) foo.txt: a:1 b:2 c:3 code: >>> r = {} >>> in open('foo.txt','r').readlines(): ... k,v = i.split(':') ... r[k]=v.strip() how about: in [43]: open("foo.txt") fd: my_dict=dict(x.strip().split(":") x in fd) ....: in [44]: my_dict out[44]: {'a': '1', 'b': '2', 'c': '3'} another approach: in [46]: open("foo.txt") fd: my_dict={k:v k,v in (x.strip().split(':') x in fd)} ....: in [47]: my_dict out[47]: {'a': '1', 'b': '2', 'c': '3'}

java - Why can't I delete the XML file I created? -

my first question speed of stax writer. have problem: can't delete xml file created, delete(); it still being used somehow. have tried delete manually not. @ , of file creation call method close() streamwriter. i trying delete file right after method done, in file. like: startstopwath;createxml(); stopstopwatch; file.delete() have add more there? here code: import java.io.*; import java.util.*; import javax.xml.stream.*; import org.springframework.util.stopwatch; public class staxvytvor { public static string subor = "test.xml"; public static void main(string[] args) { int num =600000; try { string encoding = "utf-8"; xmloutputfactory f = xmloutputfactory.newinstance(); xmlstreamwriter w = f.createxmlstreamwriter(new bufferedoutputstream(newfileoutputstream(subor)), "utf-8"); w.writestartdocument(encoding, "1.0"); w.writecharacters("\r\

Using canvas drawImage in chrome extension content script -

Image
i'm trying use drawimage on canvas context in injected content script chrome extension. testcanvas = document.createelement('canvas'); testcontext = testcanvas.getcontext('2d'); var image = new image(); testcontext.drawimage(image, 0, 0); in chrome 26 works ok, in dev channel (chrome 28) seams broken got message: uncaught typeerror: type error when move same script directly background page, works without problem. i think can related security related change failed find relevant information. this bug, should report it. more testing reveals in chrome 28.0.1498.0, image constructor not create valid htmlimageelement instance (as seen in screenshot below). code run in context of content script. same code works fine on regular pages , in extension's process (background page). to work around problem, use document.createelement('img') instead of new image() . and don't forget report bug @ https://code.google.com/p/chr

Clojure macro that doesn't need space next to it -

trying create macro form of haskell's lambda syntax, i'm pretty close except 1 last tweak, / (which should \, can't grumble..) needs space next it, there way make macro doesn't need space between , it's first argument? for instance: (reduce (/x y -> x y) [1 2 3]) instead of: (reduce (/ x y -> x y) [1 2 3]) i suspect isn't possible, way know sure ask people know, what's word? no. macros cannot change lexical syntax of language. requires read-macros, clojure doesn't have.

twitter bootstrap - how to integrate Falgun theme into Rails application? -

my client wants me use theme: http://themeforest.net/item/falgun-metro-style-bootstrap-admin-dashboard/4257951 how supposed it? cant find tutorials using custom themes in general.

directx - C# Direct X 9.0c - Mesh Intersect -

i want collide vector of mesh using up-vector. i have position , vector.. booth calculate far vector public vector3 setplayertoground(matrix object, matrix player, mesh groundobject) { vector3 intersectvector = new vector3(0, 0, 0); if (groundobject != null) { vector3 player_up = new vector3(player.m12, player.m22, player.m32); vector3 playerpos = new vector3(player.m14, player.m24, player.m34); vector3 playerpos_far = playerpos - player_up ; gameengine.m_device.transform.world = object; intersectinformation closestintersection; if (groundobject.intersect(playerpos, playerpos_far, out closestintersection)) { intersectvector = player_up + (playerpos_far * closestintersection.dist); } } return intersectvector; } well if vector3 playerpos_far = pl

android - Need Help For Foreign Key -

db.execsql(" create table " + kk_airlinebook + " (" + key_id + " integer primary key autoincrement, " + key_srno + " integer, " + key_bname + " text , " + key_bookingdate + " text, " + key_pickupaddress + " text, " + key_city + " text, " + key_airporttype + " text, "+ key_trip + " text, " + key_cabr + " text , " + key_flightdate + " text, " + key_flighttime + " text, " + key_cabdate + " text, " + key_pickuptime + " text, " + key_totalseats + " integer, " + key_charges + " integer , " + "foreign key ," + key_srno + " references kk_registration , " + key_id +");"); log cat: 05-04 20:06:36.034: e/sqlitelog(26155): (1) near ",": synta

c++ - Creating this function template -

i have simple class template tuples of vectors: template <typename... t> struct tupleofvectors { std::tuple<std::vector<t>...> tuple; }; i can use this: tupleofvectors<double, std::string> tuple; auto vec0 = std::get<0>(tuple.tuple); vec0.push_back(1.2); auto vec1 = std::get<1>(tuple.tuple); vec1.push_back("foo"); i want encapsulate class template itself. how i'd use class template: tuple.vec<0>.push_back(1.2); tuple.vec<1>.push_back("foo"); how develop such vec() template member function? template <typename... ts> struct tupleofvectors { std::tuple<std::vector<ts>...> tuple; template< size_t n > auto vec() -> decltype( std::get<n>(tuple) ) { return std::get<n>(tuple); } }; tupleofvectors<int, short, double, float> t; t.vec<3>().push_back( 3.14f );

javascript - How to deselect a HTML button tag with a simple chrome extension -

i have created chrome extension simple popup.html file contains button tag first element inside body. when test on chrome 26 under os x, each time click on extension icon triggers popup, button seems selected/focused given see blue halo. cannot figure out how disable auto focus. seems autofocus applied on first tag popup.html file. tried apply blur() on button instance retrieved document.getelementbyid not work. is there solution? workaround? alternative? the solution found consists of adding tabindex="1" on html tag. tried put focus on other elements or use autofocus="autofocus" not work.

python - How to use the a k-fold cross validation in scikit with naive bayes classifier and NLTK -

i have small corpus , want calculate accuracy of naive bayes classifier using 10-fold cross validation, how can it. your options either set or use nltk-trainer since nltk doesn't directly support cross-validation machine learning algorithms . i'd recommend using module if want write own code following. supposing want 10-fold , have partition training set 10 subsets, train on 9/10 , test on remaining 1/10 , , each combination of subsets ( 10 ). assuming training set in list named training , simple way accomplish be, num_folds = 10 subset_size = len(training)/num_folds in range(num_folds): testing_this_round = training[i*subset_size:][:subset_size] training_this_round = training[:i*subset_size] + training[(i+1)*subset_size:] # train using training_this_round # evaluate against testing_this_round # save accuracy # find mean accuracy on rounds

haskell - How to implement and use the sub-modes feature from System.Console.CmdArgs -

i create kind of swiss-knife tool specific domain, , "cabal" or "darcs" command-line interface looks perfect. using on-line tutorials implement simple "hello, world" program. implemented more sophisticated solution modes , when well. but now, explore "sub-modes" have understanding of possibilities, , i'm stuck. not find tutorial, example or detailed description of feature. how implement , use submodes feature? i want clarify understand modes, it's submodes not clear me. the cmdargs tutorial has examples sub-modes. documentation modes function clear. in fact, google search "cmdargs modes" reveals quite a few more tutorials covering this.