Posts

Showing posts from January, 2010

sql - Is there a default sort order for cursors in COBOL reading from DB2? -

i trying understand how following cobol cursor works: t43624 exec sql t43624 declare x_cursor cursor t43624 select t43624 t43624 ,b t43624 ,c t43624 ,d t43624 ,e t43624 ,f t43624 t43624 x t43624 t43624 l = :pp-l t43624 , m <= :pp-m t43624 , n = :pp-n t43624 , o = :pp-o t43624 , p = :pp-p t43624 , q = :pp-q t43624 end-exec. given there no order clause, in order rows returned? default have been set somewhere? there no default sort order results returned db/2 select statement. if need, or expect, data returned in order ordering must specified using order clause on sql predicate. you may find results appear ordered ordering artifact of access paths used db/2 resolve perdi

ios4 - Is there any way to test Venmo APIs from outside the US or on platforms other than the iPhone? -

i need implement venmo payment systems in our client's iphone application. our client in usa, i'm offsite developer based outside of usa. is there way work venmo apis outside of usa testing purposes? right now, venmo blocks ip addresses outside of united states. use vpn or proxy access venmo outside us.

python - Passing class names to dictionary (and parsing order) -

i have code looks following: class action(object): ... class specificaction1(action): ... class specificaction2(action): ... they specified in same file. before specification want put dictionary looks this: actions = { "specificaction1": specificaction1, "specificaction2": specificaction2 } the idea can import actions dictionary other modules , have 1 dictionary 1 canonical string representation of actions (they sent on network , other places need identifier). is possible "class pointers" in same way function pointers? , editor complains names undefined before dictionary declared before class definitions - true? also, if above possible can instantiate class: actions['specificaction2']() ? classes first-class citizens in python, i.e. can treat them other object. point of view construction fine, except have define actions dictionary @ end of file (because unlike other languages order important in pytho

android - Convert FragmentManager to MapView -

i'm using code show map @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); requestwindowfeature(window.feature_no_title); getwindow().setflags(windowmanager.layoutparams.flag_fullscreen, windowmanager.layoutparams.flag_fullscreen); setcontentview(r.layout.activity_main); fragmentmanager myfragmentmanager = getfragmentmanager(); mapfragment mymapfragment = (mapfragment)myfragmentmanager.findfragmentbyid(r.id.map); mymap = mymapfragment.getmap(); mymap.setmylocationenabled(true); mymap.setmaptype(googlemap.map_type_terrain); } and i'm using markers, drag them , delete them. if want make map mapview able draw lines using ondraw , touchevent in same time, how can convert mapview?

php - Create a price range from given min and max values -

given 2 values $min , $max , want create price range users choose from. example $min = 849; $max = 41259; my thresholds are: <10k 10k 25k 25k 40k 40k+ so, if min value 12000, first 1 in threshold not come. tried couple of things, none worked. highly appreciated. one solution use loop in php. $min = 123; $max = 345; for($i=$min;$i<$max;$i++){ echo $i."<br/>"; } change $min minimum , $max maximum. update: if want first , last i.e. min , max values should not displayed itself. use code $min = 123+1; $max = 345-1; for($i=$min;$i<$max;$i++){ echo $i."<br/>"; }

.net - Parse HTML in C# without AgilityPack -

i have html file, several input fields id, loaded c# string: <div> <input id="inpname" type="text" /> <input type="checkbox" /> </div> lets want add required attribute input id inpname . in jquery do: $('input#inpname').prop('required', true); q : how can achieve add attribute without adding htmlagilypack? can use xmldocument or choice regular expressions ? u can use xml objects like in http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.selectnodes.aspx and use xmlnode object take want http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.aspx you can use expressions search want http://www.w3schools.com/xpath/xpath_syntax.asp you can use code node xmldocument doc = new xmldocument(); doc.loadxml(myxmlcontent); xmlnode root = doc.documentelement; xmlnode mynode = root.selectsinglenode("mytag");

copying range of cells and pasting to the first empty row more effective code? Excel -

i have macro takes selection of cells "new search" , paste range first open cell in "past searches" i'm thinking code ineffective. have ideas of how can improve this? sub macro5() range("a3:j3").select range(selection, selection.end(xldown)).select selection.copy sheets("past searches").select range("a1").end(xldown).offset(1, 0).select activesheet.paste worksheets("new searches").activate application.cutcopymode = false end sub first, don't have use .select or .activate on cells/worksheets you'll manipulate, reference them directly. can slow down code. the .copy method can take destination parameter, don't have use .paste somewhere else. also, .end property isn't reliable. it's better use usedrange instead. you can pretty in 1 line. worksheets("new search").range("a3:j3").copy destination:=worksheets("past searches").usedrange.columns(1).offset(1, 0)

How to get a part data from a filename in Java? -

how part of data string: csvfile = "c:/users//phv/01surname local.csv" i need extract surname above string upd what think it? file f = new file(csvfile); string[] parts = f.getname().split(" "); string strparts = new string(parts[0]); string finfilename = strparts.substring(2, strparts.length()); i'm not sure understand question, assume want extract "surname". if that's correct, please try this: string surname = csvfile.substring(csvfile.lastindexof("/") + 3, csvfile.lastindexof(" "));

Laravel: How to respond with custom 404 error depending on route -

i'm using laravel4 framework , came across problem. i want display custom 404 error depending on requested url. for example: route::get('site/{something}', function($something){ return view::make('site/error/404'); }); and route::get('admin/{something}', function($something){ return view::make('admin/error/404'); }); the value of '$something' not important. shown example works 1 segment, i.e. 'site/foo' or 'admin/foo' . if request 'site/foo/bar' or 'admin/foo/bar' laravel throw default 404 error. app::missing(function($exception){ return '404: page not found'; }); i tried find in laravel4 documentation nothing right me. please :) thank you! in app/start/global.php app::missing(function($exception) { if (request::is('admin/*')) { return response::view('admin.missing',array(),404); } else if (request::is('site

vb6 - Converting VB 6 code to VB.NET -

i upgrading code vb 6 vb.net, , following code gives me error: (vb6.pixelstotwipsx(mvarpicture.clientrectangle.width) - (bdr + x), vb6.pixelstotwipsy(mvarpicture.clientrectangle.height) - (bdr + x)), mvarbordercolor, b the error is: error 6 end of statement expected. can me that? this full code: public sub draw() dim bdr, x short dim newx, newy double dim oldx, oldy double dim gridheight, gridwidth double dim mvarpicturebox system.windows.forms.picturebox on error goto nopicbox ' in case picbox isn't set yet 'upgrade_issue: picturebox property mvarpicturebox.autoredraw not upgraded. click more: 'ms-help://ms.vscc.v90/dv_commoner/local/redirect.htm?keyword="cc4c7ec0-c903-48fc-accc-81861d12da4a"' if mvarpicture.autoredraw = false mvarpicture.autoredraw = true 'upgrade_issue: picturebox method mvarpicturebox.cls not upgraded. click more: 'ms-help://ms.vscc.v90/dv_commoner/local/redirect.ht

javascript - validation for two select box using array -

i have array 'a' this var = new array(); a[key] =a[value]; a['mpp']='mpp'; a['pdf']='pdf'; a['excel']='xls'; a['word']='doc'; a['ppt']='ppt'; a['html']='html'; i have 2 select box 1 docformat contains a[key] , extension contains a[value], on submit have validate 2 select box array , can please suggest help? one way using jquery function validate(){ var key = $("#select-key").val(), val = $("#select-value").val(); return key in && a[key] == val; } assuming a array , select boxes have ids select-key , select-value respectively. hope helps.

How to run multiple jQuery effects at same time -

i trying achieve this. there box. set hide() in jquery. has fade in, @ same time, has move length top bottom. whatever length top bottom, fade in effect should begin when box start moving top , fade effect may complete when box completes it's movement top. here tried; <div id="div1">div</div> and $("#div1").animate({"margin-top": 200,}); $('#div1').fadein("slow"); but 2 functions use different time. how can this? here working fiddle. thanks in advance... :) try doing both animations css in same animate call: http://jsfiddle.net/xhrbq/ $("#div1").animate({ 'margin-top': 300, 'opacity': 1 }, 1000);

java - trouble with local time -

i use these codes local time: dateformat dateformat = new simpledateformat("yyyy/mm/dd hh:mm:ss"); calendar currenddate = calendar.getinstance(timezone.getdefault()); system.out.print("last update: "+dateformat.format(currenddate.gettime())); or: dateformat dateformat = new simpledateformat("yyyy/mm/dd hh:mm:ss"); calendar currenddate = calendar.getinstance(gettimezone("gmt+3.5")); system.out.print("last update: "+dateformat.format(currenddate.gettime())); but non of them give local time, both giving me gmt problem? note: using eclipse , android programming, codes above correctly work in java in android not! instead of system.out.print() use textview show time textview date = (textview) findviewbyid(r.id.gold_textview1); date.settext("last update: "+dateformat.format(currenddate.gettime())); please me find problem try date currentdate = new date() instead of calendar object. system.out.print()

windows - Batch File Date Format not right -

i have following code checks log file specific string, , based on datestamp matching executes tasks. now code below works great on windows 7 machine date-time format of: yy-mm-dd hh:mm, executing exact same batch file on windows server 2008 date-time format of: yy-mm-dd hh:mm not work - suspect might date-time format... confirm if date-time format used in batch file work yy-dd-mm date format? also, if date time format in log file differs dat-time format of log file itself? code still work? for /f "tokens=2" %%a in ('findstr /i /c:"database ok" log.txt') set "success=%%a" %%a in (log.txt) set "filedate=%%~ta" if "%filedate:~0,10%"=="%success%" ( call another.bat ) else ( >>otherlogfile.log echo(%date% %time% database unsuccessful ) thank you update 1: c:\utilities\filter>for %a in (logfile.txt) set "filedate=%~ta" c:\utilities\filter>set "filedate=2013-07-31 21:31&q

html - IE8 list formatting issue -

so have page bulleted items reason not coming in on ie8 should, can please steer me in right direction? http://careers.express-scripts.com/search?search=&category=&state=mo&csrf-token= thanks i don't have ie can't test instinct says might text-indent , padding on li's. you've got: #body_left ul li { font-family: helvetica,sans-serif; font-size: 13px; list-style: disc inside none; padding: 5px 0 5px 33px; text-indent: -1em; } but try: #body_left ul li { font-family: helvetica,sans-serif; font-size: 13px; padding: 5px 0; margin-left: 33px; }

mysql - How to show zero when no result is returned in grouped joined query -

i trying compact down number of queries on (php) mysql database , have following problem: for last 10 posted comments, show average comment rating , whether there image associated comment the mysql is: select obj_images.fk_obj_id has_images, avg(obj_rating) rating /*other joined tables obj_comments omitted clarity ...*/ obj_comments inner join obj_images on obj_comments.fk_obj_id=obj_images.fk_obj_id group obj_comments.fk_obj_id order comment_id desc limit 10 even when there no image associated comment, has_images still returns value, ideally want return 0 when there no images associated comment , 1 when there images associated it what missing? thanks tips use outer join , ifnull() instead of inner join. select avg(c.obj_rating) avg_rating ifnull(i.fk_obj_id, 0) has_images, /* ... */ obj_comments c left join obj_images on c.fk_obj_id = i.fk_obj_id group c.fk_obj_id order c.comment_id desc limit 10 also think declaring table aliases

java - storing a string into an array causes an ArrayIndexOutOfBoundsException error -

int x = 0; string[] qequivalent = {}; string s = sc.nextline(); string[] question2 = s.split(" "); (int = 0; < question2.length; i++) { system.out.println(question2[i]); x++; } //debug system.out.println(x); string s2 = sc2.nextline(); string[] answer = s2.split(" "); (int c = 0; c < answer.length; c++) { system.out.println(answer[c]); } //debug int y; string u = sn.nextline(); string[] t = u.split(" "); (y = 0; y < question2.length; y++) { (int w = 0; w < t.length; w++) { if (t[w].equals(question2[y])) { qequivalent[y] = "adj"; system.out.println(qequivalent[y]); break; } } } this line of codes have of now. when string in question2 found in string[] t, should store string "adj" in string[] qequivalent. can't

html - PHP Search Sub-Directory for a specific file -

i've been looking solution problem. have website has many files in many sub-directories (all in 1 main directory). need search function can search part of name of file , return back. need function not case sensitive (i.e. if file name caps , user searches lower case should still find file). function have below works 1 directory , not work recursively. please me modify code work multiple directories. <?php $dirname = "./office precedents/";//directory search in. *must have trailing slash* $findme = $_post["search"]; $dir = opendir($dirname); while(false != ($file = readdir($dir))){ //loop every item in directory. if(($file != ".") , ($file != "..") , ($file != ".ds_store") , ($file != "search.php")) { //exclude these files search $pos = stripos($file, $findme); if ($pos !== false){ $thereisafile = true;//tell script found. //display search results l

sqlite3 - Consequences of -wal file disappearing in SQLite? -

if sqlite database using write-ahead logging interrupted un-checkpointed transactions (due power failure or whatever), reopened temporary -wal file missing, database open cleanly state of last checkpoint, or corrupted in way? we're trying sqlite working icloud (yes, know you're not supposed that, make windows , android app , need cross-platform database solution), , think wal provides potential way avoid having maintain 2 copies of our database - we'd keep -wal file outside of icloud store main database in it, avoiding problem of icloud backing rollback journals (or backing databases mid-transaction without journals). the file format documentation mentions "hot wal file", applies uncommitted data. the database file not contain information committed data in -wal file, i.e., transactions before checkpoint typically not alter main database file @ all. therefore, deleting -wal file restore database state after last checkpoint (which outdated, consi

