Posts

Showing posts from September, 2012

python - Subtract dates in Django? -

i have 2 datefield variables , subtract them , return difference number of months nearest month. how might this? thanks help! for definite answer using calendar month lengths: months = lambda a, b: abs((a.year - b.year) * 12 + a.month - b.month) example: >>> import datetime >>> = datetime.date(2011, 2, 8) >>> b = datetime.date(2010, 5, 14) >>> months(a, b) 9 edit, if want round based on days too: months = lambda a, b: abs((a.year - b.year) * 12 + a.month - b.month) + int(abs(a.day - b.day) > 15) example: >>> import datetime >>> = datetime.date(2011, 2, 8) >>> b = datetime.date(2010, 5, 14) >>> months(a, b) 9 >>> b = datetime.date(2010, 5, 30) >>> months(a, b) 10

java - How to start a transaction in JDBC? -

connection.settransactionisolation(int) warns: note: if method called during transaction, result implementation-defined. this bring question: how begin transaction in jdbc? it's clear how end transaction, not how begin it. if connection starts inside in transaction, how supposed invoke connection.settransactionisolation(int) outside of transaction avoid implementation-specific behavior? answering own question: jdbc connections start out auto-commit mode enabled, each sql statement implicitly demarcated transaction. users wish execute multiple statements per transaction must turn auto-commit off . changing auto-commit mode triggers commit of current transaction (if 1 active). connection.settransactionisolation() may invoked anytime if auto-commit enabled. if auto-commit disabled, connection.settransactionisolation() may invoked before or after transaction. invoking in middle of transaction leads undefined behavior. sources: javadoc jdbc tut

android - Search to show a new intent? -

maybe 1 can me this... have custom search button (i have google search need this).. here scenario: on main page have list of records i click on search button shows list of tags can click on system search -i return main page string telling me records view -the main page shows records this fine, problem if click app quits, understandable , suppose happen. want same android search function opens result in new page , when click takes me full list cursor notescursor3 = mdbhelper.fetchsearchtagnotes(matchnotes); startmanagingcursor(notescursor3); string[] = new string[]{notesdbadapter.key_title,notesdbadapter.key_createdon}; int[] = new int[]{r.id.text1,r.id.date}; simplecursoradapter notes = new simplecursoradapter(this, r.layout.notes_row, notescursor3, from, to); setlistadapter(notes); this simple code after getting search result, changing adapter list (i same default android search works said). never mind question. had succumb inability find answer , crea

iphone - Any way to draw Core Graphics in the contentView of a UIScrollView -

