Posts

Showing posts from January, 2010

python - How to get process status using pid? -

if known process's pid, how can tell if process zombie using python ? you use status feature psutils : import psutil p = psutil.process(the_pid_you_want) if p.status == psutil.status_zombie: ....

javascript - How to create google plus circle with mouseover effect? -

those of have seen google plus may know im taking about... essentially problem this. have circle radius example of number of pixels text in center. on mouseover, outline of circle expands whatever plus 5. when mouse out, circle gradually shrinks original size. if text in middle of circle clicked alert box of sort pops up. what way , how? involve div tags? use css3 border-radius create circle , js animations...or try them css3 well. http://jsfiddle.net/dosbeats/ce6yb/ this version uses js.

java - Application hangs for few minutes even after all the threads are done -

i converted working producer/consumer example thread/runnable executor/callable/blockingqueues , using poison pill termination pattern. if run program below, hang few minutes though every thread has completed. jstack shows numerous threads blocked on queue not seemingly related application. "pool-1-thread-10" prio=5 tid=10b08d000 nid=0x10d91c000 waiting on condition [10d91b000] java.lang.thread.state: timed_waiting (parking) @ sun.misc.unsafe.park(native method) - parking wait <7f3113510> (a java.util.concurrent.synchronousqueue$transferstack) @ java.util.concurrent.locks.locksupport.parknanos(locksupport.java:198) @ java.util.concurrent.synchronousqueue$transferstack.awaitfulfill(synchronousqueue.java:424) @ java.util.concurrent.synchronousqueue$transferstack.transfer(synchronousqueue.java:323) @ java.util.concurrent.synchronousqueue.poll(synchronousqueue.java:874) @ java.util.concurrent.threadpoolexecutor.gettask(threadpoolexec

sql - Doing a calculation between two rows with EXTRA CRITERIA? -

name exactdate presents location bob1 2011 1 home bob2 2008 2 school bob2 2012 3 school mary2 1986 4 school mary1 2001 5 home mary1 2012 6 home kate1 2011 7 home kate1 2012 8 home kate2 2011 9 school celia2 2011 10 school celia2 1986 11 school celia1 1972 12 home celia1 2012 14 home celia2 2012 13 school this problem done in sql in ms access 2003 query. so goal subtract amount of presents kate got celia on same year ( since there few different present values same year choose have priority of home > school....for example celia , kate both receive presents in 2012 celia gets both home presents , school presents in 2012 in case choose ho

winapi - timed MessageBox in console application -

i use messagebox function in win32 console application. application not not use mfc, not event loop. need make wrapper, messageboxtimed(), exits (and dialog box disappears) after n seconds, if user did not press button. is there more or less simple way ? see this article in msdn example of 1 implementation. use in of our projects , works fine.

ios - how to know which cells (row & section) of a UITableView are currently being displayed? -

is there way know rows/sections being displayed inside uitableview ? know can use function : tableview:(uitableview *) tableview willdisplaycell:(uitableviewcell *) cell forrowatindexpath:(nsindexpath *)indexpath but, doesnt me. given moment, want know row/sections being displayed , processing based on that. can kindly me ? thanks. at given moment, can retrieve visible cells table view, or index paths : -(nsarray *)visiblecells; -(nsarray *)indexpathsforvisiblerows; check uitableview class reference

belongs to - inherited_resources and multiple belongs_to without nesting -

let's down brass tacks. rails: 2.3.11 i have controller using inherited_resources reference 2 separate , non-nested resources. my controller shown: class tools::deploymentlinescontroller < toolscontroller inherit_resources belongs_to :deployment belongs_to :ticket end#tools::deploymentlinescontroller however, inherit_resources assuming belongs_to :ticket nested resource of deployment . is there way of using 2 belongs_to in controller without nesting? or need write out own business logic account missing inherited_resources association? you should able use: belongs_to :deployment, :ticket

php - URL lost during POST -

what's wierd on 1 page can echo variable built by: $protocol = strpos(strtolower($_server['server_protocol']),'https') === false ? 'http' : 'https'; $host = $_server['http_host']; $script = $_server['script_name']; $params = $_server['query_string']; $currenturl = $protocol . '://' . $host . $script . '?' . $params; then post page (i know post works because send other values): <?php echo'<input type="hidden" name="refferer" value="'.$currenturl.'"/>'?> but when try use on other page empty: $return = $_post[refferer]; header("location: $return"); anyone know what's happening it? try: $return = $_post['refferer']; header("location: $return");

c# - How do I add controls dynamically to a dynamically created panel? -

i have repeater creates n-number of panels. trying dynamically add different controls each of panels. may going wrong way. my code more or less: .aspx: <asp:repeater id="repeater1" runat="server"> <itemtemplate> <% response.write("<asp:panel runat=\"server\" id=\"uxpanel_"); %> <%# databinder.eval(container.dataitem, "tableid")%><% response.write("\"></asp:panel>"); %> </itemtemplate> </asp:repeater> .cs: public partial class class1: system.web.ui.page { dataset ds= null; protected void page_load(object sender, eventargs e) { getrecords(1,1); } protected void getrecords() { ds= dal.loadrecords(); this.repeater1.datasource = ds.tables[0]; this.repeater1.databind(); literal lit = new literal(); lit.text = "some text"; this.findcontrol("uxpanel_1").controls.add(lit);

css - Issue with floating divs - how can I have the widgets alongside the posts, not below? -

i struggling figure out how align widgets right of main column on page: http://carolineelisa.com/wordpress/ it seems top 3 widgets forcing content area full width, right hand side widgets drop below left column. any tips achieving css? i'd rather not have mess templates of functions.php file move top widgets own div. thanks! you have place 2 right side divs before post divs. <div id="content" class="hfeed content"> <div id="primary" class="sidebar aside"> this instead <div id="primary" class="sidebar aside"> <div id="content" class="hfeed content">

HTML validation errors using Facebook RDFa doctype & meta property -

i followed stack, html validation error property attribute , , used rdfa doctype work facebook open graph. my question is, how can html validator work line of code (required): <map id="map" name="map"> currently validator fails because " there no attribute 'name' ". here's page , validator error . the "name" attribute in xhtml has been deprecated in favor of "id" attribute map tag.

iphone - AudioQueue output channels -

i have problem audio stream (this lpcm stream 6 channels inside). when playing stream on iphone via audioqueue hear first 2 channels. here audioqueue initialization code: - (id)initwithsamplerate:(int)asamplerate numchannels:(int)anumchannels { self = [super init]; audiostreambasicdescription thedescription; thedescription.mformatid = kaudioformatlinearpcm; thedescription.msamplerate = asamplerate; thedescription.mchannelsperframe = anumchannels; thedescription.mbytesperpacket = 2 * anumchannels; thedescription.mframesperpacket = 1; thedescription.mbytesperframe = 2 * anumchannels; thedescription.mbitsperchannel = 16; thedescription.mformatflags = kaudioformatflagsnativeendian | kaudioformatflagissignedinteger; audioqueuenewoutput(&thedescription, audioqueue_callback, self, cfrunloopgetcurrent(), kcfrunloopcommonmodes, 0, &audioqueue); audioqueuestart(audioqueue, null); return self; } do know how sol

apache - PHP programming seg fault -

i've been programming site using: zend framework 1.11.5 (complete mvc) php 5.3.6 apache 2.2.19 centos 5.6 i686 virtuozzo on vps cpanel whm 11.30.1 (build 4) mysql 5.1.56-log mysqli api 5.1.56 suddenly doing few "show create table" query mysql, got this. [wed jul 20 17:35:23 2011 ] [notice] eaccelerator(5827): php crashed on opline 138 of fetch_fields() @ /usr/lib/php/zend/db/statement/mysqli.php:235 i've tried disabling eaccelerator without success [wed jul 20 17:45:34 2011] [warn] [client 190.78.208.30] (104)connection reset peer: mod_fcgid: error reading data fastcgi server [wed jul 20 17:45:34 2011] [error] [client 190.78.208.30] premature end of script headers: index.php [wed jul 20 17:45:34 2011] [error] mod_fcgid: process /usr/local/cpanel/cgi-sys/php5(11562) exit(communication error), unexpected signal 11 [wed jul 20 17:45:34 2011] [warn] [client 190.78.208.30] (104)connection reset peer: mod_fcgid: error reading data fastcgi server [wed j

Java API modification -

i have quick question - possible modify source code of java api e.g. junit, jabx ? know seems stupid question, has been bugging me while. if can hands on source, sure can modify it. might not best option. might better create subclasses (if possible) , overwrite implementations, , use subclasses. or use composition proxy library classes. depends on need do/fix. keep in mind if modify source of external library, , upgrade, have modify source again. might have change extensions/proxies if go route, experience has taught me that's typically less complicated.

ios - Orientation problem while using GKLeaderboardViewController -

unfortunately, don't understand uiviewcontrollers well, nor understand how mesh cocos2d scenes. however, able load standard game center leaderboard view on top of cocos2d (landscape-only) game on iphone. but, game universal app , when try on ipad, game center view loads in portrait orientation, half size should (fills 1 quarter of screen), , not centered. when rotate device, game center view orients landscape gets stretched out , looks wasn't designed ipad in landscape view. does have advice? - (void) showleaderboard { if(![myappdelegate isgamecenterapiavailable]) return; if ([gklocalplayer localplayer].isauthenticated == yes) { cgsize screensize = [[uiscreen mainscreen] bounds].size; tempvc = [[rootviewcontroller alloc] init]; gkleaderboardviewcontroller *leaderboard = [[[gkleaderboardviewcontroller alloc] init] autorelease]; if (leaderboard != null) { leaderboard.leaderboarddelegate = self

c# - Error Unless Declared Static -

if have class,any member in don't declare static have error if reference inside class: an object reference required non-static field, method, or property what doing wrong? you error if accessing instance method static context. example public class dog { public void speak(){ console.writeline( "bark" ); } public static void kickdog(){ speak(); // <- error here } } instead need create instance of class public static void kickdog() { new dog().speak(); } however, mix-up might suggest misunderstanding of c# semantics , i'd recommend picking 1 of intro c# books on amazon better understanding.

php - Displaying array content from function? -

can tell me how display value of next code below? in user.php file have next content: class user { protected $userid; protected $useremail; protected $userpassword; public function __construct() { $this->userid = preg_replace('#[^0-9]#i', '', $_session['user_id']); $this->useremail = preg_replace('#[^a-za-z0-9@_.-]#i', '', $_session['user']); $this->userpassword = preg_replace('#[^a-za-z0-9]#i', '', $_session['user_password']); } public function userinfoquery() { $sql = "select * users id = '$this->userid' , email = '$this->useremail' , password = '$this->userpassword' limit 1"; $res = mysql_query($sql) or die(mysql_error()); $usermatch = mysql_numrows($res); if ($usermatch == 1) { while($row = mysql_fetch_array($res)) {

indexing - Do mysql update queries benefit from an index? -

i have table updates , i'm wondering if update queries benefit having index on column , updated column or index on column? just on column. index on update column slow down query because index has updated along data. index on column speed updates, , selects, slow down insertions. indices cause overhead when delete rows. in general thing though on columns using where on lot, , necessary on columns joins on, or order by

How to get coordinates of field within the visible screen when scroll is used? ( Blackberry, BB, Java ) -

1)the field placed in manager has fixed position in manager. 2)when user scrolls screen field moving along visible screen, (although position within manager remains fixed). how these visible-screen-coordinates of field when user scrolls view , sets focus on field? p.s. might called 'absolute coordinates' thanks! not sure if can you. have looked @ getfocusrect(xyrect xyrect)? when child field gets foucs, retreive extent of manager's focus region. api says that getfocusrect public void getfocusrect(xyrect rect) retrieves current extent of focus. invoke method retrieve extent of current focus region. notice coordinates expressed local manager, , take scrolling account ( that is, coordinates local manager's visible region, not virtual region ). overrides: getfocusrect in class field parameters: rect - rect contain extent of focus. http://www.blackberry.com/developers/docs/5.0.0api/net/rim/device/api/ui/manager.html#getfocusrect(net.rim.devic

java - Is this a good pattern for annotation processing? -

i've got standard spring webapp, , have number of custom annotations use denote requirements , constraints applied given web-service method. instance, might apply @requireslogin annotation method requires valid user session, , @requiresparameters(paramnames = {"name", "email"}) on method requires "name" , "email" set, , on. in support of implemented ad-hoc utility validating method's annotated constraints @ runtime, followed pattern of: map<class<? extends annotation>, annotation> annotations = mergeconstraintsfromclassandmethod(serviceclass, servicemethod); if (annotations.containskey(annotationtype1.class)) { annotationtype1 annotation = (annotationtype1)annotations.get(annotationtype1.class); //do validation appropriate 'annotationtype1' } if (annotations.containskey(annotationtype2.class)) { annotationtype2 annotation = (annotationtype2)annotations.get(annotationtype2.class); //do valida

iphone - Background image for activityIndicatorView -

so, creating activityindicator programmatically. works fine. want add background image indicator , center in middle of view. idea how achive that? here's code: - (void) indicatorviewshow: (bool)show { if (show) { //--- create layout rect cgrect indicatorrect; indicatorrect.origin = self.view.center; indicatorrect.size.width = 50; indicatorrect.size.height = 50; indicatorrect.origin.x -= indicatorrect.size.width / 2; //--- create indicator view indicatorview = [[indicatorview alloc] initwithframe: indicatorrect]; indicatorview.activityindicatorviewstyle = uiactivityindicatorviewstylewhitelarge; [indicatorview startanimating]; [self.view addsubview: indicatorview]; //--- show network activity [uiapplication sharedapplication].networkactivityindicatorvisible = yes; } else { //--- hide network activity [uiapplication sharedapplication].networkact

Is there a function like the magic method __call() for global scope in php? -

if call made undefined method in class, magic method __call can intercept call, handle situation see fit: http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods is there mechanism provided in php whereby can same thing functions in global scope. point best illustrated code: <?php function return_some_array(){ $a = array(); //do stuff array return array(); } // call function so: $give_me_array = return_some_array(); // want array not contain zeroes, nulls etc. // call: $give_me_array_filtered = return_some_array_filtered(); // haven't defined return_some_array_filtered() anywhere. // instead so: function __magic_call($function_name_passed_automatically){ preg_match('/(.*)_filtered$/', $function_name_passed_automatically, $matches); $function_name_that_i_defined_earlier_called_return_some_array = $matches[1]; if($matches){ $result

c# - passing RSS binded data to another page, windows phone 7 -

this may seem easy answer someone, i'm giving shot i've doubled on trying solve this. i'm passing rss information listbox itemtemplate binded data. each listboxitem has image url. want user able click on listboxitem, pass image url new page, , open page displaying image. only problem? cannot work. here have far: page1 xaml: <listbox x:name="listbox" grid.row="1" selectionchanged="listbox_selectionchanged"> <listbox.itemtemplate> <datatemplate> <grid> <grid.rowdefinitions> <rowdefinition height="auto" /> </grid.rowdefinitions> <image grid.row="0" horizontalalignment="left" height="60" width="60" source="{binding url}"/> </grid> &

cassandra - SchemaDisagreementException -

trying set cassandra cluster, tells me have schemadisagreementexception. weird writing works, not of time. assume must somewhere have different schemas, i've cleared data directories several times before, must not in there. else schema declared, other in code? you've inspired faq entry! :) http://wiki.apache.org/cassandra/faq#schema_disagreement (this didn't exist until 10 minutes ago, no, didn't miss it.)

android - How do MyLocationOverlay.getMyLocation() and getLastFix() differ? -

looking @ mylocationoverlay - know difference between: public geopoint getmylocation(); public android.location.location getlastfix(); mylocationoverlay (besides return type)? getmylocation() method return value after location has been found, , getlastfix() return cached last fix, possibly different session? according docs both relate most-recently-set user location , i'd both returns last cached location, , getmylocation provides type conversion location geopoint .

.net - Inserting One to Many Entities using dapper -

i have following 2 classes , corresponding db tables. trying insert full object graph (student multiple courses). looking example on how 1 using dapper. id's auto-increment identity fields. class public class student { public int id {get;set;} public string name {get;set;} public ienumerable<course> courses {get;set;} } public class course { public int id {get;set;} public string name {get;set;} } table student   id [int] (pk)   name [varchar(50)] studentcourse   studentid [int] (fk)   courseid [int] (fk) course   id [int] (fk)   name [varchar(50)] dapper has no general helper solve of ... quite easy wire in trivial case: student student; // populate student ... student.id = (int)cnn.query<decimal>(@"insert student(name) values(@name) select scope_identity()", student); if (student.courses != null && student.courses.count > 0) { foreach(var course in student.courses) { cours

C# Scanning an image for a certain block -

i have picture: size of 1000x1000 white random black dots. (it may contain black square (size 50x50)) is there easy way know if picture contains black square (size 50x50)? thought of scanning every pixel of picture , if black pixel found, scan 1 next him till 50x50 square or till white pixel , keep scanning. have scan on million pixel (if hasn't found square). thats code (no need complete it, said before, take way time scan it. million times if whole picture white , lot more according number of black pixels.) (int = 0; < pic.width; i++) { (int j = 0; j < pic.height; j++) { if (pic.getpixel(i, j) == color.black) { //search entire square @ area } } } and yes, time important (thats why don't want pixel on million times). ideas? like boyer-moore string searching algorithm , if item looking @ not part of looking for, can skip wh

php - Time zone issue -

what going on when time on server out 12 hours? working on site friend, , noticed although server in our timezone, 12 hours behind when writing records db. did checks so: <?php echo(gmstrftime("it %a on %b %d, %y, %x time zone: %z",time())); phpinfo(); ?> result: it thu on jul 21, 2011, 04:46:46 time zone: gmt ... date date/time support enabled "olson" timezone database version 2010.15 timezone database internal default timezone pacific/auckland directive local value master value date.default_latitude 31.7667 31.7667 date.default_longitude 35.2333 35.2333 date.sunrise_zenit 90.583333 90.583333 date.sunset_zenith 90.583333 90.583333 date.timezone pacific/auckland pacific/auckland ask can see, php reports 4:46 am. it's 4:46pm here. reports gmt timezone, phpinfo reports pacific/auckland timezone (gmt+12). i asked webhost going on. weren't sure, system's time correct. , there no other php.ini files being introduced. ide

asp.net mvc 3 - MVC 3 WCF Rest Service In Partial Trust -

i have created mvc 3 wcf rest project using tutorial described here . problem able run project , access rest api when application running @ high trust level when change trust level medium following when access service [securityexception: request permission of type 'system.configuration.configurationpermission, system.configuration, version=4.0.0.0, culture=neutral, publickeytoken=b03f5f7f11d50a3a' failed.] system.security.codeaccesssecurityengine.check(object demand, stackcrawlmark& stackmark, boolean ispermset) +0 system.security.codeaccesssecurityengine.check(codeaccesspermission cap, stackcrawlmark& stackmark) +31 system.security.codeaccesspermission.demand() +46 system.servicemodel.description.configloader.checkaccess(iconfigurationcontextproviderinternal element) +12116253 system.servicemodel.description.configloader.lookupservicebehaviors(string behaviorname, contextinformation context) +12238226 system.servicemodel.description.configloader

multithreading - How to Count the number of threads completed in java without polling for the threads status -

in java program, have start n number of threads, , each thread performs operation . these threads continue operating in parallel. have monitor, number of threads have completed operation , mark progress of operation in percentage. the method, think of poll through entire thread array , keep checking status, unless nodes have completed execution. however, wastage of cpu, other possible way achieve this? easy. have each thread (or each thread's runnable ) increment shared atomicinteger instance when completes. other alternatives include: using semaphore or countdownlatch using callback; e.g. using events , event listener using wait() , notify() . but careful. if using counter determine if threads have finished need deal case thread dies due uncaught exception. can using uncaught exception handler.

Wordpress hook action -

what hook validation on activation , download/upgrade plugin wordpress ? for activation, used register_activation_hook..before activate ( on process of activating plugin ) checking/validation.. if verification return false, hook deactivate plugin ? in order deactivate plugin, hook is: register_deactivation_hook

iphone - Will this leak memory -

i have created nstimer , call every 15 seconds. method call makes web service call. in method write code: getdata *ws = [[getdata alloc]init]; [ws getsomedata:156]; [ws release]; here make instance class call web service method, make call , release object. approach fine or bad? no leak here, if want ws , don't release it, autorelease instead.

Does Apache Ftp Server (java) SFTP work for anyone? -

after trying sftp working ive ended simplest possible sample not work. have created simple class main , copied 2nd (sftp) example http://mina.apache.org/ftpserver/embedding-ftpserver-in-5-minutes.html . server starts without exceptions no client (winscp, cuteftp etc) fail connect. im baffled pointers appreciated...im guessing im missing obvious. sftp , ftps different protocols. sftp related ssh. java implementations include: maverick - commercial implementation apache mina sshd - part of open source apache mina project ftps ftp on ssl. there many, many implementations, including apache ftpserver.

c# - Auto-implemented properties with non null guard clause? -

i agree mark seeman's notion automatic properties evil break encapsulation. concise syntax, readability , convenience bring. i quote: public string name { get; set; } the problem code snippet isn’t contains ceremony. problem breaks encapsulation. in fact “[…] getters , setters not achieve encapsulation or information hiding: language-legitimized way violate them.” james o. coplien & gertrud bjørnvig. lean architecture. wiley. 2010. p. 134. most of time, adding non-null guard clause enough property setter , know if there better way of doing 1 of below. better, mean in more concise/less repetitive way. using code contracts: private string _username; public virtual string username { { return _username; } set { contract.requires(value != null); _username = value; } } using vanilla .net: private string _username; public virtual string username { { return _username; } set { if (value ==

coding style - python styling ** question -

i'm working on first project using python 2.7. we're coming java background , our first instinct write python code in java-esque way. we're trying adapt as possible. far using pylint adapt our code. now keep running situation pylint . every time use **data pass values method i'm getting pylint warning using * or ** . question is: using ** bad styling writing python code? there kind of standard replacement using ? regards, bogdan ** can introduce more tricky bug because accept anything. want code breaks when called wrong. here example: def dostuff(**kwargs): force = 3 if kwargs.get('reallyhard', false): force += 5 # , on # need luck find bug ... dostuff(fancy=true, funky=false, realyhard=true) you shouldn't use ** because lazy type out argument names. not possible though, there legitimate uses too.

QMake: how to let UIC generate BOTH header and source files? -

in .pro file, defined both ui_headers_dir = ./uic/include ui_sources_dir = ./uic/src after compiling, ui_x.h files, contain both declarations , implementations. is mean qmake can't produce simple header file containing minimal declarations , put implementation details source file? this sample generated .h file, can find both declarations , implementations placed within .h file: /******************************************************************************** ** form generated reading ui file 'demodialog.ui' ** ** created: thu 21. jul 16:08:58 2011 ** by: qt user interface compiler version 4.7.2 ** ** warning! changes made in file lost when recompiling ui file! ********************************************************************************/ qt_begin_namespace class ui_demodialog { public: void setupui(qdialog *demodialog) { if (demodialog->objectname().isempty()) demodialog->setobjectname(qstring::fromutf8("demodialo

c++ - Why can I not call templated method of templated class from a templated function -

possible duplicate: confusing template error i have templated class templated method. have function, 2 template arguments creating class first template argument , calling function second. consider example: template<class s> class { public: template<class t> t f1() { return (t)0.0; } }; template<class t,class ct> void function() { a<t> a; a.f1<ct>(); // gcc error in line } gcc gived me: error: expected primary-expression before ‘>’ toke in line marked above. why not work , how can fix it? thanks! nathan a<t> dependent type (i.e. depends on template parameter t ), have specify you're referring template member: a.template f1<ct>();

animation - CSS3 Transform objects position without Transition applied -

i'm looking simple way take object , transform rotatey property without animating pre-set transition. it little like: $(this).css("-webkit-transform","rotatey(180deg)"); $(this).css("-webkit-transition","10s"); then later in code $(this).css("-webkit-transform","rotatey(0)"); $(this).css("-webkit-transition","0"); but above doesn't quite work me due fact needs set , reset transitions animation timing. i need solution takes object point b without fuss. cant seem find way set rotatey property without going through transition/transform prefix. any great, in advance. what need sounds css3 animations. so... in case because want animation in it's finished point, code this $(this).css("-webkit-animation", "someanimation 10s forwards"); the forwards property in css3 animation assures end point in animation permanent rendered style, animation stay in e

c# - Enum for ISO3166 countries - acceptable practice? -

i'm developing asp.net mvc 3 application , uses complex model serialized/deserialized to/from xml. some fields require iso3166 country codes. have several defined enums other restricted lists (which unlikely change) marked xmlenum attribute , displayed neatly using displyfor/editorfor templates. in order consistent created enum of iso3166 country codes. however aware these change overtime requiring me re-build/deploy project. given frequency/likelyhood of iso3166 codes changing, acceptable practice? enumerations conceptually related collection of constants, ie. they not change —a client assembly can make assumption , directly compile in value of enum field. but iso 3166 change, often several times year . example creation of new country south sudan need reflected in update.

ruby on rails 3 - Sum column values under condition -

suppose this: works table name created_at size i want list works , in end sum size values, under 1 condition. created_at must < 1 year ago. i know @works.sum(&:size) works doesn't filter out 'created_at' part. then got @works.sum(&:size, :conditions => ['created_at > ?', 1.year.ago]) but keep getting compile error expecting ) instead of , help please? better way accomplish this? you can use scope keep model clean #controller class workscontroller < applicationscontroller def index @works.recent.sum(&:size) end end #model class work scope :recent, ->{ where('created_at > ?', 1.year.ago) } end

c# - What is equivalent to Application.DoEvents() in WPF applications -

from msdn, seems application.doevents() available in windows.forms. equivalent thing in wpf. you shouldn't using in windows forms. don't perform long-running tasks on ui thread - use background thread , use dispatcher update ui required. use of application.doevents code smell. don't know whether there is equivalent in wpf, should try avoid if there is.

android - Launching installedapplication -

how launch installed application? i have installed using below: file file = new file(dir, "app.apk"); intent intent = new intent(intent.action_view); intent.setdataandtype(uri.fromfile(file), "application/vnd.android.package-archive"); startactivity(intent); second time, checking if package installed, if yes, want launch. intent intent = new intent(com.example.app); thanks in advanced! i'm using method. should change package , class names. private static final string gps_status_package_name = "com.eclipsim.gpsstatus2"; private static final string gps_status_class_name = "com.eclipsim.gpsstatus2.gpsstatus"; /** * run gpsstatus & toolbox application * * @param context * can start activity */ public static void rungpsstatus(context context) { intent intent = new intent(intent.action_main); intent.setcomponent(new componentname(gps_status_packa

c++ - KRB_AP_REQ ticket from SSPI -

i have linux server application using kerberos client authentication , client needs run on windows. kerberos tickets issued windows active directory. client authenticates on server if use mit kfw 3.2.2. api retrieving , tgs tickets kerberos server , store them in kerberos credentials store. problem approach user needs input credentials again. solution access ms lsa store not work. neither ms2mit.exe application. not matter if run normal user or administrator, or if disable uac completely. why use sspi on client make krb_ap_req message send server. possible. if yes how can done? if no, other options? please note server built , require significant effort change it, therefore find solution on windows. you can use aquirecredentialshandle , initializesecuritycontext functions of windows sspi subsystem valid ticket , authenticate against linux based server. first use acquirecredentialshandle() , use multiple calls initializesecuritycontext tokens server until authenticated

multithreading - Asp.Net. Synchronization access(mutex) -

for synchronizing access nhibernate session @ web environment try use mutex: public class factoryrepository { private factoryrepository() { } private static mutex _sessionmutex = new mutex(); private static isessionfactory factory; public static isessionfactory sessionfactory { { factory = factory ?? new configuration().configure().buildsessionfactory(); return factory; } } public static isession session { { isession currentsession; _sessionmutex.waitone(); if (httpcontext.current != null) { httpcontext context = httpcontext.current; currentsession = context.items[sessionkey] isession; if (currentsession == null || !currentsession.isopen) { currentsession = sessionfactory.opensession(); context.items[sessionkey] = currentsession;

Add event listener in javascript for IE 7 -

i want make list of menu using images. each menu has 2 images (filename.jpg & filename_active.jpg). everytime put mouse on image, image change other one. works okay in firefox , chrome, have problems in ie 7 , lower. problem is, javascript read last part (in case, read third menu only). code show below part of javascript code in ie. let me show code : html : <ul> <li class="caresoul_menu active" id="menuli_first"><a href="first.php"><img src="img_first_active.jpg" /></a></li> <li class="caresoul_menu" id="menuli_two"><a href="two.php"><img src="img_two.jpg" /></a></li> <li class="caresoul_menu" id="menuli_three"><a href="three.php"><img src="img_three.jpg" /></a></li> javascript : var caresoul_menu = dom.getelementsbyclassname('caresoul_menu', &#

c# - How to return a double or string for a method -

i have method: public static double c(string val) { return math.round(convert.todouble(val), 4); } where pass in string, , if double, want round return double, if string, want return string is. of parameters pass in strings start, how determine if string or double, , how rewrite methoed have return type flexible enough return either? ideally, use type variant in vba, dont think there analog in c#. the following try parse double . if returns true put double in output variable output ; else return false means val isn't double , should use string val instead. public static bool c(string val, out double output) { if (double.tryparse(val, out output)) { output = math.round(output, 4); return true; } else { output = 0; return false; } } use this: string val = "123.45678"; double output; if ( c(val, out output) ) { // use double output } else { // val isn't double, use val direc

Stopping Excel Macro executution when pressing Esc won't work -

i'm running excel 2007 on xp. is there way stop macro running during execution other pressing escape? if think created infinate loop or otherwise messed hit escape , throws error macro stops. this time (and i've done before not badly), set msgbox quick debugging. turns out had loop 6000 times, made means had "ok" 6000 message boxes, took several minutes. didn't save before running (another mistake) couldn't open task manager exit. is there way stop execution of macro in case goof again? use crtl + break suspend execution @ point. put break mode , can press f5 continue execution or f8 execute code step-by-step in visual debugger. of course works when there no message box open, if vba code opens message boxes reason become little tricky press keys @ right moment. you can edit of code while running. use debug.print print out messages immediate window in vba editor, that's way more convenient msgbox . use breakpoints or stop

powerbuilder - PB won't accept SQL ORDER BY statement -

i have nesetd sql qry works ssms 2008 , in pb version 11.2. when add order statement in ssms ist works, when add order statement in pb following error: select error: sqlstate = 37000 [microsoft][odbc sql server driver][sql server]incorrect syntax near keyword 'and'. any ideas why happening , how can resolve it? thanks, doug that error syntax error sql engine, i’d suggest use sql profiler trace sql determine problem , go there.

swing - java comboBox autocomplete -

can tell me how change code have autoselection , able write not existing items, because doesnt let me write new items. public class comboboxfill extends plaindocument { comboboxmodel model; jcombobox combobox=new jcombobox(); jtextcomponent editor; public comboboxfill(comboboxmodel model, jcombobox combobox,jtextcomponent editor) { this.model = model; this.combobox=combobox; this.editor=editor; } public void insertstring (int offs,string str,attributeset a) throws badlocationexception { string currenttext=gettext(0,getlength()); string beforeoffset=currenttext.substring(0,offs); string afteroffset=currenttext.substring(offs,currenttext.length()); string futuretext = beforeoffset+str+afteroffset; object item =lookupitem(futuretext); if (item!=null) { combobox.setselecteditem(item); }else { item = combobox.getselecteditem(); offs=offs-str.length(); combobox.gettoolkit().beep

eclipse - How to implement fix Bluetooth Device in Android -

i want write bluetooth app without discovery/scanning. want hardcode server device, client needs connect in code. if use constructor: public connectthread(bluetoothdevice device) { how have implement device? variable of mac address? if try this: device = new bluetoothdevice("xx:xx:xx:xx:xx:xx"); eclipse says: " constructor not visible " you can use bluetoothadapter.getremotedevice(string) create bluetoothdevice representing device of known bluetooth device address. bluetoothadapter myadapter = getdefaultapater(); bluetoothdevice mydevice; mydevice = myadapter.getremotedevice("xx:xx:xx:xx:xx:xx");

c# - Spiked vertexes on generated Icosphere -

i've been working on program generate icosphere. (a sphere evenly distributed vertexes across face, used terrain deformation) i have pretty done, sphere generated, subdivided , drawn. problem running somewhere in code, of vertices (the twelve starting vertexes, believe) being set twice radius, rather radius. here 3 images, showing icosphere @ zero, 1 , 2 refinement passes: http://i41.photobucket.com/albums/e262/cstgirllover/cho/ico0refinement.png http://i41.photobucket.com/albums/e262/cstgirllover/cho/ico1refinement.png http://i41.photobucket.com/albums/e262/cstgirllover/cho/ico2refinement.png and here code generates icosahedron, , breaks down icosphere: using system; using system.collections.generic; using system.linq; using system.text; using microsoft.xna.framework; using microsoft.xna.framework.graphics; namespace icosahedron_test { class icosahedron { int radius; // radius of planet int refinement; // number of times refine traingles int fac

javascript - Why is this jQuery animation so SLOW on Firefox 4/5? -

Image
edit phrogz: appears problem framerate of jquery animation when particular complex css applied. see video @ bottom example of problem. i think hard copy , paste whole code here. i've create fiddle this. to honest, css not important on this (i putted have decent grid). removed many functions original version, in fact aren't important. the 1 works clicking on buttons + tracks (which call addtrack()) adds new track/line in grid. tested on chrome, ie, , firefox < 4 version. there isn't problem. it's rapid , fluid. the problem on firefox 4 or 5. it's slow add new track/line. it's fast turtle. what function done clone (copy handler) element trackon , written in hidden field (tracklistoff) , add (insertafter) applying fade effect. (thats means new line in grid). why behaviour on firefox? many elements browse on dom suppose. need rid slow attitude... can do? edit you can hear difference chrome , firefox (5, last version) on this video. try

.net - Easiest way to return list<T> without first element -

somehow don´t @ moment want. i data database via nhibernate. icriteria criteria = session.createcriteria(typeof(price)); criteria.addorder(new nhibernate.expression.order("validfrom", false)); list<price> prices = criteria.list().cast<price>().tolist(); now want return list without first element (the newest price). got working, easiest way? the easiest way writing criteria.list().cast<price>().skip(1).tolist();

environment variables - Python doesn't load _fileio library -

i have problem, python doesn't loads dynamic c library _fileio ~ $ python python 2.7.1+ (r271:86832, apr 11 2011, 18:05:24) [gcc 4.5.2] on linux2 type "help", "copyright", "credits" or "license" more information. not open pythonstartup ioerror: [errno 2] no such file or directory: '/home/sven/.pythonrc' >>> import io traceback (most recent call last): file "<stdin>", line 1, in <module> file "/usr/lib/python2.6/io.py", line 63, in <module> import _fileio importerror: no module named _fileio >>> ~ $ locate _fileio /usr/lib/python2.6/lib-dynload/_fileio.so ~ $ echo $pythonpath /usr/lib/python2.6/ greetings sven seems environment issue, stemming line: ioerror: [errno 2] no such file or directory: '/home/sven/.pythonrc' to solve this, find .pythonrc , make sure pythonstartup environment variable in .bashrc file points file location. if in

sql server - Foreach Loop Container with Foreach File Enumerator option iterates all files twice -

i using ssis foreach loop container iterate through files pattern on network share. i encountering kind of unreproducible malfunction of loop container: sometimes loop executed twice. after files processed starts on first file. have encountered similar bug? maybe not directly using ssis accessing files on windows share kind of technology? error relate network issues? thanks. i found case whilst working excel files , using *.xlsx wildcard drive foreach. once put logging in place noticed when excel opened produced excel file prefixed ~$. picked foreach loop. so used trick similar http://geekswithblogs.net/compudicted/archive/2012/01/11/the-ssis-expression-wayndashskipping-an-unwanted-file.aspx exclude files ~$ in filename.

arrays - Ruby Select and Reject in one method -

is there built in method combine functions of select (find block equates true) , reject (find block equates false)? something like good, bad = list.magic_method { |obj| obj.good? } wouldn't hard myself nih , that. :) looks if enumerable.partition after. = enumerable.partition (from ruby core) ------------------------------------------------------------------------------ enum.partition {| obj | block } -> [ true_array, false_array ] enum.partition -> an_enumerator ------------------------------------------------------------------------------ returns 2 arrays, first containing elements of enum block evaluates true, second containing rest. if no block given, enumerator returned instead. (1..6).partition {|i| (i&1).zero?} #=> [[2, 4, 6], [1, 3, 5]] interesting, didn't know there. ri amazing tool...