acceptance testing - Specflow Feature File Best Practice -

thanks in advance help. my question pertains best practices inside specflow feature file? question: is using wait command inside of feature file considered bad practice. example: and click on username , wait 5 seconds , input new value last name the wait command forces 5 second wait. doing make sure page loaded prevent "element not found" errors or other errors. make sure have clean page manipulate. would better practice use wait inside of step file itself? //using fluent automation i.waituntil(() => ()); //or i.wait(); //timespan my reasoning not using fluent automation wait is: by utilizing fluent automation method dependent on default timeout in settings object. default timeout in cases may not long enough or may long. seems verbose me continually change/reset settings object benefit being remove wait commands feature file. so best practice? thanks, -n i think best practice keep feature file scenarios, , free of implementati

python - Use Javascript To Print Page As PDF (With Django) -

i need convert web page pdf because won't print/look correct if isn't converted. because web page big, html document browser try , split multiple pages (not vertically, fine, horizontally, bad). though planned on server side django, realized virtually of available libraries written python2, when using python 3. so other option client side. thing find on stackoverflow this: convert html ( having javascript ) pdf using javascript , of answers in java, not javascript. i think ideal solution change style more printer friendly rather making pdf. if have pdf created javascript, there's library jspdf http://parall.ax/products/jspdf out there creating pdfs javascript. have write on own parse page create matching pdf. if can use php, recommend using dompdf, written translate webpages pdfs, there less work involved there. https://github.com/dompdf/dompdf i've used library, , seems decent, though doesn't support css styling.