i wondering if possible draw core graphics in content view of scroll view because @ moment, in drawrect section of uiscrollview, draws on static view , when scroll content view, graphics stay still... (which means i'm not drawing in right view) do have create uiview subclass , draw there , add uiscrollview, while handling zooming , scrolling uiscrollview or - there way can keep in 1 subclass of uiscrollview! (i hope makes sense!) thanks! typically, don't draw in uiscrollview directly. uiscrollview container view scrolls 1 content view or several tile views. should add content view(s) addsubview: , position them needed. scroll view handle scrolling , zooming.

c++ - How to detect no-return statement from a function -

i have function returns non-void. on caller side, want detect whether return statement called in original function or not. i know, not allowed have non-void function return nothing , throw warning in gcc. want print runtime error based on whether return called or control reached end of function. the callee defined user. provide declaration. so, want ensure implementer of callee function, doesn't skip "return" statement. you can't determine how function returns caller (other whether throws exception or returns). thing can prevent function returning explicitly using compiler warning or put run-time error call @ end of function don't want have control fall off end of. 1 trick might able have return type function have default constructor gives run-time error; return statements need use other constructor. once that, though, might add error call end of function or change return type gcc warning.

javascript - Best HTML structure for Ajax links -

when using javascript assign onclick handlers html <a> tags, have specific question when comes use of ajax - what's best way url ajax request? should use this.href or code handler function itself? consider following link: <a id="link" href="http://mysite.com/getdata.php">get data</a> then, javascript: document.getelementbyid('link').onclick = function() { // send ajax request } i using this.href inside handler i'm worried user clicks link before domready fires , links activated. better use href="javascript:void(0);" in html , construct url in handler itself? way, link nothing unless it's activated. what's best-practice here? thanks, brian think perspective: how page architecture hold if no js enabled? your application should responsive user input under circumstances, , should not rely on implicit assumptions whether users have javascript-enabled browsers. sounds ridiculous, ri

Python error logging -

i'd find way log every error forces python interpreter quit saved file being printed screen. reason want keep stats on types of errors make while writing code, eye towards finding ways avoid mistakes make commonly in future. i've been attempting writing wrapper python interpreter using subprocess module. basically, runs python interpreter, captures output, parse , saves file, prints output, , use matplotlib make summary figures. however, i'm having problem getting output wrapper script in real time. example, if script i'm running is: import os import time x in range(10): print "testing" time.sleep(10) and i'm using subprocess.popen() p.communicate(), wrapper wait 100 seconds, , print of output. i'd wrapper invisible possible - ideally in case print "testing" once every ten seconds. if point me towards way of doing this, i'd appreciate it. thanks! i believe can replace sys.excepthook own functi

php - why there is a difference between below given output? -

$y = 07; echo 'y: '.$y; // result 7 $y = 08; echo 'y: '.$y; // result 0 view demo :edit: one more similar $y = 013; echo $y + 5; //this result in 16 i can not figure out how ans 16? can 1 help? part 1 the rules parsing explained in integers documentation . in php number starting 0 assumed in octal. because 08 in octal isn't valid getting 0. part 2 the same issue in play, 013 in octal 11 in decimal , 11 + 5 = 16

PictureBox Tooltip changing C# -

ok complete beginner , have managed put small app in c# enter username in textbox , application gets avatar of username , displays in picturebox. what want have tooltip show username typed in textbox when mouse hovers on loaded avatar. should change each time new avatar loaded. know how use tooltips normal way bit complex me. appreciated. thanks. add hover event picturebox following code. private void picturebox1_mousehover(object sender, eventargs e) { tooltip tt = new tooltip(); tt.settooltip(this.picturebox1, "your username"); }

iphone - Reachability App 2.2 - Local Wifi does not restore -

can explain why reachability app behaves strangely? built under ios 4.2 when start it, 3 text boxes show available network. if turn airport off, show no connection. turning airport on again remote host , tcp/ip routing shown availabl. local wifi remains 'access not available' this may seem dumb question, did build in simulator? results on simulator won't mirror on device, 3g in simulator abstraction of wifi radio in mac. you'll need use device in order see work.

How to uncheck the CheckBox, when limit exceeds in android? -

hello new android, requirement allow user check maximum 3 number of checkboxes. when user trying check fourth 1 should populate dailogue. iam trying problem fourth 1 not unchecking... can 1 me... regards shiva.m just uncheck checkbox using following code block: final checkbox checkbox = (checkbox) findviewbyid(r.id.checkbox_id); if (checkbox.ischecked()) { checkbox.setchecked(false); }

wordpress - How to redirect to sitemap.php from htaccess -

i using htaccess coppied wordpress. rewritecond %{request_filename} !-f rewritecond %{request_filename} !-d rewriterule . index.php [l] it works fine. i add script redirect sitemap.php file if user requests sitemap.xml. i tried adding rewritecond %{request_filename} !-^sitemap.xml$ didn't work. put rule before set of rules: rewriterule sitemap\.xml sitemap.php [l] rewritecond %{request_filename} !-f rewritecond %{request_filename} !-d rewriterule . index.php [l]

javascript - Reference material for calculating response times -

i have mobile application (ios) sends instructions via comet server ( ape ) web application (js). each instruction, web application responds "ack" message, tagged instruction id. want calculate average response time web application. the frequency of instructions may vary 5 per second on every other second (or longer, depending on user). my naive solution timestamp each send , receive , calculate average among differences. inefficient since algorithm (basic for-loop) stalls application , inflicts delay in handling acks. solution use ten latest timestamps , limiting number of response times calculation. i'm not happy solution , looking reference material provide me information problem i'm facing. here use, not based on scientific material, works me... we keep average of last 10 + keep worst 2 ever , best 2 ever . don't persist data, worst/best 'ever' measured since reboot of application server. then make average on these 14. hope

iphone - Contact Like handling of fields -

i developing app information location. information contains phone number, email address, address etc. bit contact detail information of iphone itself. now question. when select contact in phonebook, can select phonenumber call, select emailaddress mail , select location information view in maps of iphone. want achieve. i have searched google functionallity searching wrong things.can me achieve functionallity? thanks!!! //// followup now know stuff want add possible, have followup question subject. does know can find examples actions calling, mailing , location information? me lot... thnx!! with kind regards, douwe here link accessing address book details. this example shows display first name, last name, instead display phno.,email, location along button near ti it. then code in button action call, mail, view location respectively.

database - HQL: how can I maintain sort order when fetching complete rows using a where-in-subselect construct? -

i creating feature 'other people liked like'. the hql statement in question returns list of product ids (ordered count of shared 'likes' between 2 products). result not distinct - stripped down basics, query looks this. (please note: it's not original query, rather simplified example give idea of doing) select prd2.id userlike ul2 join ul2.product prd2 ul.userid in ( select ul.userid userlike ul join ul.product prd prd.id=:productid ) group prd2.id order count(prd2.id) desc starting there, there common pattern retrieve complete row/entity each product? in sql i'd use query above subselect within , join product table. as hql not support subselects within from, not think there way wrap from product p p.id in (subselect_as_above) but there goes sorting. :( maybe sounds bit weird, think common use case - there common workarounds this? thanks lot in advance , best regards, peter you can in 2 steps: 1. list if ids (which have

In a Rails 3 view, how do I detect an URL in a display string and format it as a link to that URL? -

i have user generated comments on site. if user adds url in comment, i'd formatted link , link url. how do that? rails has auto_link text helper. auto_link("go http://www.rubyonrails.org , hello david@loudthinking.com") # => "go <a href=\"http://www.rubyonrails.org\">http://www.rubyonrails.org</a> , # hello <a href=\"mailto:david@loudthinking.com\">david@loudthinking.com</a>" auto_link("visit http://www.loudthinking.com/ or e-mail david@loudthinking.com", :link => :urls) # => "visit <a href=\"http://www.loudthinking.com/\">http://www.loudthinking.com/</a> # or e-mail david@loudthinking.com"

html - How to check the children of div container had been fulfill or not in jquery? -

i not sure how describe in title.so,just give more information here. i have container div class=container random children link tag inside .e.g: <div class='container' style='width:200px; height:25px;overflow:hidden;'> <a href='' style='display:block;float:left;padding:1px 3px'>people name here[long or short]</a> ..... <!--random total of name's link--> </div> so, in cases there only one name , didn't go outside of container in case, the count of name outside of container , want put tip or beside note there more name here didn't display. thank much!! [update] for example: if link inside of container is: <a href='' style='display:block;float:left;padding:1px 3px'>join keviin</a> <a href='' style='display:block;float:left;padding:1px 3px'>my second name</a> <a href='' style='display:block;float:left;padding:1px 3px'

Can I translate my website with Google Translate? -

i have web page created in english. depending on continent, want dynamically translate whole webpage language. the webpage complex, cannot string string. want in way @ time of loading translated desired language. can translate webpage using google translate api? here example to add google translator web page translate specific element: <html> <head> <title>my page</title> <meta http-equiv="content-type" content="text/html; charset=utf-8"> </head> <body> <div class="translate">Тестирование</p> <div class="translate_control" lang="en"></div> <script> function googlesectionalelementinit() { new google.translate.sectionalelement({ sectionalnodeclassname: 'translate', controlnodeclassname: 'translate_control', background: '#f4fa58' }, 'google_sectional_el

C++ template problem -

i implement base class attributes of size know @ compile-time. idea use template base class. following code compiles , runs fine under vc++9.0. class definition in .h file template<int n> class baseclass { int* idx; int* incr; int* limit; public: baseclass(void); ~baseclass(void); void loopmethod(void); }; implementation of class methods in .cpp file #include "baseclass.h" #include<iostream> using namespace std; // instantiation template class baseclass<2>; template<int n> baseclass<n>::baseclass(void) { idx = new int [n]; incr= new int [n]; limit = new int[n]; for(int m = 0; m < n; m++) { idx[m] = 0; incr[m] = 1; limit[m] = 2; } } template<int n> baseclass<n>::~baseclass(void) { } template<int n> void baseclass<n>::loopmethod( ) { for( idx[n-1]; idx[n-1] < limit[n-1]; idx[n-1] += incr[n-1] ) { cout << "loopmethod nr " << n-1 << " calle

Ant copy with many mappers problem -

i want copy directory directory must rename 1 file. trying this: <copy todir="destdir" enablemultiplemappings="true"> <fileset dir="sourcedir"/> <compositemapper> <identitymapper /> <globmapper from="oldfilename" to="newfilename"/> </compositemapper> </copy> but task copy files, , copy renamed file. , in destdir directory have 2 files: destdir\oldfilename , destdir\newfilename . need destdir\newfilename . can me this? edited: need copy files form sourcedir destdir, , rename file name "oldfilename". set enablemultiplemappings="false" , , swap order of mappers: <copy todir="destdir"> <fileset dir="sourcedir" /> <compositemapper> <globmapper from="oldfilename" to="newfilename" /> <identitymapper /> </compositemapper> </copy> without multiple map

gwt2 - PropertyChangeSupport in GWT -

in gwt application developed module uses java.beans.propertychangesupport. have started using module , getting the import java.beans cannot resolved error when run. application runs well. why getting compiler error in gwt dev mode window? ideas? 00:17:33.079 [error] errors in 'file:/d:/workspace/app/src/main/java/com/abc/def/client/extract/pojos/clientdata.java' 00:17:33.079 [error] line 3: import java.beans cannot resolved 00:17:33.079 [error] line 4: import java.beans cannot resolved 00:17:33.079 [error] line 11: propertychangesupport cannot resolved type 00:17:33.079 [error] line 14: propertychangesupport cannot resolved type 00:17:33.079 [error] line 14: propertychangesupport cannot resolved type 00:17:33.079 [error] line 17: propertychangelistener cannot resolved type 00:17:33.079 [error] line 18: propertychangesupport cannot resolved type 00:17:33.079 [error] line 21: propertychangelistener cannot resolved type 00:17:33.079 [error] line 22: propertychang

Android webview, file input field filechooser doesn't show up -

i supposed display web page in webview in app. page contains html form 1 of fields file. goes like... <input type="file" name="file"> if open page in browser , press choose file button, file chooser pops , good, when press choose file button in webview nothing happens :/ any ideas how make work? webview default doesn't open file chooser. possible make work. webchromeclient has hidden method openfilechooser , needs overridden pop file chooser , return result webview. according gurus 1 should never use hidden methods of android sdk not solution, , shouldn't used in enterprise apps. android's stock browser way. little more information how overrode method in question . if needs source let me know ill post somewhere.

java - GWT and SpringSecurity -

i've created 2 modules gwtappauth gwtapp when try posting form gwtappauth j_spring_security_check nothing happened. firebug shows in console "failed load source for:http://127.0.0.1:8888/j_spring_security_check" but if try after manually access gwtapp works. knows matter? looks spring security doesn't redirect second (gwtapp). how check it? run application in hosted mode try access gwtapp.html spring security redirects me gwtappauth.html press login button in place if check firebug log can see "post //127.0.0.1:8888/j_spring_security_check" and response - "failed load source for: http://127.0.0.1:8888/j_spring_security_check" then next record - "get //127.0.0.1:8888/gwt/gwtapp.html?gwt.codesvr=127.0.0.1:9997" and fetching needed resources can manually input "//127.0.0.1:8888/gwt/gwtapp.html" and have access gwtapp.html i found out solution. should use html form , subm

c# - Create an On-screen Keyboard -

i use postmessage simulate keystrokes in program in background. work fine except characters need shift on physical keyboard. how simulate shift? " the code use roughly: vk vk = vkkeyscanex (c, getkeyboardlayout (0)); attachthreadinput (_attachedthredid, _attachedprocessid, true); postmessage (_window, wm_keydown, vk.key, 0x1); postmessage (_window, wm_keyup, vk.key, 0xc0010001); attachthreadinput (_attachedthredid, _attachedprocessid, false); how should handle extended part of vk? edit i'm trying create on-screen keyboard. each button on on-screen keyboard simulates sequence of keystrokes. receiver old program performs different tasks depending on keyboard sequence performed. keyboard sequences follows {esc}nn{esc}nn {esc}nn ½nn §nn where {esc} simulate pressing esc key, nn hex values , §/½ program listen. normally have special physical keyboard control program, expensive. in test environment not have physical keyboards, have enter

javascript - flotr / protochart bar chart based on timestamps -

i want create bar chart flotr / protochart (tried both) can't work properly. when doing following, bars small grid line. flotr.draw( $('workflow-chart'), [ { label: 'd1', data: [[1291622400000, 3], [1291708800000, 8], [1291795200000, 7], [1291881600000, 0], [1291968000000, 5]] } ], { bars: {show: true, fill: true}, xaxis: { tickformatter: function(t) { date = new date(); date.settime(t); day = date.getdate() > 9 ? date.getdate() : "0" + date.getdate(); month = date.getmonth()+1 > 9 ? date.getmonth()+1 : "0" + (date.getmonth()+1); return day + "." + month; } } } ); this question sim

xcode - Objective-C program falling on scrolling UITableView -

hi made application has tableview, works fine starts falling when scroll it.it scroll 5-10 percent of content, if use on table whit 200 data scroll 10-20 whit larger data shows larger data falls.can u me why?or have find problem? thanks the error message: 2011-02-09 13:23:13.631 navtest[2277:207] *** terminating app due uncaught exception 'nsinvalidargumentexception', reason: '*** -[nscfstring appendstring:]: nil argument' *** call stack @ first throw: ( 0 corefoundation 0x00fa0be9 __exceptionpreprocess + 185 1 libobjc.a.dylib 0x010f55c2 objc_exception_throw + 47 2 corefoundation 0x00f59628 +[nsexception raise:format:arguments:] + 136 3 corefoundation 0x00f5959a +[nsexception raise:format:] + 58 4 foundation 0x000bf406 mutateerror + 156 5 navtest 0x0000c13a -[tretiviewcontroller configurecell:

asp.net mvc - what is the standard for creating a web REST API for adding new items -

i have order catalogue web site , want create rest api people can create own apps , add order or update existing order: lets order has: orderid product quantity shippingtype so need api allow send in new order (orderid blank in response). how deal passing in items product or shipping type. these tables in db , keyed off own specific primary key id. should neworder api ask string name these fields, should ask id. if asked id, assume have call givemeproductlist() method upfront (which gives name , id of product dataset). what standard dealing this? martin fowler has post steps toward glory of rest might find useful come rest api.

c++ - Does boost test have support for wide strings? -

i'm using boost_test_message(l"blah") , thing printed out hex value such 0x12345678. missing configuration? i'm using boost 1.44. if take @ boost/test/unit_test_log.h , can see class unit_test_log_t using std::ostream streaming logs. so, have implement own logger.

iphone - memory leak issue -

am getting memory leak in following code..pls me solve this.. if (ui_user_interface_idiom() == uiuserinterfaceidiompad) { //ipad specific code. universalapp=1; nslog(@"ipad started......."); // override point customization after application launch window.frame = cgrectmake(0, 0, 768, 1004); //window.frame = cgrectmake(0, 0,320,460); mainpagecontroller = [[mainpagecontroller alloc] initwithnibname:@"mainpagecontroller" bundle:nil]; // [mainpagecontroller.view setframe:cgrectmake(0, 20, 320, 460)]; [window addsubview:mainpagecontroller.view];//memory leak [window makekeyandvisible]; i don't see leak there, assuming you're releasing mainpagecontroller in -applicationwillterminate: or app delegate's -dealloc . what's problem?

Creating Android Location Object -

i using geocoder class fetch multiple location objects using following code: geocoder geocoder = new geocoder(this, locale.getdefault()); list<address> addresses = geocoder.getfromlocation(latitude, longitude, 3); address[] addresses_array = new address[addresses.size()]; addresses.toarray(addresses_array); for( int = 0; < addresses_array.length; i++ ){ //create location object here locobj.setlatitude(latitude); locobj.setlongitude(longitude); } in addition, inside forloop, trying dymanically create location objects add array; how can create blank location objects ? assuming refer android.location.location use constructor takes provider string , set whatever want.

cocoa - Why NSWindow without styleMask:NSTitledWindowMask can not be keyWindow? -

problem: have 1 window mainwindow , childwindow added mainwindow . childwindow kind of windowext class. class define catch method call [nswindow becomekeywindow] must called after [childwindow makekeywindow] . if create childwindow , try make keywindow on next way: windowext *childwindow = [[windowext alloc] initwithcontentrect:addedwindowrect stylemask:nsborderlesswindowmask | nstitledwindowmask backing:nsbackingstorebuffered defer:no]; [mainwindow addchildwindow:childwindow ordered:nswindowabove]; [childwindow makekeywindow]; method [windowext becomekeywindow] childwindow called - fine, childwindow become keywindow. but if create childwindow as windowext *childwindow = [[windowext alloc] initwithcontentrect:addedwindowrect stylemask:nsborderlesswindowmask backing:nsbackingstorebuffered defer:no]; [mainwindow addchildwindow:childwindow ordered:nswindowabove]; [childwindow makekeyw

php - preg_match() find all values inside of table? -

hey guys, curl function returns string $widget contains regular html -> 2 divs first div holds table various values inside of <td> 's. i wonder what's easiest , best way me extract values inside of <td> 's have blank values without remaining html. any idea pattern preg_match should like? thank you. you're betting off using dom parser task: $html = <<<html <div> <table> <tr> <td>foo</td> <td>bar</td> </tr> <tr> <td>hello</td> <td>world</td> </tr> </table> </div> <div> irrelevant </div> html; $dom = new domdocument; $dom->loadhtml($html); $xpath = new domxpath($dom); $tds = $xpath->query('//div/table/tr/td'); foreach ($tds $cell) { echo "{$cell->textcontent}\n"; } would output: foo bar hello world

asp.net mvc - Design: Product Treeview shared among several controllers -

i have product treeview referenced in multiple views , controller. treeview items of product treeview loaded dynamically using ajax , public action method. should move product treeview's logic , public action method shared controller such sharedcontroller? recommend? burnt1ce, as ever, depends... if use via ajax (jquery or msajax?? [not matters much, allow add appropriate tag question]), tempted refactor out html.helper few overloads allow different product models loaded. (i recommend using product interfaces, rather concrete classes allow variety of product sub-classes if required)... if ever need load in context of view, keep , load via html.renderaction() method. this initial thoughts.

android - Copy all files beginning with a certain letter -

what trying copy files 1 folder another. however, twist copy files 1 folder begin 123 , can follow. for example have folder 3 files, 123__sdf.jpg, 123034.jpg , 321.jpg. want copy first 2 how select them only. because application dynamic files can change thats why want able select files begin 123. first, want create file pointing directory. then, can use list method list of files inside directory. can use startswith check whether start 123 or not. file dir = new file("/the/dir/"); if( dir.isdirectory() ){ string[] files = dir.list(); (string string : files) { if( string.startswith("123") ){ file file = new file(dir, string); // copy stuff } } } list method returns list of strings files , directories, may want use isfile() method if want copy files.

layout - intellij - how can I see a lot more compilation errors in each build -

intellij question regarding feature had in eclipse , missing in intellij. i don't fact after build process see few compilation errors. there way see lot more (i know not possible see cause correlated in eclipse use see more). 10x. it's compiler feature/limitation, not idea. can more errors switching eclipse compiler in settings | compiler.

jquery - Submit username and password javascript (not a form) -

i have popup asks user login information, means 2 input text fields password , username. now verifying information using ajax didn't wrap elements on because form needs php action, correct? or missing something? so i'd know if there fancier way check if user pressed enter, in order submit login information, checking each time key pressed, keydown, if it's enter key. thanks in advance you still need form wrap user inputs, , form still has action. however, won't full page post. instead, you'll send ajax post. jquery makes easy. $(function() { $("#myform").submit(function () { var data = $(this).serialize(); var url = $(this).attr("action"); $.post(url, data); return false; }); });

open the Windows virtual keyboard in a Java program -

i create event in button. when click in button, open windows virtual keyboard. can me code? thank collaboration. best regards. i think simple this: runtime.getruntime().exec("osk");

java - jpanel with image in background -

i have simple doubt, need replace this: panel[1].setbackground(color.red); for image, want avoid new jlabel image, because tested , have label inside panel pushed below background panel shows 2 approaches. 1 involves custom painting, other involves using jlabel. approach use based on requirement. custom painting more flexible little more complicated.

C# WinForms DateTimePicker Component -

i m using datetimepicker component. possible tu change format ? want yyyy-mm-dd. componenet default format mm/dd/yyyy thanks . love guys :d yes, use customformat specify format want. aware picker uses user's regional settings default format, might not want set (if care internationalization).

regex - php preg_match_all, returning multiple optional values when available -

example of haystack: interventions: --------------------- med given: versed - 9:50 pm med admin route: intravenous dosage: 20.00 mg med given: lidocaine - 9:50 pm med admin route: intravenous dosage: 150.00 mg med given: succinylcholine - 9:50 pm med admin route: intravenous dosage: 200.00 mg med given: oxygen - 7:23 pm dosage: 2.00 l/min med given: vancomycin med given: fentanyl med given: dopamine med given: dextrose med given: gentamicin as cans see, there times ( - h:mm am/pm), "med admin route: ..." , "dosage: ...", want name (versed, oxygen, etc) , if available - time (h:mm am/pm), route (intravenous, oral, etc) , dosage (20.00 mg, 2.00 l/min, etc) stored in array. i've thought i've had in past when throw different haystack @ it fails... note appears there tab instead of space between variables time-admin or admin-dosage... luckily you, have time on hands during lunch break :) in regex, ? after expression means accept

visual studio 2010 - Source control for multiple projects -

i've worked sourcegear vault sometime source control i've run problem - going more common. i have visual studio solutions looks so: -main solution - web app project - shared class library 1 - shared class library 2 the problem can bind solution 1 repository, class libraries shared, need used multiple solutions. is there source control solution knows of allow solution contain multiple projects, bound different repositories? thanks in advance al build shared libraries separately , reference assemblies. building of libraries can automated (e.g. using continuous integration), easy , efficient solution.

extjs apply formatting to grid column -

in extjs, if have grid definition this: xtype: 'grid', store: 'somestore', flex: 1, frame: true, loadmask: true, titlecollapse: true, cls: 'vline-on', ref: '../somegrid', id: 'somegrid', columns: [ { xtype: 'gridcolumn', header: 'id', dataindex: 'someid', sortable: true, width: 100 } is there way apply formatting column? example, field number , if wish set decimal precision..can it? or need apply formatting when store being loaded in java file? guess latter?? use "renderer" option. can define function there. example want show someid wrapped in tag: columns: [ { xtype: 'gridcolumn', header: 'id', dataindex: 'someid', sortable: true, width: 100, renderer: function(value) { // logic here return &q

ruby on rails 3 - devise 2 models 2 views problem with path -

context : rails 3.0.3 devise 1.1.5 , 1.2rc i have following devise rdoc rails g devise:install rails g devise user rails g devise employee rails g devise:views users rails g devise:views employees routes.rb devise_for :users devise_for :employees, :path => 'admin' devise.rb config.scoped_views = true rake routes gives new_user_session /users/sign_in(.:format) {:action=>"new", :controller=>"devise/sessions"} user_session post /users/sign_in(.:format) {:action=>"create", :controller=>"devise/sessions"} destroy_user_session /users/sign_out(.:format) {:action=>"destroy", :controller=>"devise/sessions"} user_password post /users/password(.:format) {:action=>"create", :controller=

gridview - how to disable a button outside my update panel? -

i have dotnet 2.0 web application. and there button outside update panel... inside update panel..i have gridview ...while sorting grid, need disable button outside update panel. please me. <table> <tr> <td> <updatepanel> <gridview /> </updatepanel> </td> </tr> <tr> <td> <button /> </td> </tr> <table> edit: i tried below code on server side sorting function - not working scriptmanager.registerstartupscript(this.page, this.gettype(), "", "<script>document.getelementbyid('" + ((button)dualgridtablerow.findcontrol(string.concat(webconstants.prioritytext, webconstants.uptext))).clientid + "').style.enabled ='false';</script>" , true); you can add disable functionality in onclick event of sort buttons(links). don't know if elegant, work. 1 point, if need disa

Regex in javascript fails every other time with identical input -

this question has answer here: why regexp global flag give wrong results? 4 answers a simple test script: <script type="text/javascript"> var reg = new regexp('#([a-f0-9]{3})$', 'gi'); (var = 0; < 10; i++) { console.log(reg.exec('#fff')); } </script> console output: ["#fff", "fff"] null ["#fff", "fff"] null ["#fff", "fff"] null ["#fff", "fff"] null ["#fff", "fff"] null why every other result null when input remains constant? when use global flag, regex becomes "sticky." say, uses counter variable track where last match found. rather matching beginning each time, sticky regex pick last match ended. counter reset 0 (the beginning) if entire match fails (which why works every-

python - setting breakpoints with nosetests --pdb option -

nosetests --pdb let's me halt upon error or failure, late needs. stepping through code during execution helps me debug problem is. however, nosetests helpful allow tests rely on relative imports (i.e. tests in package). how can set breakpoints before tests executed? i'm using: python -m pdb /path/to/my/nosetests testfile.py this solution isn't adequate. nosetests interfere pdb output, , keyboard controls (e.g. arrow keys) broken. using import pdb; pdb.set_trace() seem idea, nosetests blocking access pdb console. you can add import pdb; pdb.set_trace() anywhere in source want stop in debugger. make sure pass -s nose not capture stdout .

sql server - SQL address data is messy, how to clean it up in a query? -

i have address data stored in sql server 2000 database, , need pull out addresses given customer code. problem is, there lot of misspelled addresses, missing parts, etc. need clean somehow. need weed oout bad spellings, missing parts, etc , come "average" record. example, if new york spelled in 4 out of 5 records, should value returned. i can't modify data, validate on input, or that. can modify copy of data, or manipulate through query. i got partial answer here addresses stored in sql server have many small variations(errors) , need allow multiple valid addresses per code. sample data code name address1 address2 city state zip timesused 10003 american nutriton inc 2183 ball street olden utah 87401 177 10003 ameican nutrition inc 2183 ball street po box 1504 olden utah

Multiple Functions on a Single Event with JQuery/Javascript -

what best way call 2 functions upon single click event? there multiple elements requiring script, script must act upon element being clicked — not elements @ once. let me know if need provide more details. again help. $(function() { $('a').click(function() { func1(); func2(); }); });

cocoa - Formatted text encoding in binary plist -

i'm trying scripting edits binary plist file. plist describes objects contained in dvd studio pro file. appears text box in dvd studio pro encoded in plist base64 data describes text string along formatting. can't seem figure out how understand data. ideally, i'd able alter text string not formatting. following seems describe text box says "menu title here". there 2 strings, 1 key called "dictionary" , other called "string"; both cfdata. ideas how can parse or convert format can edit directly? i've been playing around writing little converter in cocoa, no luck yet. <dict> <key>dictionary</key> <data> batzdhjlyw10 exblzihoa4qb qisehaxou0rp y3rpb25hcnka hiqitlnpympl

How do I write arrays in pascal? -

is program correctly written array? program malaria_outbreak (input,output); var bc:real; lo:real; count:integer; num:integer; bloodtest:integer; registration:integer; clinic:string; doctorfee:integer; total:integer; nmb_payable:real; company:string; name:string; patient:array[1..10] of string begin clrscr; bc:=(0.8); lo:=(0.7); count:=(0); num:=(0); bloodtest:=(num * 700); registration:=(500); writeln('please enter name of patient'); readln(name); while (name <> 'end')do begin count:= 1 10 begin writeln('please enter clinic patient attends'); readln(clinic); if (clinic = 'type 1') begin doctorfee:=(800); end; if (clinic = 'type 2') begin doctorfee:=(1200); end; writeln('the doctor fee patient $',docto

iphone - iOS - 1000's of literal strings, how to handle? -

i have few thousand literal strings in app. i have them listed in .m file. i don't have problem doing way, , works app. is not best practice? should house string data in external db? thank you. several thousand literal strings sounds annoying, that's worst of it. database overkill , hard maintain. long can localize app when/if need to, should fine.

Getting glibc detected error when trying to delete parts of a matrix in C++ -

when run following code, keep getting glibc detected error when try use delete[] i[i] command (always on last run through of loop). right before loop tries delete i[i], print out values in last row of i, , shows supposed to, don't think issue has loop being large. doing wrong? (i've included every line of code **i shows up). edit 2: entirety of error message is: *** glibc detected *** getparams: free(): invalid next size (fast): 0x086861f0 *** ======= backtrace: ========= /lib/tls/i686/cmov/libc.so.6(+0x6b591)[0x271591] /lib/tls/i686/cmov/libc.so.6(+0x6cde8)[0x272de8] /lib/tls/i686/cmov/libc.so.6(cfree+0x6d)[0x275ecd] /usr/lib/libstdc++.so.6(_zdlpv+0x21)[0x1cb741] /usr/lib/libstdc++.so.6(_zdapv+0x1d)[0x1cb79d] getparams[0x804ac78] getparams[0x8048943] /lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe6)[0x21cbd6] getparams[0x8048731] ======= memory map: ======== 00110000-001f9000 r-xp 00000000 08:01 396979 /usr/lib/libstdc++.so.6.0.13 001f9000-001fa000 ---p 000e9000

c# - gridview, how to build a image url in code behind? -

i have gridview control contains image field. however, image url built several fields in returned dataset. how concatenate fields together, , @ point do can pass image url imagefield in gridview? guessing it's on rowdatabound don't know how access each of rows in dataset? thanks. i'm not sure trying concatenate without code example, perform concatenation before binding gridview , store in private member on class can access later in rowdatabound event. you can use row data bound event find control within row , set imageurl property. private string m_concaturl; protected void gridview_rowdatabound(object sender, gridviewroweventargs args) { if(args.row.rowtype == datacontrolrowtype.datarow) { image imgctrl = (image) args.row.findcontrol("imgctrl"); imgctrl.imageurl = m_concaturl; } }

Internet Explorerer Parses JSON differently than all other browsers in Rails -

i have json object. if parse in internet explorer: (rdb:776) parsed_json = activesupport::json.decode(params[:json]) standarderror exception: invalid json string yet if in other browser, same param succeeds.. what may cause of ? the json passes "{\"results\":[{\"date_paid\":\"2/27/2008\",\"interest_rate\":5.5,\"date_awarded\":\"02/02/2008\",\"total_interest\":7.66,\"tf\":0.0712328767123288,\"principal\":1955.96,\"amount_paid\":100.0},{\"date_paid\":\"12/31/2008\",\"interest_rate\":5.5,\"date_awarded\":\"02/28/2008\",\"total_interest\":86.14,\"tf\":0.843835616438356,\"principal\":1855.96,\"amount_paid\":0.0},{\"date_paid\":\"12/31/2009\",\"interest_rate\":4.0,\"date_awarded\":\"1/1/2009\",\"total_interest\":74.24,\"tf

asynchronous - Java AWT drawImage race condition - how to use synchronized to avoid it -

after many hours of debugging , analysis, have managed isolate cause of race condition. solving matter! to see race condition in action, recorded video way in debugging process. have since furthered understanding of situation please forgive poor commentary , silly mechanisms implemented part of debugging process. http://screencast.com/t/atak1novanjr so, situation: have double buffered implementation of surface (i.e. java.awt.frame or window) there ongoing thread loops continuously, invoking render process (which performs ui layout , renders backbuffer) , then, post-render, blits rendered area backbuffer screen. here's pseudo-code version (full version line 824 of surface.java ) of double buffered render: public renderedregions render() { // pseudo code renderedregions r = super.render(); if (r==null) // nothing rendered return (region in r) establish max bounds blit(max bounds) return r; } as awt surface implementation, impl

Zend framework registration + email confirmation -

do know how registration in zend require email confirmation? zend has mechanism easy? have found classes send emails dont know zend has special support email confirmation in registration process? thanks, what you're describing business process , such, not covered framework. have build yourself. the basic process go generate unique token , store against user record create email containing link confirmation page. include unique token in link other identifying fields require on confirmation page, check token against 1 saved user record. if match, complete registration.

sql - Aggregate Relational Algebra (Maximum) -

i working on homework assignment requires selection occur pulls out element containing specific attribute of maximum value compared other records. i've read number of sources online reference "aggregate" relational algebra function called maximum, don't describe how works using basic operators. how 1 select attribute containing maximum value? you can express aggregate functions basic operators. it's pretty neat thing. suppose have table t, , we'd find maximum of "value" field. first, should take cartesian product of t -- or rather copy of itself, t2. select rows t.value smaller t2.value: nets unwanted rows, value less value of other row. maximal values, should subtract these unwanted rows set of rows. , that's it. @ least that's basic idea, need use projections dimensions right. unfortunately have no idea how insert latex here, using relational algebra notation, it'd this: π(t.a1...tan, t.value)(t) - π(t.a1...tan,

iphone - Programmatically created ToolBar items not working on some of the frame positions -

i having weird problem programmatically created uitoolbar , uiwebview uiwebview frame size can changed , tool bar position calculated @ runtime. problem is, uitoolbar not taking touch events or uibarbuttenitems not clickable frame sizes. kind of pattern like, if webview starts xy(0,0) fine. move webview center, uitoolbar buttons below half works , on.. tested web view not overlapping @ point. tried bound uitoolbar structure using. (custom/pro grammatically/no nibs) created uiview uiwebview , uitoolbar, inside uiviewcontroller creating uiview desired frame. thank you when using view's inside views. how setting frame ? should use bound not frame..

How to protect drawable resource in Android application -

please tell me how protect our resource in apk package. simple rename-extract process, 1 can copy , thief application drawable resource images or soundfx files. question is, there way protect drawable resource in android application? the drawable needs accessible operating system, has readable. if want keep secure, consider storing encrypted raw asset, load it, decrypt bytestream , pass bitmapfactory. that, of course, has slight performance ramifications , force hand-code lot of stuff have done in xml otherwise. that aside, there many ways steal data - if it's drawable, people take screenshot.

methods - How to write Java function that returns values of multiple data types? -

for example, want create function can return number (negative, zero, or positive). however, based on exceptions, i'd function return boolean false is there way write function can return int or boolean ? ok, has received lot of responses. understand i'm approaching problem incorrectly , should throw sort of exception in method. better answer, i'm going provide example code. please don't make fun :) public class quad { public static void main (string[] args) { double a, b, c; a=1; b=-7; c=12; system.out.println("x = " + quadratic(a, b, c, 1)); // x = 4.0 system.out.println("x = " + quadratic(a, b, c, -1)); // x = 3.0 // "invalid" coefficients. let's throw exception here. how handle exception? a=4; b=4; c=16; system.out.println("x = " + quadratic(a, b, c, 1)); // x = nan system.out.println("x = " + quadratic(a, b, c, -1)); // x = nan } public static do