Posts

Showing posts from June, 2012

php - RSS Feed "Updating Too Often" -

this may or may not silly question know little of mysterious ways of rss feeds, can put me straight! i have website rss feed of news items. user has complained feed updating crazily frequently, without change in top 5 news items displayed. i'm ashamed don't use rss feeds personally, don't know implies 1 "updating often" - can see how annoying, if keep checking "updated feed" find no new content, or worse if receiving continual alerts of non-existent updates. say, don't have clear picture of how rss feed consumption works. the next question is, if way our site generating rss feed problem, can it? top news items aren't changing incredibly frequently. it's possible, not certain, automated scripts updating items in database related news items, though still, can't imagine how happening "crazily frequently". rss feeds, how work? re-generation of top news items count update everyone's rss readers, if top news items ...

java - starting a new activity in onCreate works only with delay -

i have simple activity shows 2 buttons, , load activity 1 finished loading. @override public void oncreate(bundle savedinstancestate) { dbg("starting on create"); super.oncreate(savedinstancestate); dbg("stting content view"); setcontentview(r.layout.main); createdrpopup(); } private void createdrpopup(){ dbg( "created new activity"); startactivityforresult(new intent(this, drpopup.class), dr_popup_activity_id); } i don't errors code, new activity doesn't load properly. way blanc screen. but if call new activity delay, works fine. @override public void oncreate(bundle savedinstancestate) { dbg("starting on create"); super.oncreate(savedinstancestate); dbg("stting content view"); setcontentview(r.layout.main); thread splashtread = new thread() { @override public void run() { try { sleep(500); ...

java - while(Matcher.find()) is looping infinitely -

i modified following code oracle's java tutorials : import java.util.regex.pattern; import java.util.regex.matcher; public class regextestharness { public static void main(string[] args){ while (true) { pattern pattern = pattern.compile("foo"); matcher matcher = pattern.matcher("foo foo foo"); boolean found = false; while (matcher.find()) { system.out.format("i found text \"%s\" starting @ " + "index %d , ending @ index %d.%n", matcher.group(), matcher.start(), matcher.end()); found = true; } if(!found){ system.out.format("no match found.%n"); } } } } i trying learn how use regular expressions in java. (i feel pretty confident regex's, not java's classes using them.) using eclipse, not incredibly familar with. not figure out how console not initialized null (as tutorial warned), removed , using static ...

c# - Get a successful Ajax action to open another popup -

right i'm trying have ajax window open window on completion. basically, first window asks if user wants , second tells them successful. first needs yes or no , second needs ok. how tell ajax actionlink open 1 when done? i'm working in mvc 3 c#. right actionlink is: @ajax.actionlink("reset user password", "resetuserpw", "admin", new { username = model.username }, new ajaxoptions { confirm = "reset password?", httpmethod = "httpget" }) this works fine (i know there no onsuccess bit, fact mentioned later). executes logic fine , resets user's password. can't figure out how open window. here's controller action: public actionresult resetuserpw(string username) { string newexcept; membershipuser user = membership.getuser(username); if (user != null) { try { string newpassword = membership.generatepassword(8, 2); if...

.net - Async Queue Processing With Reactive Extensions -

there couple of articles on this, , have working...but want know how set max number of task threads observable subscriptions @ once. i have following parallelize async saving of log entries: private blockingcollection<ilogentry> logentryqueue; and logentryqueue = new blockingcollection<ilogentry>(); logentryqueue.getconsumingenumerable().toobservable(scheduler.taskpool).subscribe(savelogentry); to schedule saving...but how specify max threads scheduler use @ once? this not function of observable, function of scheduler. observable defines what , scheduler defines where . you'd need pass in custom scheduler. simple way subclass taskscheduler , override "maximumconcurrencylevel" property. http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler.maximumconcurrencylevel.aspx i found sample of on msdn: http://msdn.microsoft.com/en-us/library/ee789351.aspx edit: asked how go taskscheduler ischeduler. develope...

java - How to call a servlet from a batch program? -

i have situation have series of similar jsps, each of called servlet based upon option entered user. however, adjust these jsps can additionally called in batch program runs hourly on server, , write jsp output text file. can tell me how might done @ all? i thinking along lines of: url url = new java.net.url("http://127.0.0.1/myservlet"); urlconnection con = url.openconnection(); or there better way? ok: must doing foolish here because doesn't appear work: have batch program runs every hour , contains following code: try { url url = new java.net.url("http://127.0.0.1:8084//myapp//myservletmapping?par=parvalue"); urlconnection connection = url.openconnection(); connection.setrequestproperty("accept-charset", "utf-8"); connection.setdoinput(true); inputstream response = connection.getinputstream(); } catch (exception ex) { logger.error("error calling servlet in batch...

date - Java SimpleDateFormat parsing issue -

i'm trying parse date string got out of website in java using simpledateformat class, goes wrong , can't figure out why. the date strings come in following syntax: "13:37 - tue 28-jun-2011" so tried doing following: simpledateformat dateformat = new simpledateformat("hh:mm - eee dd-mmm-yyyy"); parseposition pos = new parseposition(0); date d = dateformat.parse("13:37 - tue 28-jun-2011", pos); as said before, doesn't work; when print system.out.println(pos.geterrorindex()); it prints "8", assume means error somewhere around eee part. i've tried different permutations nothing worked. doing wrong? thanks bompf if trying parse date work. dont know trying parseposition simpledateformat dateformat = new simpledateformat("hh:mm - eee dd-mmm-yyyy"); date d = dateformat.parse("13:37 - tue 28-jun-2011"); system.out.println(d);

Android ListView Item Colour and Scrolling issue -

i have messaging application displays list of received messages want highlight messages have not been read colour(yellow) whereas other list items remain default list item colour (white). i have managed using code below whenever scroll list of list items regardless of whether have been read or not "highlight" colour when scroll out of view , view. my list selector: <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_selected="true" android:drawable="@android:color/transparent" /> <item android:state_pressed="true" android:drawable="@android:color/transparent" /> <item android:state_selected="false" android:drawable="@drawable/messageunreadcolour" /> my code behind in array adapter applies setting: @override public view getview(int position, view convertview, viewgrou...

.net - Repository Pattern - aggregate root -

i trying head around aggregates roots lie in entity framework data model know repositories need create. if talk in relational database terms second, have exceptiongroup object , exception object (not system.exception!). exception belongs exceptiongroup , cannot exist without exceptiongroup. should have repository each object or single repository containing methods both? if have single repository methods follows... findallexceptionsbyexceptiongroup(int groupid) addexceptiongroup(exceptiongroup exceptiongroup) - because exception cannot exist without group. addexception(dataaccess.exception exception) deleteexceptiongroupbyid(int groupid) deleteexceptionbyid(int exceptionid) deleteexceptionbygroup(int groupid) if understand model correctly, sounds have repository exceptiongroup , exceptiongroup object encapsulate access , operations on exception instances (for ex., exposing collection of them). in way, forced relationship between 2 classes becomes apparent. jeff ...

php - How to get the value of a dropdown menu returned by Paypal? -

i'd know how value of dropdown menu paypal. everything works fine on paypal's side, exept fact don't know subscription members paying for. my form follow : <input type="hidden" name="on0" value="formula">formula <select name="os0"> <option value="basic">basic €5</option> <option value="standard">standard €10</option> <option value="vip">vip €20</option> </select> how can grab selected value please ? guess it's : $_post['os0'] ...but doesn't work. missing please ? any apreciated, ! i'm not sure if problem or not, if you're not using http post, values won't show in $_post['os0'] . try using $_request['os0'] instead , see if values way. you can read more $_post , $_request @ the php docs . can read how set form submission method @ the mozilla d...

Getting history from CVS archive -

i'm trying automatically extract data our cvs archive. when log on our current revision, can changes revision interested in single file: cvs log -rcurrent-release foo.cc but have interate through files, , no longer exist since deleted. is there way iterate through history entries in order in occurred? when try: cvs history i own history, in sequential order. i can specify user: cvs history -u foo but i'd everyone. you want cvs2cl , you'll able generate delta between 2 tags.

objective c - Cocos2d rotation on touches moved problem -

i have spear sprite. rotation decided touchesmoved method. whenever user slides finger points towards touch. method: - (void)cctouchesmoved:(nsset *)touches withevent:(uievent *)event { uitouch* touch = [touches anyobject]; cgpoint location = [touch locationinview: [touch view]]; float angleradians = atanf((float)location.y / (float)location.x); float angledegrees = cc_radians_to_degrees(angleradians); spear.rotation = -1 * angledegrees; } this kinda works, 0 45 degrees. , goes opposite. moving finger bottom top, rotates clockwise (it should follow direction of fnger , rotate counter clockwise). 45 90, works fine (moves counter clickwise) if start touch in upper diagonal of screen. what doing wrong? thanks #define ptm_ratio 32 - (void)cctouchesmoved:(nsset *)touches withevent:(uievent *)event{ for( uitouch *touch in touches ) { cgpoint location = [touch locationinview: [touch view]]; location = [[ccdirector shareddirec...

Are most of today’s web applications ( and web service applicatins ) being written using ORM? -

i know question bit stupid, still: i know there plenty of threads on when should/shouldn’t use orm. @ level of “expertise” i’m far qualified able tell whether or not app better off or without orm. , don’t want wait till i’m proficient enough figure out whether should learn orm or not. so tell me whether or not of today’s web service apps ( , of web apps in general ) being written using orm? thank you ps - i'm learning wcf , asp.net web forms i guess lot of webapps (yes, of them) use orm persistence layer these days, provided use relational database. goes java (hibernate, jpa), .net, python, groovy/grails , rails (activerecord default). there more , more orm solutions appearing non-relational data stores. it depends on language , application framework using, if any.

How do I make module methods available to a constant Proc variable? (Ruby) -

this in application helper: def call_me "blah" end p = proc.new { call_me } def test_me p.call end if in view: <%= test_me %> i error saying call_me undefined method. how proc able call call_me? require doesn't it. prefixing applicationhelper::call_me doesn't either. :( this works, don't since test_me called lots of times , in reality there many many more procs: def test_me p = proc.new { call_me } p.call end it should work in ruby 1.9.2, in earlier versions can pass helper argument proc: p = proc.new { |helper| helper.call_me } def test_me p.call self end since call_me instance method on helper, need invoke instance.

python - Perceptual hash function for text -

does knows simple perceptual hash algorithm text ? took in phash function ph_texthash want more simple algorithm. preferably in python. thank ! a blog post perceptual hash functions (in imaging context): http://www.hackerfactor.com/blog/index.php?/archives/432-looks-like-it.html and related python code (dealing images, not text, may adaptable): http://sprunge.us/wcvj?py (53 loc) as understand short presentation perceptual hashing of textual content , there numerous approaches (in different dimensions such level of text, linguistic or statistical approach, model chosen represent text, ...), , right 1 depend on domain , problems try solve. also might locality-sensitive hashing , is method of performing probabilistic dimension reduction of high-dimensional data. basic idea hash input items similar items mapped same buckets high probability (the number of buckets being smaller universe of possible input items)

ARGB not working properly in Android app -

i trying apply transparent background row when pressed in listview. create file list_selector.xml this: <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@drawable/argb80804040" /> </selector> and in news_item.xml, define ground follow: <?xml version="1.0" encoding="utf-8"?> <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/list_selector"> <imageview android:id = "@+id/img" android:layout_width="95dip" android:layout_height="75dip" android:layout_alignparentleft = "true" android:paddingtop="10dip" android:layout_marginleft="10dip" android:paddingbottom="10dip" a...

mysql - PHP IF ELSE statement -

i have following statement in page , doesnt seem processing, can see obvious errors im missing? else{ if($usersclass->register($_post['produgg_username'], md5($_post['produgg_password']), $_post['produgg_email'], $randomkey)) { print "success"; $toemail = $_post['produgg_email']; $touser = $_post['produgg_username']; // send activation email $to = $toemail; $subject = "activation"; $headers = "from: support@.co.uk"; $body = "howdy $touser!"; mail($to, $subject, $body, $headers); if(isset($_post['r']) { $refcode = mysql_real_escape_string($_post['r']); mysql_query(" update produgg_users set credits=credits+200000 produgg_users.id = ".$refcode or die(mysql_error()); }; }else{ print "error!...

regex - Regular Expression for irregularly occurring repeating string -

i searched have not found answer question - maybe obvious no 1 else had ask... i using ultraedit 16.00 run regular expressions in perl mode ... situation: i have delimited string can contain variable number of repeating segments must adhere specific format. these segments occur randomly throughout delimited string. example: clp*data*data*data~ref*data*data~n1*data*data*data~**cas*oa*29*99.99**~amt*i*99.99~svc*data*data*data*data~**cas*pr*99.99**~**cas*co**99.99**~dtm*150*date~amt*b6*99.99~svc*data*data*data*data~cas*pr*n16*99.99~**cas*co* *99.99**...line continues here. correct format - cas*oa*29*99.99~ incorrect format 1 - cas*oa* *99.99~ incorrect format 2 - cas*oa**99.99~ goal: identify strings of cas segments adhere format. things i've tried: (btw: know regular expressions not optimized, please give me break) cas segment missing value or containing 1 or more spaces cas\*(oa|pr|cr|co)\*\*[-]?[\d]+\.?[\d]{0,2} ~ matches first instance if fi...

scala - Findig the 2nd last item in the list, please explain this solution -

// pattern matching makes easy. def penultimaterecursive[a](ls: list[a]): = ls match { case h :: _ :: nil => h case _ :: tail => penultimaterecursive(tail) case _ => throw new nosuchelementexception } can comment doing line line? is [a] generic in c# ? h doesn't seem defined? i think major part of algo recursive call: case _ :: tail => penultimaterecursive(tail) there doesnt' seem check 2 items in list, , taking 1st item 2nd last, confused! the keys understanding pattern match realize x :: y only match list single item x followed rest of list y (which nil , or many elements), , _ means "there needs here, won't bother naming it". (and matches occur in order, , lists end nil .) you're correct [a] generic type. so, first line: case h :: _ :: nil => h says, if our list looks (conceptually) node(h) -> node(whatever) -> nil , return h . two-element list first item selec...

How to make C# COM DLL equivalent to ATL COM C++ -

hi trying develop com using c# , visual studio 2005 first did interface "csharpserver.cs" <code> using system; using system.runtime.interopservices; namespace csharpserver { [comvisible(true)] [guid("dbe0e8c4-1c61-41f3-b6a4-4e2f353d3d05")] public interface imanagedinterface { int printhi(); } [comvisible(true)] [guid("c6659361-1625-4746-931c-36014b146679")] public class interfaceimplementation : imanagedinterface { public int printhi() { console.writeline("hello!"); return 33; } } } </code> i compiled. output is: csharp_server.dll. after, did: regasm csharp_server.dll /tlb /codebase output is: ... regasm : warning ra0000 : registering unsigned assembly /codebase can ca use assembly interfere other applications may installed on same computer. /...

c++ - Casting floating point (double) to string -

i'm running i've never seen before , understand going on. i'm trying round double 2 decimal places , cast value string. upon completion of cast things go crazy on me. here code: void formatpercent(std::string& percent, const std::string& value, config& config) { double number = boost::lexical_cast<double>(value); if (config.total == 0) { std::ostringstream err; err << "cannot calculate percent 0 total."; throw std::runtime_error(err.str()); } number = (number/config.total)*100; // format string return 2 decimals of precision number = floor(number*100 + .5)/100; percent = boost::lexical_cast<std::string>(number); return; } i wasn't getting quite expected did investigation. did following: std::cout << std::setprecision(10) << "number = " << number << std::endl; std::cout << "percent = " << percent <<...

c++ - Assembly Performance Tuning -

i writing compiler (more fun else), want try make efficient possible. example told on intel architecture use of register other eax performing math incurs cost (presumably because swaps eax actual piece of math). here @ least 1 source states possibility (http://www.swansontec.com/sregisters.html). i verify , measure these differences in performance characteristics. thus, have written program in c++: #include "stdafx.h" #include <intrin.h> #include <iostream> using namespace std; int _tmain(int argc, _tchar* argv[]) { __int64 startval; __int64 stopval; unsigned int value; // keep value keep being optomized out startval = __rdtsc(); // cpu tick counter using assembly rdtsc opcode // simple math: = (a << 3) + 0x0054e9 _asm { mov ebx, 0x1e532 // seed shl ebx, 3 add ebx, 0x0054e9 mov value, ebx } stopval = __rdtsc(); __int64 val = (stopval - startval); cout << "resu...

javascript - Length of Array Differs In Internet Explorer With Trailing Comma -

i'm working data using javascript in form of array. array may contain empty entry @ end, such [1,2,] . in google chrome , firefox, length of example 2; however, in ie, length 3. in short: internet explorer giving different length array in javascript google chrome , firefox. there way standardize behavior across browsers? code: var = [1,]; alert(a.length); edit: a lot of answers saying not have trailing comma, however, data given me in way. never have trailing commas in ie. period. that goes arrays too javascript browser quirks - array.length to handle edit works (tested in in ie8): if (a[a.length-1]==null) a.length--; // or a.pop() for safer test, please @ other suggestion on page: length of array differs in internet explorer trailing comma - demo here by way, never heard words elision or elided before - learn new here every day

PHP: How to find position of (user-defined) occurrence of a string using stripos -

there strpos() find first occurrence, , strrpos() find last occurrence. this tutorial explained it's possible occurrence using loop, might not fast when haystack big. , code looking ugly now. is there way find 2nd, 3rd, 4th, etc occurrence without looping on haystack? mean, finding required occurrence directly without looping? possible? you can use regular expression, not faster looping strpos. if (preg_match_all("/(match string)/g",$string,$matches)) { echo $matches[0] ; // whole string echo $matches[1] ; // first match echo $matches[2] ; // second match echo $matches[3] ; // , on } if wan replace occurrences, use str_replace() . way don't have worry offsets.

Problem with decoding UTF-8 JSON in perl -

utf-8 characters destroyed when processed json library (maybe similar problem decoding unicode json in perl , setting binmode creates problem). i have reduced problem down following example: (hlovdal) localhost:/tmp/my_test>cat my_test.pl #!/usr/bin/perl -w use strict; use warnings; use json; use file::slurp; use getopt::long; use encode; $set_binmode = 0; getoptions("set-binmode" => \$set_binmode); if ($set_binmode) { binmode(stdin, ":encoding(utf-8)"); binmode(stdout, ":encoding(utf-8)"); binmode(stderr, ":encoding(utf-8)"); } sub check { $text = shift; return "is_utf8(): " . (encode::is_utf8($text) ? "1" : "0") . ", is_utf8(1): " . (encode::is_utf8($text, 1) ? "1" : "0"). ". "; } $my_test = "hei på deg"; $json_text = read_file('my_test.json'); $hash_ref = json->new->utf8->decode($json_text)...

Use command line args in a Java Swing program -

how can process command line arguments in java swing program? edit: want have user give file path arg. set text of jtextpane contents of file. the way through main method when run java class file. you following in command line once compiled; java nameofclassfile b c d for example print them out array of command line arguments: public static void main(string[] args) { for(string arg : args) system.out.println(arg); } i don't know of anyway pass command line arguments running java swing program. not sure if can. to display files contents on jtextpane can use args[0] a command line argument file path using: jtextpane pane = new jtextpane(); jframe frame = new jframe("example"); frame.add(pane); frame.setvisible(true); file file = new file(args[0]); pane.setpage(file.tourl().tostring()); frame.pack(); if want more 1 files contents use java nameofclassfile file1 file2 file3 can use args[0] args[1] args[2] file path , modify above cod...

vb.net - Raw .net framework libraries? -

i need access raw .net framework libraries ( such system ) , etc. of libraries required .net programs run. there specific place on harddrive can find them all? .net 2.0 (32-bit) c:\windows\microsoft.net\framework\v2.0.50727 .net 2.0 (64-bit) c:\windows\microsoft.net\framework64\v2.0.50727 .net 4.0 (32-bit) c:\windows\microsoft.net\framework\v4.0.30319 .net 4.0 (64-bit) c:\windows\microsoft.net\framework64\v4.0.30319 the .net 3.0 assemblies in various places under c:\windows\microsoft.net, around them. i wonder why want directly access these assemblies. real use can think of using runtime compiler load specific assemblies manually, can specify assembly filename because in gac.

Finding the highest n values of each group in MySQL -

i have data formatted this: lane series 1 680 1 685 1 688 2 666 2 425 2 775 ... and i'd grab highest n series per lane (let's 2 sake of example, many more that) so output should be: lane series 1 688 1 685 2 775 2 666 getting highest series per lane easy, can't seem find way highest 2 results. i use max aggregate function group max, there's no "top n" function in sql server , using order by... limit returns highest n results overall, not per lane. since use java application coded myself query database , choose n is, loop , use limit , loop through every lane, making different query each time, want learn how using mysql. this solution fastest mysql , work large tables, uses "funky" mysql features, wouldn't of use other database flavours. (edited sort before applying logic) set @count:=-1, @la...

How can I run a PHP explode() function when parsing a variable in Stacey? -

how can run php explode() function on variable called "artist" in stacey ? i've been digging around in /app/asset-types/page.inc.php around line 49 "#magic variable assignment", don't have enough php experience understand what's going on. thanks!

c# - how to move a button in WPF -

xaml code below <window x:class="denemewpfapplication1.mainwindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" title="mainwindow" height="350" width="525"> <grid> <dockpanel width="auto" verticalalignment="stretch" height="auto" horizontalalignment="stretch" grid.columnspan="1" grid.column="0" grid.row="0" margin="0,0,0,0" grid.rowspan="1"> <stackpanel> <stackpanel.background> <lineargradientbrush> <gradientstop color="white" offset="0" /> ...

cakephp - Return ACL group of user -

i have created user authentication system using cakephp's aco/aro tables using this tutorial . i creating interface change groups of users , display current group of user. i searched api , not find built-in method query group user belongs to. best way this? you may or may not decide in users table have security_group_id field points security_groups table. within security_groups table store aliases/names of security groups (i.e. administrators, site users, managers, etc.). in aro table these security groups root/parent nodes subsequent user accounts create on system. querying users tables security_group_id field, can determine group user in. another approach do: $aro =& classregistry::init('aro'); $theuser = array('user' => array('id' => <user_id>)); $aropath = $aro->node($theuser); $aropath array including user node in $aro table , parent nodes.

android - Clearing all cached items created by a WebView? -

i've got webview in app. when user logs out of app, i'd delete cached resources webview may have created. looking @ emulator, see following files: /data /data /com.example.myapp /cache /webviewcache bunch of files here.. /databases webview.db webviewcache.db is there system call can use clear elements in /cache , /databases, or should manually? i'm worried doing manually because don't know new files webview may leave behind in future versions of android won't sure i'm clearing user. try this mwebview.clearcache(true); mcontext.deletedatabase("webview.db"); mcontext.deletedatabase("webviewcache.db");

windows phone 7 - How to write a simple WP7 unit test using xUnitContrib? -

i'm working xunitcontrib codeplex page , toward bottom lists these steps for windows phone 7 follow along this blog post create windows phone application add references to: microsoft.silverlight.testing.dll (silverlight 3 version - included in release) xunit-silverlight-wp7 xunit.extensions-silverlight-wp7 xunitcontrib.runner.silverlight.toolkit-wp7 visual studio may display warnings including silverlight 3 assemblies. ignore it, these right files add [fact] based tests , run app (note- blog post mentioned isn't using fact based tests i'm more confused ...) but after add above mentioned dll's , start below ... resharper , can't seem hookup testing harness enough compile. has wired unit test xunit wp7? public class myfirstwp7test { [fact] public void can_run_test_for_wp7() { var x = "hello world"; assert.equal("hello world", x); } } you can't use res...

upload image displays an error under drupal 6 -

a site have run ok time. recently, when upload image, raising error: an unrecoverable error occurred. form missing server cache. try reloading page , submitting again. the first time uploaded image ok. when create second article , upload image, shows above error. , upload button disappeared. does konw how correct , what's reason of error emergence ? apparently problem not drupal. setting on server. if use hosting services. please contact support, may advise. recommend looking faq page module loads image coordinates. also, test problem, try move website local kompyuter , test not appear whether problem. luck. , update modules before actual sosoyaniya. poeksprimentiruyte module load module dev.

Null property selection using named scopes/lambda in Ruby on Rails -

i have object jobbreakdown has_one :invoice . if jobbreakdown has invoice (i.e. invoice_id not nil) considered invoiced . if not, consider uninvoiced . users want able select drop down box invoiced or uninvoiced , have correct records show up. how write named scope test , return right records? along lines of named_scope :is_invoiced, lambda {|is_invoiced| {:conditions => :invoice.nil? == is_invoiced}} nb: using ruby 1.8.7, rails 2.3.5 i'm not sure, right syntax rails 2.x @ least it'll give idea of how that. named_scope :is_invoiced, lambda { |is_invoiced| :condition => is_invoiced ? "invoice not null" : "invoice null" } or maybe this: named_scope :is_invoiced, lambda { |is_invoiced| :condition => "invoice #{is_invoiced ? 'not' : ''} null" }

iphone - Error resolving a NSNetService -

i'm creating board game played via wi-fi, in iphone. when device invites device b play(try resolve nsnetservice published b), device b can accept or decline. if b declines, notified , fine. if try invite b again later, following error in netservice:didnotresolve: delegate method. nsnetserviceserrorcode = -72003 nsnetserviceserrordomain = 10 the error -72003 means nsnetservicesactivityinprogress ...how can proceed let 1 player "invite" other player more once ? i'm using asynchsocket libray, thanks! ok, figure out. what i'm doing resolve nsnetservice quick possible in browserdidfind: delegate method. when need connect call [socket connecttoaddress:], passing nsnetservice address, no more errors! thanks!

javascript - URL Encode a string in jQuery for an AJAX request -

i'm implementing google's instant search in application. i'd fire off http requests user types in text input. problem i'm having when user gets space in between first , last names, space not encoded + , breaking search. how can either replace space + , or safely url encode string? $("#search").keypress(function(){ var query = "{% url accounts.views.instasearch %}?q=" + $('#tags').val(); var options = {}; $("#results").html(ajax_load).load(query); }); try encodeuricomponent . encodes uniform resource identifier (uri) component replacing each instance of characters one, two, three, or 4 escape sequences representing utf-8 encoding of character (will 4 escape sequences characters composed of 2 "surrogate" characters). example: var encoded = encodeuricomponent(str);

PHP File Operation -

i trying create text file php in fopen("test.txt","a") . have tried fopen("test.txt","w+") . the text file created want check string in test.text, exist or in test.txt not create duplicate entry. can me out? use code: $content = file_get_contents('test.txt'); if (str_pos('your keyword', $content) !== false){ // keyword exists in file }

objective c - UIAccerlerometer in iphone -

i working in iphone application included accelerometer. haven't worked accelerometer till , not familiar librarys used . had gone through uiaccelerometer library in iphone bit more . if can refer tutorials on topic appreciated . you haven't mentioned need in uiaccelerometer vist this link . hope you.

localization - Dynamically change android soft keyboard language setting? -

i have edit boxes in app, of them input english text, of them input spanish. i'm using standard android soft keyboard, device locale set english, when type spanish in 1 of "spanish" edit boxes, english corrective text/predictive text makes difficult. the workaround i've found, go device settings , change language over, quite annoying. is there anyway have kind of button, when clicked dynamically change soft keyboards language setting? exposed via intents? regards try slide finger across spacebar on keyboard change languages.

html - How to make scrollable DIV with scrollbar outside div like on facebook? -

i has scrollable div scrollbar should on right side of browser default (but not on right side of div). i've seen on facebook (ceter div - contentarea scrolled right side browser scrollbar). the way facebook having content doesn't scroll have position of fixed . way native browser scrollbar appear scroll center area only, while it's rest of page fixed in position. a simple example of this: http://jsfiddle.net/tcavn/ now imagine above, non-scrollable items setup #header . edit here more complex example, 3 columns: http://jsfiddle.net/tcavn/1/

One payment gateway(paypal) but business accounts across different account providers -

i working on website involves users paying each other. payment gateway going paypal., require every user have business account paypal? (or) possible let them have business account business account provider?. would appreciate pointers. thanks! define mean 'business account'. if mean merchant account @ acquiring bank: no, that's not required. if mean paypal business account; no, that's not require either, recipients can have premier account well. technically, you'll want adaptive chained payments -- allows chain payment along multiple recipients (up 9, if recall correctly). have @ introducing adaptive payments or dev guides

java - Application in Sun app server hangs after processing a few messages -

appliation server sun appserver 8.1 jvm - java 1.5.0.11 we have jms receiver processing messages deployed in sun application server 9.x after processing 50 odd messages appserver hangs. upon restart 50 odd messages gets processed , hangs again. no exceptions / error thrown (we modified code catch throwable , log in severe mode). hence bhavior cannot attributed code or messages re-processed. would appreciate f/b suggestions not load entire stack, there way attach file? attached jstack o/p regds, chiths thread t@139: (state = blocked) - com.sun.httpservice.spi.httpservice.stop() @bci=0, line=286 (interpreted frame) - com.sun.enterprise.web.httpservicewebcontainer.stophttpservice() @bci=16, line=1080 (interpreted frame) - com.sun.enterprise.web.httpservicewebcontainer.stopinstance() @bci=24, line=913 (interpreted frame) - com.sun.enterprise.web.httpservicewebcontainerlifecycle.onshutdown() @bci=9, line=62 (interpreted frame) - com.sun.enterprise.server.applicationserv...

linux - How to handle an Error correctly using Javascript? -

when want send , error using javascript do: throw new error() it works, if pass number, example: throw new error(500) the result is: error: 500 where 'error: ' string. i have function handle errors, function must know code of error, how retrieve it? have parse string? :-( thank you. if throw error way, text between parenthesis becomes error message. can throw using a custom error object . a useful link: the art of throwing javascript errors

how to get low battery alert in iphone? -

i want display low battery alert programatically in iphone, when battery charge level low. any 1 have idea this, please me. can find battery charge level using code uidevice *mydevice = [uidevice currentdevice]; [mydevice setbatterymonitoringenabled:yes]; mydevice.batterymonitoringenabled=yes; float batterylevel = [mydevice batterylevel]; use battery level property uidevice. if battery level less 5% show alert example. pool periodically battery level in app delegate example. uidevice *mydevice = [uidevice currentdevice]; [mydevice setbatterymonitoringenabled:yes]; float batterylevel = [mydevice batterylevel]; batterylevel - battery charge level device. batterylevel - battery level ranges 0.0 (fully discharged) 1.0 (100% charged). before accessing property, ensure battery monitoring enabled. if battery monitoring not enabled, battery state uidevicebatterystateunknown , value of property –1.0.

php - How to select particular rows on a MySQL table? -

i have table called 'topics' in topics saved. want select latest 5 rows table, show them on 1 page, select other 5 latest ones , show them on other page. i know how echo topic names in while loop, problem here making mysql select 5 rows, other 5 page, not same ones again. how achieve this? select * tablename order id desc limit 0, 5 on page: limit 5, 5

How to make XML document from string in java or Android? -

i trying create dynamically generated xml file java. code trying use: try{ bufferedreader bf = new bufferedreader(new inputstreamreader(system.in)); system.out.println("how many elements: "); string str = bf.readline(); int no = integer.parseint(str); system.out.println("enetr root: "); string root = bf.readline(); documentbuilderfactory dbf = documentbuilderfactory.newinstance(); documentbuilder db = dbf.newdocumentbuilder(); document d1 = db.newdocument(); element e1 = d1.createelement(root); d1.appendchild(e1); (int = 0; < no; i++) { system.out.println("enter element: "); string element = bf.readline(); system.out.println("enter data: "); string data = bf.readline(); element em = d1.createelement(element); ...

Must static method/classes/variables be accessed one at a time in .net? -

i write lot of code in static methods/classes/variables can accessed across site, globalization ideas , "spare" creation , destruction of classes when not data preservation classes(dbcontext example). the question is, must these classes/methods accessed once @ time? cause kind of bottle-neck? thanks. the question classes/methods can accessed once @ time? no, can accessed multiple times , in parallel. should careful static classes in multi-threaded applications need ensure thread safe. does cause kind of bottle neck? this depend on how written , do.

datetime - Filtering ASPxGridView by a ASPxDateEdit using Control -

i want filter gridview choosing date , time in dateedit. put button has databind() controls. query of datasource of gridview has clause. has control connecting gridview , dateedit. when test query, works fine. enabled buttonclick event , wrote following code that: protected void aspxbutton2_click(object sender, eventargs e) { dateedit.databind(); sqldatasource.databind(); aspxgridview.databind(); } as can see bound stuff need. no items displayed when choose date , time , click button. did miss something? appreciate if help. i'm devexpress asp.net technical evangelist, mehul. there many ways can approach recommend using aspxgridlookup control gives grid within dropdown: http://demos.devexpress.com/aspxgridviewdemos/aspxgridlookup/filterservermode.aspx you can use built-in features: http://www.devexpress.com/support/center/p/q267406.aspx or try sample: http://www.devexpress.com/support/center/e/e2040.aspx some of these may well: http://search.devex...

php - Zend Framework: How to attach other than default layout -

i have created module 'admin' . created layout admin module. how can permanently attach layout 'admin' module. can 1 suggest me , how can write code purpose. whether in bootstrap file ? if module can add layout.phtml file module's layout/scripts/ folder. if have different name layout.phtml admin.phtml simple add following in controller $this->_helper->layout->setlayout('admin'); it should , check first module's layout folder , default folder.

cryptography - DUKPT - how does the receiver verify the transaction counter? -

ansi x9.24 says (page 41) receiver should verify originator's transaction counter in smid has increased. other sources hsm's not store state apart base derivation keys. the base derivation keys can looked key set identifier (contained in smid). receiver (hsm) able decrypt without keeping state of originator. when verifying transaction counter can not imagine other way keeping track of transaction counter per key serial number (ksn) of originator (a table or map) - there state kept, there should not kept state. does know how implemented or explain basic idea how can done without keeping track of state? edit: question posted to: https://security.stackexchange.com/questions/5025/dukpt-how-does-the-receiver-verify-the-transaction-counter

java - arraylist sorting -

i have 2 arraylist 1 have employee entity list other have same entity list. one arraylist have employees , other 1 have selected employees. now want arrange employee in list in first arraylist on selected employees first arrive in second arraylist. for ex:: list1 [{1,test1}{2,test2},{3,test3},{4,test4}] list2[{2,test2}{4,test4}] what want is list1[{2,test2}{4,test4}{1,test1}{3,test3}] how can same using single method or minimal line code .. from have said seems need take members of list1 not in list2 , append them list2 in order appear in list1. something like: for ( employee e : list1 ) { if ( !list2.contains(e) ) { list2.append(e); } }

java - Convert array list items to integer -

i have arraylist, arr. arraylist stores numbers strings. want convert arraylist integer type. how can that??? arraylist arr = new arraylist(); string a="mode set - in service", b="mode set - out of service"; if(line.contains(a) || line.contains(b)) { stringtokenizer st = new stringtokenizer(line, ":mode set - out of service in service"); while(st.hasmoretokens()) { arr.add(st.nexttoken()); } } since you're using untyped list arr , you'll need cast string before performing parseint: list<integer> arrayofints = new arraylist<integer>(); (object str : arr) { arrayofints.add(integer.parseint((string)str)); } i recommend define arr follows: list<string> arr = new arraylist<string>(); that makes cast in conversion unnecessary.

Delphi 2007 VCL Project Name Different from Compiled Exe Name? -

Image
is there way have project named "someproject" creates exe named "somethingdifferent.exe"? in .net simple have project name independent of generated assembly name, don't see how equivalent in delphi 2007. you can use msbuild post-build event for example can create copy of exe name want using command del "$(outputdir)somethingdifferent.exe" copy "$(outputdir)$(outputfilename)" "$(outputdir)somethingdifferent.exe"

Displaying different text on a spinner item than the selected text, android -

i have spinner item, 3 elements, i) - 1 ii) b - 2 iii) c - three. when user presses spinner, drop down box displays these elements, when 1 of them selected text should displayed character, (like index). i can't seem find useful except using "android:promt" display legend indicating each character/code stands looks unprofessional , confusing user. is there anyway can using android? if can me, in advance :)

How can I create a separate plugin folder for my Rails 2.3 app? -

in rails app have 2 classes of plugins , separate them into vendor/plugins -> default core plugins vendor/extensions -> extensions apps run inside platform app the problem plugins inside extensions folder aren't loaded platform app. thanks. this should help: config.plugin_paths << "#{rails_root}/vendor/extensions"

winforms - changing the text box border style in windows form - c# -

i have text box , in square form want convert square oval shape using win forms application can 1 tell idea you can use setwindowrgn api function change shape of window. function - can see here - gets 3 arguments: window handle : can textbox handle , can handle property. a window rgn : can create calling createroundrectrgn (or rgn creator functions can find them here ) a boolean determine redraw : better true. you can subclass textbox , create oval shaped textbox using functions in onhandlecreated method. class can this: class ovaltextbox : textbox { [dllimport("user32.dll")] static extern int setwindowrgn(intptr hwnd, intptr hrgn, bool bredraw); [dllimport("gdi32.dll")] static extern intptr createroundrectrgn(int x1, int y1, int x2, int y2, int cx, int cy); public ovaltextbox() { base.borderstyle = system.windows.forms.borderstyle.none; } protected override void onhandlecreated(eventargs e)...

multithreading - Multithreaded code in Java with ExecutorService fails to return, why? -

i have similar multithreaded code elsewhere in codebase works fine, can't see quite what's going wrong here. this simple multi-threaded process generate result xml search query. output of running method is: returning threads the line system.out.println("finished multithreading loop");" never reached. modifying number of threads doesn't help. private void fillallresults() { int threads = 2; final futuretask[] tasks = new futuretask[threads]; final executorservice executor = executors.newcachedthreadpool(); (int = 0; < allresults.size(); i++) { tasks[i] = new futuretask<integer>(new callable<integer>() { public integer call() throws exception { int index; while ((index = getresultsindex()) < allresults.size()) { system.out.println("processing result " + index); result r...