android - Is it idiomatic to call FEATURE_ACTION_BAR from code -

my question related activating actionbar in android app. more idiomatic getwindow().requestfeature(window.feature_action_bar) or more idiomatic force through theme using ? if you're asking "best practice" recommended google, take @ sample applications on developer's page. you'll notice don't see requestfeature() used. action bar default holo themes, in cases don't need address problem @ all. even if you're using new compatlibrary, should use theme. new action bar guide doesn't mention requestfeature() . edit: ah, demos did have use of this. however, "normally set activity's theme" , tell how instead. // action bar window feature. feature must requested // before setting content view. set automatically // activity's theme in manifest. provided system // theme theme.withactionbar enables you. use // use theme.notitlebar. can add action bar own themes // adding element <item name="android:window

unit testing - Enforcing code standards in git before commit is accepted -

alright, here's scenario: team of developers wants ensure new code matches defined coding standards , unit tests passing before commit accepted. here's trick, of tests need run on dedicated testing machine , not have access modify git server must done using local commit hook on each dev machine. while specs pretty strict (we're not switching windows or subversion, example) real world problem there flexibility if have solution fits. we're using git , *nix. the updated code needs sent server run test suite. a list of modified files needs provided ensure match coding standard. its rather large codebase, should send smallest amount of information necessary ensure identical copies of codebase. if tests fail message needs displayed error , commit should blocked. assume trust our dev team , okay allow tests bypassed --no-verify option. the question: best way test server sync local environment run tests? sort of hash-to-hash matching git patch new commit? ski

R roxygen2 Error in preref.parsers[[tag]] %||% parse.unknown: attempt to use zero-length variable name -

i intend use roxygen2 roxygenize() update package documentation after bit of work. have done in past. on instance encountered following error message: ==> roxygenize('.', roclets=c('rd', 'collate', 'namespace')) * checking changes ... error error in preref.parsers[[tag]] %||% parse.unknown : attempt use zero-length variable name i don't doubt have problem variable name somewhere , though don't know how locate source of error. r cmd check doesn't identify problems other collate , namespace issues mean use roxygen2 rectify... any appreciated. to track problem down systematically removed files , re-ran roxygenize() until no longer failed run through. having identified offending file, suggested, misplaced "@". this results in aforementioned error: #' @ export so fix misplaced space , problem solved: #' @export the difficult aspect locating typo.

php - ../ in relative URL not behaving as expected -

almost documentation can find tells me using " ../ " in relative urls goes 1 level current directory. so if in file @ " html/testing/new_version/admin/login.php " i use following relative url " ../images/fail.gif " server should looking fail.gif @ " html/testing/new_version/images/fail.gif " . but come file not found error. it's looking file in "html/images/fail.gif" why that? php setting of sort?

html - PHP error when trying to integrate facebook PHP SDK -

i’m new php , tying set page users can login using facebook php sdk , javascript sdk. keep getting fallowing error , don’t seem able find solution. saw similar post in here couldn’t give solution error. parse error: syntax error, unexpected t_string, expecting ',' or ';' in /homepages/9/d321009915/htdocs/kno_login/login.php on line 2 here code: <?php echo '<div id='fb-root'></div>'; require_once("facebook.php"); $config = array(); $config['appid'] = 'some id'; $config['secret'] = 'something here'; $facebook = new facebook($config); ?> <script> window.fbasyncinit = function() { fb.init({ appid : '293441190799565', // app id channelurl : '//www.reyesmotion.com/kno_login/channel.html', // channel file status : true, // check login status cookie : true, // enable cookies allow server access session xfbml : true // parse

iis 7 - WMI access to IIS7 -

we have internal tool enumerates iis sites , applications server. uses code similar this: using (var servermanager = servermanager.openremote(servername)) { var site = servermanager.sites[sitename]; // slow // , starting enumerate applications incredibly slow foreach (var application in site.applications) { // ... } } the problem i'm having when sites collection accessed, response time slow when connecting server on our vpn. accessing applications site slower. theory slowness caused fact entire set of metadata sites sent on wire. however, need subset of site data. my theory if switched code using wmi queries, i'd able query specific fields concern application (like select name site ). unfortunately, when trying explore wmi objects in wmi cim studio, local iis 7.5, none of objects i'd expect present, site , application objects. i'm using root\webadministration namespace. does of wmi stuff work iis 7.5? ensured "iis 6 wmi

Client/server: how to synchronize UDP send and receive in C? -

i writing simple web server , client using udp , far: the programs can connect each other, the client can send request, the server can read request, the server can recognize client's ip address , client's port, , the server can send message client my problem client code gets stuck waiting in rcvfrom function, after server has sent response. here function supposed pick server message , return number of bytes read socket: ssize_t receive_from_server(rdp_socket *rsocket, char *buffer, size_t buf_len){ socklen_t sendsize = sizeof(rsocket->server_addr); bzero(&(rsocket->server_addr), sendsize); //stuck here: return recvfrom(rsocket->sockfd, buffer, buf_len, 0, (struct sockaddr*)&(rsocket->server_addr), &sendsize); } i set sockopts both so_sndtimeo , so_rcvtimeo timeout after few seconds. question: in short term future adding acknowledgements (acks) reliable data transfer. imagine missing acks issue i'm wonderi

ruby - Did Rails Routing change the way it handles the params[:path]? -

i upgraded site ruby 1.8.7 ruby 1.9.2, , rails 3.0.x 3.2.x. noticed of legacy urls weren't being handled correctly anymore, , wanted diagnose issue. here's noticed. http://myapp.com/links/oldlink.html had, in old app, provided params[:path] of /links/oldlink.html , now providing links/oldlink . it's dropping leading forwardslash file extension. can me figure out what's going on here? of course can manually change legacy strings in database drop forward slashes , file extensions, seems hacky solution, , want make sure understand underlying principles account change in rails routing behavior. thanks! you should try in routes.rb match '/foo', :to => redirect('/foo.html')

python - A way to show/hide a field on Django -

i have list display in django admin list_display = ('product', 'price', 'purchase_date', 'confirmed', 'get_po_number', 'notes') in models.py: class purchaseorder(models.model): notes = models.textfield( null=true, blank= true) this looks here: [1]: http://i.imgur.com/zykmpof.png ' as can see 'notes' take lot of room, there way can view/hide field click of button? instead of doing button, can resize field become smaller. class purchaseadmin(admin.modeladmin): formfield_overrides = { models.charfield: {'widget': textinput(attrs={'size':'20'})}, models.textfield: {'widget': textarea(attrs={'rows':4, 'cols':40})}, } admin.site.register(purchaseorder, purchaseadmin) if want have button, can use custom inline class define fields: class custominline(admin.tabularinline): readonly_fields = [...'link',...] # important part def

c# - asp.net report viewer error basics : operation not allowed -

i'm trying handle on basics of report viewer control in asp.net webforms project c#. i'm using adventure work reports feel basics. i have report called salesordernumber under report parts on sql server i want able view @ point if (!page.ispostback) { // set processing mode reportviewer remote reportviewer1.processingmode = processingmode.remote; serverreport serverreport = reportviewer1.serverreport; // set report server url , report path serverreport.reportserverurl = new uri("(!removed!"); serverreport.reportpath = "/report parts/salesordernumber"; // create sales order number report parameter reportparameter salesordernumber = new reportparameter(); salesordernumber.name = "salesordernumber"; salesordernumber.values.add(&q

graphics - Old 8 bit retro video emulation - sprite drawing -

i'm trying understand how sprites drawn onto scanlines of example vdp 9929a graphics chip, emulation. there limit of 4 sprites per scanline, mean cannot have more 4 sprites same y coordinate? if cascade them draw 32 sprites on each line below 1 , 1 pixel right of each other overlapping each other, result in centre of 16 sprites being drawn on same line. still drawn correctly not scanline relating starting y coord. hope i'm making sense. thanks in advance. there can no more 4 sprites on single scanline; additional sprites' horizontal pixels dropped. sprites higher priority drawn first. in other words, each line, chip draw 4 sprites highest priority exist on line, not start on line. 1111 3333 5555 1111 2222 3333 4444 5555 6666 1111 2222 3333 4444 5555 6666 1111 2222 3333 4444 5555 6666 2222 4444 6666 ....where 1 highest prio, scan line 1 draw sprite 1,3,5, scan line 2-4 draw 1,2,3,4, scanline 5 d

ActionListener works perfectly after second time it's pressed -

entercommand.addactionlistener(new actionlistener() { public void actionperformed(actionevent event) { string userinput = enterword.gettext(); string userinput2 = entersecondword.gettext(); if (" ".equals(userinput) || " ".equalsignorecase(userinput2)) { joptionpane.showmessagedialog(null, "the space empty please try again"); } else { enterword.settext(" "); entersecondword.settext(" "); system.out.println("test"); japanesestudiesexcel je = new japanesestudiesexcel(); je.japanesestudiesexcel(userinput, userinput2); } ; } }); it checks input in fieldbox second time listener fired, first time not work. better explain this, when user enters nothing doesn't check empty string writes empty box excel. second time actionlistener fired

objective c - Listen for iOS screen capture event -

is there way listen screen capture event on idevice? logic: user takes screen capture using 'power' plus 'home' button combination. event triggered , listening application loads. application modifies captured image , exits. the application listen save camera roll event , allow same types of modification. thank in advance feedback. there no way directly... there bit of workaround though explained here: http://tumblr.jeremyjohnstone.com/post/38503925370/how-to-detect-screenshots-on-ios-like-snapchat

ruby on rails - How to populate a dropdown [rails4] -

so, have app lets users upload , comment on songs. however, i'd add genres category. when users upload songs they'll able choose genre of song. when add search. for quick overview of code see: www.github.com/apane/leap i'm guessing i'd add genres table db , associate songs e.g: genre belongs_to song, song has_many genres. but after i'm stumped. how populate genres dropdown? rails g model genre name rails g model genre_song genre:belongs_to song:belongs_to rake db:migrate models/genre.rb has_many :genre_songs has_many :songs, through: :genre_song models/song.rb has_many :genre_songs has_many :genres, through: :genre_song def self.tagged_with(name) genre.find_by_name!(name).songs end def tag_list genres.map(&:name).join(", ") end def tag_list=(names) self.genres = names.split(",").map |n| genre.where(name: n.strip).first_or_create! end end songs/index.html.erb genres: <%= raw song.genres.map(&a

Reversing "group" of strings in Python -

how reverse "groups" (not list) of strings? example convert "123456789" "321654987" given "group" size equals 3. followings code turns out print empty strings: string = "12345678901234567890" new_string = "" in range(0, len(string), 5): new_string = new_string + string[i:i+5:-1] print (new_string) thanks input , advice. when using negative step, swap start , end values too: new_string += string[i + 4:i - 1 if else none:-1] note end value excluded, , none should used include first character ( -1 slice end again , string[4:-1:-1] empty). demo: >>> string = "12345678901234567890" >>> new_string = "" >>> in range(0, len(string), 5): ... new_string = new_string + string[i + 4:i - 1 if else none:-1] ... >>> new_string '54321098765432109876' however, may easier first slice, reverse, , save headaches of such slicings: new_string

android - OnItemSelectedListener, ListView and item recycling -

i have bunch of items in listview. each item contains several editable views. want save changes user makes these. event save occur when item loses focus. i see 2 ways: view.onfocuschangelistener() onfocuschange(view v, boolean hasfocus) this works messy since each item contains several editable views. rather save when whole item defocused. attempts simplify far have complicated things. if there onitemdeselectedlistener perfect, there opposite: adapterview.onitemselectedlistener() onitemselected(adapterview<?> adapterview, view view, int i, long l) on surface looks good. create variable lastselectedview know last selected (deselected) item was. problem how listview recycles views. believe there no guarantee adapter has not recycled lastselectedview , changed data contains. reasonable assumption? is there reasonable way around recycling view problem onitemselectedlistener? if you're using single selection, selecting item "deselect"

javascript - Match simple regex pattern using JS (key: value) -

i have simple scenario want match follow , capture value: stuff_in_string, env: 'local', // want match , capture content in quotes more_stuff_in_string i have never written regex pattern before excuse attempt, aware totally wrong. this trying say: match "env:" followed none or more spaces followed single or double quote capture until.. the next single or double quote /env:*?\s+('|")+(.*?)+('|")/g thanks ps here #failed fiddle: http://jsfiddle.net/dfhge/ note: regex ended using (not answer below overkill needs): /env:\s+(?:"|')(\w+)(?:"|')/ you can use this: /\benv: (["'])([^"']*)\1/g where \1 backreference first capturing group, content in second. simple way simple cases. now, other cases like: env: "abc\"def" env: "abc\\" env: "abc\\\def" env: "abc'def" you must use more constraining pattern: first: avoid different quo

google maps api 3 - Extend polyline and handle mouse event -

i write js app draw lot of polylines using array of points, in avery point have additional properties in point (gps data, speed etc). i want show these additional props onmouseover or onmouseclick event. i have 2 ways: use standard polylines , event handler. in case can't determine additional properties start point of polyline cause can't save these props in polyline properties. there 1 solution - save in array additional properties , try find them latlng of first point of polyline, it's slow guess.. extend polyline , save additional properties in new object, can't extend mouse events :( to extend polyline use code: function mypolyline(prop, opts){ this.prop = prop; this.polyline = new google.maps.polyline(opts); } mypolyline.prototype.setmap = function(map) { return this.polyline.setmap(map); } mypolyline.prototype.getpath = function() { return this.polyline.getpath(); } mypolyline.prototype.addlistener= function(prop) { return t

eclipse - How do I add/use an embedded SQLite in a Java project? -

i'm trying add embedded database application, have no clue begin. far i've found should download sqlite-jdbc driver , add .jar project. there i'm kind of lost, there tutorials me started or helpful tips? also, i'm using eclipse ide, if there's within there simplify process, feel free add well! you want dependency management here? read on maven (very easy), write maven pom.xml file , load eclipse way. eclipse , netbeans understand maven now. no need learn eclipse-specific way since maven work in netbeans eclipse , simple run on command line too. based on search.maven.org says, dependency in maven added standard pom file latest: <dependency> <groupid>org.xerial</groupid> <artifactid>sqlite-jdbc</artifactid> <version>3.7.15-m1</version> </dependency>

symfony - How do I generate ID when I have composite keys in Doctrine? -

i have entity composite keys. see below: class bankaccount { /** * @orm\id * @orm\column(type="integer") * */ protected $bank; /** * @orm\id * @orm\manytoone(targetentity="companybundle\entity\company") */ protected $company; ... } because doctrine has issues composite keys won't generates sequences (i'm working in postgresql), how deal in order generate $bank pk? if sounds don't want composite key, primary key on $bank , foreign key on $company . if that's case, class bankaccount { /** * @orm\id * @orm\column(type="integer") * @orm\generatedvalue(strategy="auto") */ protected $bank; /** * @orm\manytoone(targetentity="companybundle\entity\company") */ protected $company; ... } should it.

authentication - jQuery is Undefined, json is undefined, 'fn' is null or not an object -

Image
i updated jquery, unobtrusive ajax , other libraries in asp.net mvc4 website. things working pretty fine till friday both on localhost on server i'm totally stuck in many weird errors. errors 1. localhost not resolving 127.0.0.1 : have no idea made change everytime press "run" button visual studio, browser not open http:localhost:53381 link instead goes http://173.6.120.31/ - in fact gets nothing. "operation time out" error after time. if enter http://127.0.0.1 in browser manually website works. 2. jquery, json scripts not published server when publish website server , try access site browser on system site works properly. however on other system, jquery related components has stopped working in internet explorer. it throws 'jquery undefined', json undefined etc errors on html page. i googled more , found windows authentication culprit here. using windows authentication , there 2 types of authentication mechanism i.e. negotiat

coordinates - firefox returning 0 for this.x and this.y in jquery hover -

using hover function on set of elements: $('.thumb-image').hover(function () { alert(this.x); this works fine in chrome firefox (22)...both x , y 0. i realized should not using this.x , this.y ..it returning undefined in ie. so instead used jens fransden's gettop , getleft answer @ bottom of post: get position of div/span tag this gets me need in ff , ie chrome

python - Matching an input from a string of characters? -

suppose have string -> (a,b,c,1,2,3) the user pick character string, perhaps b? pickcharacter=raw_input("pick character? ") user inputs, 'b' the code recognizes 'b' character within string , accepts input. whereas if user inputs 'f', program reject input because character not within string. how can determine if user picks 1 of following characters list? string_list = strng.split(",") if pick in string_list: print "yep" else: print "nope"

ember.js - Ember-Data handling 401’s -

any thoughts on handling 401 errors? in application initializer i'm deferring readiness , fetching current user via ember-data. if receive 401 app dies , becomes unusable. i'd handle error, , advancereadiness. cant seem find workaround this. info appreciated! gist here: https://gist.github.com/unknpwn/6126462 i noticed there similar topic here , seems out of date. application.initializer not correct place put logic. synchronous , it's purpose things adding custom objects ioc container, etc. code better suited in model hooks of applicationroute . app.applicationroute = ember.route.extend({ beforemodel: function() { return app.user.find({ filter: "authenticated" }); }, setupcontroller: function(controller, model) { controller.set('loggedin', true); controller.set('currentuser', model);// or property of model }, events: function() { error: function(err) { // error handler called in case of error.

c# - HttpListener in mono can't process more than 2 requests in the same time? -

i faced problem in multi-threaded http requests processing httplistener in mono. looks httplistener.begingetcontext(_handlerequestcallback, null) can't process more 2 requests "in same time". wrote small test: using system; using system.net; using nunit.framework; using system.io; using log4net; using system.threading; namespace other { public class listenertest { private ilog _log; private httplistener _httplistener; private const int port = 8080; private const int requests = 20; private asynccallback _handlerequestcallback; [testfixturesetup] public void setup() { servicepointmanager.defaultconnectionlimit = requests; threadpool.setminthreads(requests, requests); threadpool.setmaxthreads(requests, requests); _httplistener = new httplistener(); _httplistener.prefixes.add(string.format("http://*:{0}/", port));

SVN keyword substitution in pre-commit hook -

i have 2 versions of same file svn, don't have access repository. need know if equal, contain keywords substituted svn. these keywords different when rest text lines same. what proper way clean off svn keywords? is possible compare files ignoring values of svn keywords? there convenient class svntranslator in svnkit. i'm looking command line analogue.

iphone - Strange iOS VoiceOver behavior -

some of testers reports me strange behavior , know if else has seen , potential fix. the problem quite simple. use ver uiaccessibilitytraitdirectinteraction . before user can access views set such need tap 1 more time let voiceover activate direct interaction. some users report in random situation if touch view vo can't allow direct interaction. strange thing happens if stop/reset device ando/or exit app through application switch. i'm sorry if can't give more details, can't find origin/trigger of bug/problem. has else had similar situation?

powershell - Converting byte array to true/false -

through various different posts on stackoverflow , other places able put powershell script ftp uploads files , works great. wanted add bit more verbosity it. see code below: foreach ($file in $uploadfiles) { # create full path file on remote server (odd okay!) $ftp_command = $ftp + $file # debugging #$ftp_command # create new uri object full path of file $uri = new-object system.uri($ftp_command) #for debugging #$uri # our upload remote server - uri object, full path local file #$responsearray = $ftpclient.uploadfile($uri,$file.fullname) $result = $ftpclient.uploadfile($uri,$file.fullname) if ($result) { $file.fullname + " uploaded successfully" } else { $file.fullname + " not uploaded successfully" } } basically after file uploaded wanted check , see if successful or not. upload file supposed return byte array ( http://msdn.microsoft.com/en-us/library/36s52zhs(v=vs.80).aspx ; a byte array containing body of response resource. ). i&#

"parse" function in Language.Haskell.Exts.Parser? -

there function called parse in title module. has type signature parse :: string -> parseresult ast i have been working @ while , can't figure out how use it. i'm sure obvious not seeing it. in advance! the language.haskell.exts.parser module handles parsing haskell source code appropriate syntax tree. parse general function handle parsing string of haskell source instance of parseable class. exp (a haskell expression), parse defined as: instance parseable exp parse = parseexp so, use parse function, provide type declaration if 1 cannot inferred. example, parse expression "5 + 5": parse "5 + 5" :: parseresult exp which equivalent to: parseexp "5 + 5" in ghci, both return: parseok (infixapp (lit (int 5)) (qvarop (unqual (symbol "+"))) (lit (int 5)))

Emacs embedded in a Qt Application -

Image
i've tried embed emacs in qt application using qx11embedcontainer , , works 2 important exception. first of all, here code: #include <qx11embedwidget> #include <qtgui> #include <qapplication> int main(int argc, char *argv[]) { qapplication app(argc, argv); qx11embedcontainer container; container.show(); container.resize(500, 500); qprocess* process = new qprocess(&container); qstring executable("emacsclient"); qstringlist arguments; arguments << "--parent-id" << qstring::number(container.winid()); process->start(executable, arguments); int status = app.exec(); process->close(); return status; } and compilation , execution line (and previous thrown of emacs server): $ emacs -q --daemon & // filtered output $ g++ test.cpp -lqtgui -lqtcore -i/usr/include/qt4/qtcore -i/usr/include/qt4/qtgui -i/usr/include/qt4 $ ./a.out and finally, result: but, when or if try write in minibuf

vba - What do I set "Dim y As"? -

so i'm trying order list 1 through whatever bottom # is. within doing i'm in way moving of information right. i'm going bottom of selection find bottom of list in column b. , left 1, find bottom column fill in # system way down bottom of list. private sub commandbutton2_click() 'my problem don't know set "dim y range" know range 'incorrect along long, , integer. dim y range sheets("palmfamily").select columns("a:a").select selection.insert shift:=xltoright, copyorigin:=xlformatfromleftorabove range("a1").select activecell.formular1c1 = "1" range("a2").select activecell.formular1c1 = "2" range("a3").select activecell.formular1c1 = "3" range("a1:a3").select 'as can notice have weird code '" y = range("b1").end(xldown).offset(0, -1)" i'm trying go bottom

database - Using Microsoft.Fakes framework in Coded UI Tests -

am working on coded ui tests web application. trying isolate repository method calls same way i'm doing in unit , integration tests, i.e. using microsoft.fakes framework. seems ui tests fakes not working, because real method still called instead of shim. without isolation ui test results in affecting database (for example adding new user when testing registration process) makes not reusable. wondering whether possible fake/mock methods , avoid setting test database , test web site each time need run coded ui tests. didn't find useful information related issue, grateful help. in case of need here link simple example: https://www.dropbox.com/s/m6les7pmto14njq/testcodeduitest.zip vs 2012 solution 1 class library (containing class method throws exception), 1 web application (containing page 1 button on calls mentioned method) , 1 coded ui test contains shim of method , opens ie, navigates page , clicks button. coded ui tests real application or real website. code

Stripe checkout.js with coupons -

i'm using stripe's checkout.js because it's easy setup , use. there way add coupons? <script src="https://checkout.stripe.com/v2/checkout.js" class="stripe-button" data-key="pk_test_czwzktp2tactuloeoqbmtrzg" data-amount="2000" data-name="demo site" data-description="2 widgets ($20.00)" data-image="/128x128.png"> </script> stripe checkout not support coupons. it's not listed in documentation , either button or custom integration. one might wonder if there secret feature. however, using undocumented features, when comes payment processor bad idea. full stop. this being stack overflow - let's keep digging! fire jsfiddle. paste code html section. open developer tools can see network requests. there en.json, internationalized strings file. if there input coupons, there ought label saying "enter coupon code" or similar. there none.

Rails bootstrap-editable-rails not displaying current text -

i'm trying use gem 'bootstrap-editable-rails' in-line edit text column. want display current text in column. but, right displays "empty" instead. if click on , enter new text, replaces column value in database - updating working. the table called "taskup". text column called "comments". this code in view file: <a href="#" class="answer" data-type="text" data-pk="1" data-resource="taskup" data-name="comments" data-url="/taskups/<%= taskup.id %>" ></a> and coffee script: $(".answer").editable() thanks help! almost! you're missing set value inside tag <a href="#" class="answer" data-type="text" data-pk="1" data-resource="taskup" data-name="comments" data-url="/taskups/<%= taskup.id %>" > <%= taskup.comments ? taskup.comments : &

io - Writing single bytes to a QDataStream -

i want write series of bytes qdatastream . when viewed in hex editor, i'd resulting file this: 0x dead my attempt looks this: qfile file("test.txt"); file.open(qiodevice::writeonly); qdatastream stream(&file); stream << ((char)0xde); stream << ((char)0xad); file.close(); when open test.txt hex editor, can see instead of writing these single bytes, datastream has left-padded them full words, , file looks this: 0x ffff ffde ffff ffad what's right way this? the qiodevice left-shift operator ( << ) doesn't have overloaded definition char primitive, cast int . it have definition qint8 type. changing code fixes output: stream << ((qint8) 0xde); stream << ((qint8) 0xad);

c# - HttpClient Not Saving Cookies -

i using new httpclient handle project's web surfing needs; however, although correctly set, httpclient not save cookies cookie container , empty. code private cookiecontainer _cookiecontainer = new cookiecontainer(); private httpclient httpclient { get; set; } private httpclienthandler httpclienthandler { get; set; } public initialize() { httpclienthandler = new httpclienthandler { allowautoredirect = true, usecookies = true, cookiecontainer = _cookiecontainer }; httpclient = new httpclient(httpclienthandler); } public cookiecontainer cookies { { return _cookiecontainer; } set { _cookiecontainer = value; } } public void test() { //this empty, although sure site saving login cookies var cookies = cookies; } weird... did tried directly use httpclienthandler's cookiecontainer ? code :

iphone - How to reduce PNG size in ios for email sharing -

now trying share png file on app. i opened 2 mb png on app , share png email on app. but, email said image size 20 mb. how can reduce png size email sharing? consider using jpeg, png designed quality, not size. are creating uiimage or reading directly file? if absolutely sure correct size beforehand, , being resize, read file directly nsdata file , add octects attachment stream, jpeg nicer size.

django - Way to not duplicate codes between "models.py" and "forms.py"? -

i'm writing custom user model field. while doing this, realized duplicating codes between "models.py" , "forms.py"?? for example: models.py class myuser(abstractbaseuser): email = models.emailfield( verbose_name='email address', max_length=255, unique=true, db_index=true, ) full_name = forms.charfield( max_length=64, ) username_field = 'email' required_fields = ['full_name'] ... forms.py class registrationform(forms.form): error_css_class = 'error' required_css_class = 'required' email = forms.emailfield( label=_("email"), ) full_name = forms.charfield( label=_("full name"), ) password1 = forms.charfield( widget=forms.passwordinput, label=_("password"), ) password2 = forms.charfield( widget=forms.passwordinput, label=_("pa