Posts

Showing posts from February, 2012

qt - Is emitting a disconnected signal bad? -

i defined signal in myapp , emit in different places within code, need when my_defined_flag defined, question is: should change every: emit mysignal(); to #ifdef my_defined_flag emit mysignal(); #endif ? and if answer "yes" then, there better idea? the class emits signal shouldn't care if listens or not. users of class connect signals if need to, or not. maybe need connect of them. there no harm signal nobody connected to, call cheap. it's every other part of api: signals part of interface design, service provided class users, might use part of api, or not, own business.

php - Is an X-Requested-With header server check sufficient to protect against a CSRF for an ajax-driven application? -

i'm working on ajax-driven application requests pass through amounts main controller which, @ bare bones, looks this: if(strtolower($_server['http_x_requested_with']) == 'xmlhttprequest') { fetch($page); } is sufficient protect against cross-site request forgeries? it's rather inconvenient have rotating token when entire page isn't refreshed each request. i suppose pass , update unique token global javascript variable every request -- somehow feels clumsy , seems inherently unsafe anyway. edit - perhaps static token, user's uuid, better nothing? edit #2 - the rook pointed out, might hair-splitting question. i've read speculation both ways , heard distant whispers older versions of flash being exploitable kind of shenanigans. since know nothing that, i'm putting bounty can explain how csrf risk. otherwise, i'm giving artefacto . thanks. i'd it's enough. if cross-domain requests permitted, you'd doomed ...

sql - one to many join on 3 levels all on the same table -

i have table pages, these pages have parents pages in same table. for examples sake table looks like: table: pages pageid :key pageparent :foreign key pagename now question sql when creating menustructure like: pageid pageparent pagename 1 null home 2 1 page_under_home1 5 2 page_under_pageid2_1 6 2 page_under_pageid2_2 4 1 page_under_home2 5 4 page_under_pageid4_1 7 5 page_under_pageid5_1 6 4 page_under_pageid4_2 9 6 page_under_pageid6_1 10 6 page_under_pageid6_2 8 1 page_under_home3 11 1 page_under_home4 12 11 page_under_pageid11_1 13 12 page_under_pageid12_1 i have this: select p1.pageid, p1.pagename, p1.pageparent, p2.pagename expr1 ...

Is there a way to take a screenshot using Java and save it to some sort of image? -

simple title states: can use java commands take screenshot , save it? or, need use os specific program take screenshot , grab off clipboard? believe or not, can use java.awt.robot "create image containing pixels read screen." can write image file on disk. i tried it, , whole thing ends like: rectangle screenrect = new rectangle(toolkit.getdefaulttoolkit().getscreensize()); bufferedimage capture = new robot().createscreencapture(screenrect); imageio.write(capture, "bmp", new file(args[0])); note: capture primary monitor. see graphicsconfiguration multi-monitor support.

.net - Saving an open generic type in an array? -

i facing problem .net generics. thing want saving array of generics types (graphicsitem): public class graphicsitem<t> { private t _item; public void load(t item) { _item = item; } } how can save such open generic type in array? implement non-generic interface , use that: public class graphicsitem<t> : igraphicsitem { private t _item; public void load(t item) { _item = item; } public void somethingwhichisnotgeneric(int i) { // code goes here... } } public interface igraphicsitem { void somethingwhichisnotgeneric(int i); } then use interface item in list: var values = new list<igraphicsitem>();

database design - When/Why to use Cascading in SQL Server? -

when setting foreign keys in sql server, under circumstances should have cascade on delete or update, , reasoning behind it? this applies other databases well. i'm looking of concrete examples of each scenario, preferably has used them successfully. summary of i've seen far: some people don't cascading @ all. cascade delete cascade delete may make sense when semantics of relationship can involve exclusive "is part of " description. example, orderline record part of parent order, , orderlines never shared between multiple orders. if order vanish, orderline should well, , line without order problem. the canonical example cascade delete someobject , someobjectitems, doesn't make sense items record ever exist without corresponding main record. you should not use cascade delete if preserving history or using "soft/logical delete" set deleted bit column 1/true. cascade update cascade update may make sense when use real...

c# - Optimize Windows Form Load Time -

i have windows form takes quite bit of time load initially. however, each subsequent request load form doesn't take long. there way optimize form's load time? you can use ngen . i use tip reduce memory footprint on startup . the native image generator (ngen.exe) tool improves performance of managed applications. ngen.exe creates native images, files containing compiled processor-specific machine code, , installs them native image cache on local computer. runtime can use native images cache instead using just-in-time (jit) compiler compile original assembly.

sql - what is the quickest way to run a query to find where 2 fields are the same -

i have table id, first, last , want run query says give me every record combination of first , last exists more once (i trying find duplicate records) edit concatenation give out false answers pointed out in comments ('roberto neil' vs 'robert oneil'. here answer eliminates concatenation issue. found out non duplicates , eliminated them final answer. with mytable ( select 1 id, 'john' firstname, 'doe' lastname union select 2 id, 'john' firstname, 'doe' lastname union select 3 id, 'tim' firstname, 'doe' lastname union select 4 id, 'jane' firstname, 'doe' lastname union select 5 id, 'jane' firstname, 'doe' lastname ) select id, firstname, lastname mytable selecttable id not in ( select min (id) mytable searchtable group firstname, lastname having count (*) = 1 ) old solution use group , having.. check out working ...

python - How to extend pretty print module to tables? -

i have pretty print module, prepared because not happy pprint module produced zillion lines list of numbers had 1 list of list. here example use of module. >>> a=range(10) >>> a.insert(5,[range(i) in range(10)]) >>> [0, 1, 2, 3, 4, [[], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5, 6, 7, 8]], 5, 6, 7, 8, 9] >>> import pretty >>> pretty.ppr(a,indent=6) [0, 1, 2, 3, 4, [ [], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5, 6, 7, 8]], 5, 6, 7, 8, 9] code this: """ pretty.py prettyprint module version alpha 0.2 mypr: pretty string function ppr: print of prett...

What is the benefit of using ONLY OpenID authentication on a site? -

from experience openid , see number of significant downsides: adds single point of failure site not failure can fixed site if detected. if openid provider down 3 days, recourse site have allow users login , access information own? takes user sites content , every time logon site if openid provider not have error, user re-directed site login. login page has content , links. there chance user drawn away site go down internet rabbit hole. why want send users company's website? [ note: provider no longer , seems have fixed problem (for now).] adds non-trivial amount of time signup sign site new user forced read new standard, chose provider, , signup. standards technical people should agree in order make user experience frictionless. not should thrust on users. it phisher's dream openid incredibly insecure , stealing person's id log in trivially easy. [ taken david arno's answer below ] for of downside, 1 upside allow users have fewer logins on i...

C (or any) compilers deterministic performance -

whilst working on recent project, visited customer qa representitive, asked me question hadn't considered before: how know compiler using generates machine code matches c code's functionality , compiler deterministic? to question had absolutely no reply have taken compiler granted. takes in code , spews out machine code. how can go , test compiler isn't adding functionality haven't asked for? or more dangerously implementing code in different manner expect? i aware perhapse not issue everyone, , indeed answer might be... "you're on barrel , deal it". however, when working in embedded environment, trust compiler implicitly. how can prove myself , qa right in doing so? for safety critical embedded application certifying agencies require satisfy "proven-in-use" requirement compiler. there typically requirements (kind of "hours of operation") need met , proven detailed documentation. however, people either cannot or d...

.net - Getting started with Silverlight development -

how 1 start development in silverlight? does 1 need new ide? or visual studio support? yes there tooling support visual studio. still in beta though. get started building silverlight 2 applications 1) install visual studio 2008 install silverlight tools beta 2 visual studio 2008 add-on visual studio 2008 allows use .net create silverlight 2 beta 2 web sites. silverlight 2 beta 2 runtime , silverlight 2 beta 2 sdk installed part of install. additional information read overview , silverlight 2 beta 2 readme notes. note if have visual studio 2008 service pack 1 beta installed, please see information details on installing correctly. 2) install expression blend 2.5 june 2008 preview preview version of expression blend designing silverlight 2 experiences. 3) install deep zoom composer tool allows prepare images use deep zoom feature in silverlight 2. one thing watch out silverlight not support synchronous calls server. calls asynchronous of this beta .

architecture - How do you avoid Technical Debt while still keep true to Agile, i.e.: avoiding violation of YAGNI and avoiding BDUF? -

technical debt via martin fowler , via steve mcconnell yagni (you ain't gonna need it) via wikipedia bduf (big design front) via wikipedia update: clarify question, think can state way , keep meaning: "in ways you, agile practioner, find right balance between "quick , dirty" (unintentionally risking technical debt while attempting adhere yagni) , over-engineering (bduf) within each iteration?" it seems if stick "plan, do, adapt; plan, do, adapt" idea of agile (iterations, iteration reviews) avoid things default. bduf contrary idea of agile estimating & planning if agile, wont bduf automatically. the purpose of release & iteration planning meetings make sure adding valuable features project iteration. if keep in mind, you'll avoid yagni free. i recommend mike cohn books on agile planning: user stories applied agile estimating , planning update: after clarification avoiding yagni , bduf within iterati...

sql server - What is the best implementation for DB Audit Trail? -

a db audit trail captures user last modified, modified date, , created date. there several possible implementations: sql server triggers add usermodified, modifieddate, createddate columns database , include logic in stored procedures or insert, update statements accordingly. it nice if include implementation (or link to) in answer. depending on you're doing, might want move audit out of data layer data access layer. give more control. i asked similar question wrt nhibernate , sqlserver here .

asp.net - Help with aligning the controls -

i have dropdownlist (asp.net) , when user change selection dropdownlist display respected div. i need in aligning controls. , want this: dropdownlistcontrol -- > selected_div -- > button below soucr code.... <div style="width: 880px; padding-top: 2px; border-bottom: none; height: 28px;"> <asp:label id="lblfilterresultsby" runat="server" text="filter results by:"></asp:label> <asp:dropdownlist id="ddlfilter" runat="server" width="221px"> <asp:listitem text="select..." value=""></asp:listitem> <asp:listitem text="date" value="date"></asp:listitem> <asp:listitem text="subject" value="subject"></asp:listitem> <asp:listitem text="status" value="status"></asp:listitem> </as...

How do websites get your real IP address when you're proxied? -

from trusted computer engineer , rapidshare, seems possible real ip address when you're proxied. note define proxied mean using kind of tunneling (vpn, ssh, etc) computer not share ip address. not mean proxy sites, since trivial javascript , server side code can ip address easily. my question though how? computer engineer mentioned said ask browser directly (presumably js) , cough real ip. mentioned using tracking image, although don't think work since thats requested proxy, not directly. on http proxies, can use header name x-forwarded-for . format of header looks it: x-forwarded-for: client1, proxy1, proxy2 this header added http proxy, web applications check it, of course can send fake header. supported major proxy servers squid, ms isa server, cisco cache engine, etc.

Apache Fall Back When PHP Fails -

i wondering if knew of method configure apache fall returning static html page, should (apache) able determine php has died? provide developer elegant solution displaying error page , not (worst case scenario) source code of php page should have been executed. thanks. the php source code displayed when apache not configured correctly handle php files. is, when proper handler has not been defined. on errors, shown can configured on php.ini, display_errors variable. should set off , log_errors on on production environment. if php dies, apache return appropriate http status code (usually 500) page defined errordocument directive. if didn't die, got stuck in loop, there not can far know. you can specify different page different error codes.

jQuery this and Selector $(this:first-child).css('color', 'red'); -

is possible use :selector following in jquery? $('.galler_attr').bind('click', function() { $(this:first-child).css('color', 'red'); }); no. you're trying mix function context string. use this context of selector or call find() on $(this) search within dom scope of element. either $('.galler_attr').bind('click', function() { $(this).find(':first-child').css('color', 'red'); }); or (which resolves above internally): $('.galler_attr').bind('click', function() { $(':first-child', this).css('color', 'red'); });

c# - NHibernate save object, a column is null -

the database has 2 table,one mb_user table , other mb_comment table。a user have comments.when insert comment mb_comment ,the comment_user_id of mb_comment null.i can't save value of comment_user_id.please me! map file mb_user map file <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="miserblogdata" namespace="miserblogdata.entities" default-lazy="false"> <class name="a_person" table="mb_user" discriminator-value="0"> <id name="id" column ="user_id" > <generator class ="native"/> </id> <discriminator column="user_role" type="int" /> <property name="state" column="user_state" /> <property name ="name" column="user_name" /> <property name ="pwd" col...

objective c - Confused about alloc and release -

i'm little confused objective-c , allocating/releasing objects. if this: nsstring *mystring; if([somestring isequaltostring: @"test1"]){ mystring = @"got 1"; }else{ mystring = @"got 2"; } do have release mystring after that? and same self-defined objects: myownobject *someobject = [somearray objectatindex: 1]; mybutton.label1.text = someobject.name; do have release someobject ? the reason why i'm asking memory-leaks in method , can't find is. i'm trying figure out whether alloc/release stuff correctly. leak occurs on nsplaceholderstring (i guess that's somewhere hidden in nib-file). also - if have object, allocate it, use of properties, release of every property on dealloc - cause memory leaks? sorry - hope questions make @ least some sense :) thanks help! listen me. this rule matters. if use method "copy", "alloc", "new", or "retain" in name you...

optimization - Refactoring dissassembled code -

you write function and, looking @ resulting assembly, see can improved. you keep function wrote, readability, substitute own assembly compiler's. there way establish relationship between high-livel language function , new assembly? if looking @ assembly, fair assume have understanding how code gets compiled down. if have knowledge, possible 'reverse enginer' changes original language better not bother. the optimisations make small in comparison time , effort required in first making these changes. suggest leave kind of work compiler , go have cup of tea. if changes significant, , performance critical, (as in embedded world) might want mix normal code assemblar in fashion, however, on computers , chips performance sufficient avoid headache. if really need more performance, optimise code not assembly.

unit testing - Disadvantages of Test Driven Development? -

what lose adopting test driven design? list negatives; not list benefits written in negative form. several downsides (and i'm not claiming there no benefits - when writing foundation of project - it'd save lot of time @ end): big time investment. simple case lose 20% of actual implementation, complicated cases lose more. additional complexity. complex cases test cases harder calculate, i'd suggest in cases try , use automatic reference code run in parallel in debug version / test run, instead of unit test of simplest cases. design impacts. design not clear @ start , evolves go along - force redo test generate big time lose. suggest postponing unit tests in case until have grasp of design in mind. continuous tweaking. data structures , black box algorithms unit tests perfect, algorithms tend changed, tweaked or fine tuned, can cause big time investment 1 might claim not justified. use when think fits system , don't force design fit tdd.

How to copy a file to a remote server in Python using SCP or SSH? -

i have text file on local machine generated daily python script run in cron. i add bit of code have file sent securely server on ssh. if want simple approach, should work. you'll want ".close()" file first know it's flushed disk python. import os os.system("scp file user@server:path") #e.g. os.system("scp foo.bar joe@srvr.net:/path/to/foo.bar") you need generate (on source machine) , install (on destination machine) ssh key beforehand scp automatically gets authenticated public ssh key (in other words, script doesn't ask password). ssh-keygen example

Prevent Visual Studio from crashing (sometimes) -

how can stop visual studio (both 2005 , 2008) crashing (sometimes) when select "close this" option?this not happen time either. first, check windows update , make sure both vs environments date. if doesn't help, uninstall them both completely, reinstall 2005, update , test it. if 2005 doesn't crash, install 2008, update , test them both. don't install add-ons may have been using until you've reinstalled , tested both editions of vs. if 1 or other crash, should try filing bug against visual studio . if didn't crash, install add-ons use 1 @ time , continue test both editions after each one. (this take ages, that's how has be) when start crashing, remove offending add-on, , file bug add-on developer. (be sure tell them other add-ons you're using, in case happens when 2 conflicting add-ons installed.)

c# - Is there any elegant way in LINQ to bucket a collection into a set of lists based on a property -

i have collection of cars. want bucket separate lists property of car . . .lets brand. so if have collection of ford, chevy, bmw, etc, want seperate list each of buckets. something like: ienumberable<car> mycarcollection = getcollection(); list<ienumerable<car>> buckets = mycarcollection.bucketby(r=>r.brand) does exist or need "manually" through loops return mycarcollection.groupby(r => r.brand);

jquery - jQueryUI: selectable - cancel option when dragging the lasso over an element -

the cancel option on selectable following: prevents selecting if start on elements matching selector. is there build-in way make ignore elements if drag on them? cause cancel works if start element if start selectable element , drag lasso on 1 of canceled elements still select them. if there isn't build-in way guess have add myself selecting event. you can use filter option :not() selector this, example: $(".selector").selectable({ cancel: 'li.cancelclass', filter: 'li:not(.cancelclass)' }); this prevents same cancel elements being selected in lasso either...they do selected because default filter * .

javascript - What’s the best way to reload / refresh an iframe? -

i reload <iframe> using javascript. best way found until set iframe’s src attribute itself, isn’t clean. ideas? document.getelementbyid('some_frame_id').contentwindow.location.reload(); be careful, in firefox, window.frames[] cannot indexed id, name or index

When do you use Java's @Override annotation and why? -

what best practices using java's @override annotation , why? it seems overkill mark every single overridden method @override annotation. there programming situations call using @override , others should never use @override ? use every time override method 2 benefits. can take advantage of compiler checking make sure overriding method when think are. way, if make common mistake of misspelling method name or not correctly matching parameters, warned method not override think does. secondly, makes code easier understand because more obvious when methods overwritten. additionally, in java 1.6 can use mark when method implements interface same benefits. think better have separate annotation (like @implements ), it's better nothing.

encoding - Error reading UTF-8 file in Java -

i trying read in sentences file contains unicode characters. print out string reason messes unicode characters this code have: public static string readsentence(string resourcename) { string sentence = null; try { inputstream refstream = classloader .getsystemresourceasstream(resourcename); bufferedreader br = new bufferedreader(new inputstreamreader( refstream, charset.forname("utf-8"))); sentence = br.readline(); } catch (ioexception e) { throw new runtimeexception("cannot read sentence: " + resourcename); } return sentence.trim(); } the problem in way string being output. i suggest confirm correctly reading unicode characters doing this: for (char c : sentence.tochararray()) { system.err.println("char '" + ch + "' unicode codepoint " + ((int) ch))); } and see if unicode codepoints correct characters being messed up. if corre...

web services - using browsers programatically -

i want build following back-end service: for each call service, spawn web browser loads webpage (including flash) , returns screenshot of page caller @ intervals (ie every 3 seconds) until caller disconnects. needs scale many callers (thousands perhaps), each of needs own browser session. when decided needed build program, surprised had no idea how it. on stackoverflow, found following link looks promising: http://www.genuitec.com/about/labs.html any other ideas? thanks! this app shows promise: http://sikuli.csail.mit.edu/ it's tricky setup. think looking for.

How do you send a HEAD HTTP request in Python 2? -

what i'm trying here headers of given url can determine mime type. want able see if http://somedomain/foo/ return html document or jpeg image example. thus, need figure out how send head request can read mime type without having download content. know of easy way of doing this? edit : answer works, nowadays should use requests library mentioned other answers below. use httplib . >>> import httplib >>> conn = httplib.httpconnection("www.google.com") >>> conn.request("head", "/index.html") >>> res = conn.getresponse() >>> print res.status, res.reason 200 ok >>> print res.getheaders() [('content-length', '0'), ('expires', '-1'), ('server', 'gws'), ('cache-control', 'private, max-age=0'), ('date', 'sat, 20 sep 2008 06:43:36 gmt'), ('content-type', 'text/html; charset=iso-8859-1')] there...

sorting - Sort a Map<Key, Value> by values (Java) -

i relatively new java, , find need sort map<key, value> on values. since values not unique, find myself converting keyset array , , sorting array through array sort custom comparator sorts on value associated key. there easier way? here's generic-friendly version you're free use: import java.util.*; public class maputil { public static <k, v extends comparable<? super v>> map<k, v> sortbyvalue(map<k, v> map) { list<map.entry<k, v>> list = new linkedlist<map.entry<k, v>>(map.entryset()); collections.sort( list, new comparator<map.entry<k, v>>() { public int compare(map.entry<k, v> o1, map.entry<k, v> o2) { return (o1.getvalue()).compareto( o2.getvalue() ); } }); map<k, v> result = new linkedhashmap<k, v>(); (map.entry<k, v> entry : list) { result.put(entry.getk...

mysql - RoR scaffold add field after script/generate -

i generated scaffold , put in type:value need add field / db column how add type:value without destroying , restarting whole project? rake aborted! mysql::error: have error in sql syntax; check manual corres ponds mysql server version right syntax use near '(11), `titl e` varchar(255) default null, `artist_old` varchar(255) default null,' @ line 1 : create table `albums` (`id` int(11) default null auto_increment primary key(11 ), `title` varchar(255) default null, `artist_old` varchar(255) default null, `r elease_date` datetime default null, `genre` varchar(255) default null, `feature` int(11) default null, `image_path` varchar(255) default null, `created_at` date time default null, `updated_at` datetime default null, `artist_id` int(11) defau lt null) engine=innodb usually when use scaffold command create migration in db/migrate/ folder, containing database setup model, example: class createcomments < activerecord::migration def self.up create_table...

iphone - Cocoa Touch: How To Change UIView's Border Color And Thickness? -

i saw in inspector can change background color, i'd change border color , thickness, possible? thanks you need use view's layer set border property. e.g: #import <quartzcore/quartzcore.h> ... view.layer.bordercolor = [uicolor redcolor].cgcolor; view.layer.borderwidth = 3.0f; you need link quartzcore.framework access functionality.

iphone - NSXMLParser crashing on faulty xmls, no correct error handling? -

anyone else experiencing crashes deep down in iphone libraries when nsxmlparser parses xml containing errors? thought supposed call: (void)parser:(nsxmlparser *)parser parseerroroccurred:(nserror *)parseerror but instead crashes entire app somewhere inside _xmlraiseerror. is else experiencing , there way catch this, instead of having program crash? the error handling not found in touchxml framework or in cxmldocument. in libxml framework (to knowledge) output string not raise exception. passing error pointer , reading straight after. if not nil, error has occurred. if getting crashes error should somewhere else... hope helps.

algorithm - Could a truly random number be generated using pings to pseudo-randomly selected IP addresses? -

the question posed came during 2nd year comp science lecture while discussing impossibility of generating numbers in deterministic computational device. this suggestion didn't depend on non-commodity-class hardware. subsequently nobody put reputation on line argue definitively or against it. anyone care make stand or against. if so, how mention possible implementation? i'll put rep on line (at least, 2 points of per downvote). no. a malicious machine on network use arp spoofing (or number of other techniques) intercept pings , reply them after periods. not know random numbers are, control them. of course there's still question of how deterministic local network is, might not easy in practice. since no benefit pinging random ips on internet, might draw entropy ethernet traffic. drawing entropy devices attached machine well-studied principle, , pros , cons of various kinds of devices , methods of measuring can e.g. stolen implementation of /dev/ra...

linux - How to do something with Bash when a text line appears in a file -

i want run command text appears in log file. how do in bash? use command tail -f file.log | grep --line-buffered "my pattern" | while read line echo $line done the --line-buffered key here, otherwise read fail.

c - Parenthesis surrounding return values -

quite in ansi c code can see parenthesis sorrounding single return value. like this:- int foo(int x) { if (x) return (-1); else return (0); } why use () around return value in cases? ideas? can see no reason that. there isn't reason...it's old convention. to save space, programmers final math in return line instead of on it's own line , parens ensure there make easier see single statement returned, this: return (x+i*2); instead of int y = x+i*2; return y; the parenthesis became habit , stuck.

deployment - web.xml and relative paths -

in web.xml set welcome file jsp within web.xml <welcome-file>web-inf/index.jsp</welcome-file> inside index.jsp forward on servlet <% response.sendredirect(response.encoderedirecturl("myservlet/")); %> however application tries find servlet @ following path applicationname/web-inf/myservlet the problem web-inf should not in path. if move index.jsp out of web-inf problem goes there way can around this? <% response.sendredirect(response.encoderedirecturl("/myservlet/")); %>` since jsp served web-inf directory servlet url resolved relative path. adding / before resolve url context root

java me - Custom Date Formatting in J2ME -

i format j2me date object show date part, not date , time. easiest way? need include external library this. java.util.calendar has methods required format date output.

javascript - how to make a 'div' element drag on iphone -

this code,for reason , can't use javascript lib ,like ;jquery: <!doctype html public "-//wapforum//dtd xhtml mobile 1.0//en" "http://www.wapforum.org/dtd/xhtml-mobile10.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" style="height: 100%;"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width,minimum-scale=0.3,maximum-scale=5.0,user-scalable=yes"> <meta name="apple-mobile-web-app-capable" content="yes" /> </head> <body style="height: 100%;margin:0;"> <style type="text/css"> #draggable { width: 100px; height: 100px; padding: 0.5em; float: left; margin: 10px 10px 10px 0; border:1px solid #dddddd; color:#333333; background:#f2f2f2; cursor:move; } #droppable { width: 150px; height: ...

About Flex with PHP kick start -

i php developer , wish start application php flex combination. can direct me tutorial/sample other zend tutors. since working drupal have no idea zend concepts. do need know actionscript start flex? thanks in advance, gobi :) i don't know flex iam php developer flex friends told me go throught book foundation flex developers:data-driven applications php, asp.net, coldfusion, , lcds publishers friendsofed. book provide think looking for.

sql - Unique vs Distinct keyword in Oracle -

i bit confused uses of these words. have table following columns: site, lat, long, name, ...... i want results unique (or distinct) lat, long. how achieve this? select unique cola, colb atable select distinct cola, colb atable in context, unique , distinct mean same thing. distinct ansi standard, whereas unique not. please note unique has many other meanings when used in other area's ie index creation etc.

What is the best comment in source code you have ever encountered? -

what best comment in source code have ever encountered? i particularly guilty of this, embedding non-constructive comments, code poetry , little jokes of projects (although have enough sense remove directly offensive before releasing code). here's 1 i'm particulary fond of, placed far, far down poorly-designed 'god object': /** * brave souls far: chosen ones, * valiant knights of programming toil away, without rest, * fixing our awful code. you, true saviors, kings of men, * this: never gonna give up, never gonna let down, * never gonna run around , desert you. never gonna make cry, * never gonna goodbye. never gonna tell lie , hurt you. */ i'm sorry!!!! couldn't myself.....! and another, i'll admit haven't released wild, though very tempted in 1 of less intuitive classes: // // dear maintainer: // // once done trying 'optimize' routine, // , have realized terrible mistake was, // please increment following counter warnin...

servlets - javascript dialogbox without opening page -

i have display dialog box servlet without opening new window. below code printwriter printwriter =response.getwriter(); string s ="<html><head><title>javascript example</title>"+ "<script language=javascript>"+ "alert('file uploaded');"+ "</script>"+ "</head>"+ "</html>"; printwriter.print(s); this code open dialog in new window want dialog in current window. it's hard understand problem. posted code isn't opening new window @ all, it's displaying alert dialog. if mean opening new window and displaying alert, problem rather lies in calling code. maybe have target="_blank" in link or form calling servlet? that said, generating view code in servlet isn't best practice. jsp should used that.

agile - How do you (developer) deal with unclear requirements and multiple acting POs? -

here's question trying figure out how scrum could/should work in real life. here typical scenario encounter: note: term "product owner" not used below. because true "product owner" - product manager in case - not make final decisions. db lead has final on many things decides how app interacts db. qa has own ideas on how things should / work - , ideas entered bugs , expected (by everyone) treated such. product manager writes story "x user needs page y". at sprint planning meeting story added sprint backlog. some poor developer grabs (or assigned) story. the developer asks product manager "what want page like". product manager (if available) says, "hmm, well, needs collect a, b, , c." developer starts working on best guess should like. developer tries hook page stored proc , asks db lead questions. db lead says "page needs d , e. , shouldn't need b". developer makes changes , commits it. qa says "i ...

c# - ASP.NET : Check for click event in page_load -

in c#, how can check see if link button has been clicked in page load method? i need know if clicked before click event fired. if( ispostback ) { // target of post-back, name of control // issued post-back string etarget = request.params["__eventtarget"].tostring(); }

multithreading - HTTP posts and multiple threads in Java -

i writing internal java applet file uploads via http. started using built in clienthttprequest worked great if want post 1 after another. when try have multiple threads post @ same time, on server side freaks out , connection hang large files while still uploading smaller files. (large seems around 10 megs) after lots of looking, not able find timeout set recover error, found clienthttp apache provide mechanism set timeout. problem while claims able work in multi-threaded program, 1 request after another. have found lots of example code httpclient says work multiple threads , have made adjustments code incorporate changes, none of them make difference, , still stuck 1 thread. while multiple threads not required release (httpclient seem bit faster clienthttprequest), nice speed boost since there lot of smaller files sent @ same time. the files being sent on http because want use same authentication of logged in user using session cookies. so looking either way set timeou...

sql server - How do you convert VARCHAR to TIMESTAMP in MSSQL? -

you'd call stored proc on ms sql has parameter type of timestamp within t-sql, not ado.net using varchar value (e.g. '0x0000000002c490c8'). what do? update: have "timestamp" value coming @ exists varchar. (think output variable on stored proc, it's fixed varchar, has value of timestamp). so, unless decide build dynamic sql, how can programmatically change value stored in varchar valid timestamp? a timestamp datatype managed sql server. i've never seen used anywhere other table column type. in capacity, column of type timestamp give rigorous ordinal of last insert/update on row in relation other updates in database. see recent ordinal across entire database, can retrieve value of @@dbts or rowversion(). per http://msdn.microsoft.com/en-us/library/ms182776(sql.90).aspx timestamp (transact-sql) is data type exposes automatically generated, unique binary numbers within database. timestamp used mechanism version-stamping table rows. s...

c - Program misbehaves 25% of the time -

inspired this topic , decided write simple program that. logic isn't complicated , have working program 75% of time.. amount of asked numbers defined #define bufsize x , x can arbitrary int. problem arises when ((bufsize+1) % sizeof(int)) == 0 . so example, if bufsize=10 , program behaves correctly, when bufsize=11 odd behaviour. here sourcecode: #include <stdio.h> #include <stdlib.h> #define bufsize 7 int max(int *buf); int main() { int bufsize = bufsize, *buf = malloc(sizeof(int[bufsize])); // read values int *ptr = buf; while(--bufsize + 1) { printf("input %d: ", bufsize - bufsize); scanf("%d", ptr); ++ptr; } // reset pointer , determine max ptr = buf; printf("\nmax: %d\n", max(ptr)); // cleanup free(buf); ptr = null; buf = null; exit(exit_success); } int max(int *buf) { int max = 0; while(*buf) { printf("%d\n...

In XML, what are the nodes with question marks called, and how do I add them in C#? -

here's example of xml file created in infopath: <?xml version="1.0" encoding="utf-8"?> <?mso-infopathsolution solutionversion="1.0.0.1" productversion="12.0.0" piversion="1.0.0.0" href="file:///c:\metastorm\sample%20procedures\infopath%20samples\template1.xsn" name="urn:schemas-microsoft-com:office:infopath:template1:-myxsd-2010-07-21t14-21-13" ?> <?mso-application progid="infopath.document" versionprogid="infopath.document.2"?> <my:myfields xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myxsd/2010-07-21t14:21:13" xml:lang="en-us"> <my:field1>hello</my:field1> <my:field2>world</my:field2> </my:myfields> what top 3 nodes question mark called... , how create them in c#? so far have this: xmldocument xmldoc; xmldeclaration xmldeclaration; xmldoc=new xmldocument(); xmldecl...

sql - Data Base design turnkey records -

i have questions regarding data base design simple cms. every page in table "pages" "assignedto" , "lockedby" specific user. manage users using sql specific table "aspnet_users", every user identified using gui uniqueidentifier column. if page "unlock" , can edited users, value in table "pages" null, same mechanism "assignedto". here script when create table "pages": lockedby uniqueidentifier null foreign key references aspnet_users(userid), assignedto uniqueidentifier null foreign key references aspnet_users(userid) my question: design generate many null values in "lockedby" since pages locked in moment of editing, because heard have many null values not thing in data base design,, know if design in practice, or if suggest better way. guys normally think it's idea have in 1 table, ignoring fact there's many null values, here's solution: you split 2 other table...

asp.net - Listbox values are persisting across postbacks -

i having listbox in asp.net. populating listbox values listbox in page dynamically. during postbacks values of output listbox not persisted. (while going page , come page). please suggest answer. enableviewstate = "true" not working. are doing in page_load should in if(!ispostback) {} initialization code in load needs called when page first loaded, not on postbacks. if going page , coming page, think need preserve information in session , restore when come page.

php - Matching a nonquoted string -

i'm trying work regexes in php on school's news site (running wordpress). idea is, whenever saves post, instances of "regis" (without 'jesuit' @ end) replaced "regis jesuit." (i go regis jesuit high school, , they're picky branding). overall works fine following case-insensitive regex: /regis(?! jesuit)/i how modify regex doesn't match if finds string "regis" or 'regis' (in single or double quotes)? (or "i go regis high school" quoted well)? idea here change necessary, keep same in direct quotes in people's stories don't change people's quotes. thanks! morgan based on comments question, perhaps solution stick current regex, use client-side javascript warning only. so, if text entered matches "regis" not followed " jesuit" before user submits displays message saying "make sure you've correctly branded us", doesn't automatically change - leaving l...

ruby on rails - How to change default path for images to look for -

by default, rails looking images "public/images" folder. but not suiteable me, since have multimedia stuff in "public/data/:model/:id" folders. how force rails folder. i don't need obligatory such pattern, mentioned above. thing, need, change "public/images" path "public/data", so, rails should "data" folder, instead of "images". i don't need use "paperclip" plugin, because models holding pure html content (with clean , simple structure, not change in future), has "img" tags. how can done ? you mean image_tag helper looking default there? that's case if specify relative path. putting full path in gets want believe. <%= image_tag '/data/model/1' would generate <img src="/data/model/1.png">

c++ - Dynamic vs non-dynamic class members -

in c++, ff have class needs hold member dynamically allocated , used pointer, or not, this: class { type a; }; or class { a(); ~a(); type* a; }; and in constructor: a::a { = new type(); } and destructor: a::~a { delete a; } are there advantages or disadvantages either one, aside dynamic 1 requiring more code? behave differently (aside pointer having dereferenced) or 1 slower other? 1 should use? there several differences: the size of every member must known when you're defining class. means must include type header, , can't use forward-declaration pointer member (since size of pointers known). has implications #include clutter , compile times large projects. the memory data member part of enclosing class instance, allocated @ same time, in same place, other class members (whether on stack or heap). has implications data locality - having in same place potentially lead better cache utilization, etc. stack allocation tad...

multithreading - Setting a thread priority in a service has no effect -

is there additional configuration needed before can set thread priorities in windows service? in service, have few threads each call createprocess() function launch external application. adjust thread (or process) priorities normal or lower , depending on other factors. the problem setthreadpriority() function fails error 6 (invalid handle?). i'm passing in handle obtained process_information::hthread (after calling createprocess() of course), think handle should valid. i've tried setting priority on processes using setpriorityclass() function, fails. the service logged on local user. maybe don't have correct access rights? msdn on setthreadpriority says: hthread [in] handle thread priority value set. the handle must have thread_set_information or thread_set_limited_information access right. more information, see thread security , access rights. windows server 2003 , windows xp/2000: handle must have thread_set_in...

How do you get log4net's SmtpPickupDirAppender to use the IIS pickup directory? -

due nature of live server deploy to, mail settings using deliverymethod="pickupdirectoryfromiis". i'm using log4net send logs via email , need find way of getting same thing. i can see docs there smtppickupdirappender, has pickupdir setting. if set whatever pickup directory iis uses, i'm sure work ok. want tell log4net use iis's setting , leave there. way if ever changes won't have change log4net config too, we're forget. there way this? afaik, that's not possible. although sounds idea. one of greatest things log4net can change configuration without having restart or recompile application (check faq ), don't need worry having downtime in logging. i don't know if can query iis smtp pick directory, maybe if possible can add background job queries iis information?

oracle - What could cause an ORA-00936 - Missing Expression with the following sql? -

we're seeing error message ora-00936 missing expression following sql: note cut-down version of bigger sql rewriting inner join or similar not in scope of this: this sql fails: select (select count(*) gt_roster ros_rosterplan_id = rpl_id) gt_rosterplan rpl_id = 432065061 what i've tried: * extracting innermost sql , substituting id outer sql gives me number 12. * aliasing both sub-query, , count(*) individually , both @ same time not change outcome (ie. still error) what else need at? the above tables, no views, rpl_id primary key of gt_rosterplan, , ros_rosterplan_id foreign key column, there no magic or hidden information here. edit: in response answer, no, not need aliases here columns uniquely named across tables. solved: problem client running wrong client driver version, 9.2.0.1, , there known problems version. that should work, assuming column names not ambiguous (and if lead different error). ran equivalent statement , got result with...

visual studio - Debugging across projects in VS2008? -

we have dll provides data layer several of our projects. typically when debugging or adding new feature library, run 1 of projects , step function call , continue debugging code in dll project. reason, no longer working since switched visual studio 2008... treats code other project dll has no visibility into, , reports exception whatever line crashes on. i can work around testing in dll's project itself, i'd able step in , see how things working "real" code used able do. any thoughts on might have happened? is pdb file dll in same directory dll? should work -- on regular basis. in modules window show whether it's managed load symbols dll. if hasn't won't able step functions in dll.

performance - Which performs better: Crystal Reports or SQL Server Reporting Services? -

which performs better: crystal reports or sql server reporting services? ssrs job of making reporting quick , easy. of microsoft's tools if stay within have decided should isn't problem. if try go outside box things become interesting , you'll wind having use pretty odd workarounds things work. crystal reports on otherhand more difficult learn gives greater flexability in can do. we have alot of our reports work in crystal reports , have decided convert them ssrs. taking while , we've found several things don't work way we'd ssrs has distinct advantage of being free sql server. crystal costs alot if have consider cost stick ssrs , learn quirks edit: performance can't tell of difference in render times crystal vs. ssrs reports.

javascript - How to load webpage after video completes -

i have image takes window, first frame of video clip , has "enter" button website. when click "enter" plays video , needs load home page. i have tried html5's video tag , 'onend' method, no luck. have tried 5 different open-source video players-none have scriptable 'onend' methods. have tried setting "timeout" function equal time of video...no luck. i in flash, has play on ipad. any appreciated. jase i believe event you're looking onended , not onend .

java - how to localise jcolorchooser -

as part of college project localising our application. is possible localise swing components such joptionpane , if how? you can use resourcebundle localization in general (in option pane case choise strings , messages) . can use localized strings etc joptionpane. example: string[] choises = new string[]; choises[0] = bundle.getstring("yes"); choises[1] = bundle.getstring("no"); choises[2] = bundle.getstring("cancel"); string message = bundle.getstring("messagetext") joptionpane optionpane = new joptionpane(message, joptionpane.warning_message, joptionpane.yes_no_cancel_option, null, choises); for more details resource bundles check out java internationalization: localization resourcebundles .

hibernate - Rich interaction in Java/JSP web app -

i'm writing website in jsp using struts , hibernate. i'm looking way implement rich ui can have more buttons. examples, drag , drops, drop down lists updates in real time type more letters out etc. there way use swing struts , hibernate? or there other options available making rich ui?? (i'm open abandon struts and/or hibernate if there better alternatives) fundamental problem: organization work have strict rules development tools , open source libraries can or cannot use, , pretty slow on updating approval list. none of ajax things (e.g. gwt, dojo) on list yet. thank taking time read post! first of all, use of struts , hibernate has no impact on interactivity of ui, because both of server-side technologies. unless can use technology gwt, openlaszlo or flex, way you`ll able achieve rich user interface writing in raw javascript. lot easier if can persuade organisation allow use javascript library such jquery or prototype.

c++ - Strange issue running infinite while loop in EXE -

i facing strange issue on windows ce: running 3 exes 1)first exe doing work every 8 minutes unless exit event signaled. 2)second exe doing work every 5 minutes unless exit event signaled. 3)third exe while loop running , in while loop work @ random times. while loop continues until exit event signaled. now exit event global event , can signaled process. the problem when run first exe works fine, run second exe works fine, run third exe works fine when run exes third exe runs , no instructions executed in first , second. as third exe gets terminated first , second starts processing. can case while loop in third exe taking cpu cycles? havn't tried putting sleep think can tricks. os should give cpu processes ... thoughts ??? put while loop in third exe sleep each time through loop , see happens. if doesn't fix particular probem, isn't ever practice poll while loop, , using sleep inside loop poor substitute proper timer.

dvcs - Does Mercurial support empty commit messages? -

is there way configure mercurial allow empty commit messages? if try hg commit through cli without entering commit message, commit canceled with: abort: empty commit message . now, know committing without message considered bad form, mercurial allow @ all? you can use space, i'd discourage it: hg commit -m " "

Where the deploy files goes for .NET Web Service running inside Visual Studio? -

when use browser test web service, opens @ http://localhost:4832/ -- can find files physically on drive? update i not want know files of vs.net solution located should put files of web service... .asmx, .dll , other files install real web service later. update 2 the webservice need call external dll when initializing plugin. why need know files go put manually plugin dll... so when launch webservice out of vs - cassini (the built in web server) runs files directly out of bin file of project. http://localhost:4832/ point folder code located in (as suggested alassek) , directly consume asmx file. asmx file run off of dll compiled bin folder.

.net - Fastest way to hash a set of GUIDs -

i have list of n guids , need hash them single value. value size of guid object or size of int32, doesn't matter, need statistically unique (say similar md5). so 1 approach sort them, concatenate bytes , take md5 hash of bytes... isn't quick. another idea: notice standard practice in .net implement gethashcode method of composing object xor of hash codes of composed objects. therefore mathematically sensible xor list of guids? any ideas welcome! if want hash valid set (i.e. order doesn't matter) xoring hashcode of each guid choice. if you've got sequence of guids , order matters i'd suggest using same approach wrote in answer - repeatedly add/multiply. (note xoring hashcodes won't same answer xoring guids , hashing result. may be, depends on implementation of guid.gethashcode(). i'd hash each value , xor results - aside else, that's trivial implement.)