Posts

Showing posts from January, 2011

c# - Order of events when switching Winform controls -

i have "leave" event on text box , "selectedvaluechanged" on list box. going text box list box, 1 fire before other? or, fire simultaneously? listbox.enter has fire before can see change in selected value. implies textbox.leave fires first. events can never fire simultaneously, these events run on ui thread, 1 @ time.

constructor - Storage allocation of local variables inside a block in c++ -

i want know @ point compiler allocates storage local variables inside block. how goto , switch jump past constructor? : class tree {/*...*/} ... void foo (int i){ if (i < 10) goto label; //illegal: cannot jump past ctor tree t (45); label: switch (i){ case 1: tree t2 (45); break; case 2: //illegal: cannot jump past ctor tree t3 (45); break; } } while above code not work user-defined objects works if replace them built-in objects. why that? edit: built in objects int, char, etc. errors (g++ 4.5 on ubuntu): jumppastconstructor.c++: in function ‘void foo(int)’: jumppastconstructor.c++:26:3: error: jump label ‘label’ jumppastconstructor.c++:24:20: error: here jumppastconstructor.c++:25:10: error: crosses initialization of ‘tree t’ jumppastconstructor.c++:31:16: error: jump case label jumppastconstructor.c++:29:25: error: crosses initialization of ‘tree t2’ 6.7/3: it possible transfer ...

c - Problem debugging a macro in visual studio -

i having trouble debugging macro in c. when try set breakpoint, message: "breakpoint not hit. no executable code associated line..." funny thing can debug else in file, not macro. have correctly loaded symbol files, cleaned , rebuilt, , turned off optimizations. ideas why debugging macro not working? not knowing enough context (it might helpful see definition, invocation , you're trying set breakpoint), here few guesses: are setting breakpoint in macro definition or called? if set in definition, error see. definition telling preprocessor substitutions elsewhere in code, time code reaches compiler, line #define on has been replaced blank line. if correctly setting breakpoint @ point it's used, sure you're using definition of macro think are, , macro isn't conditional compiled produce no code? common method of disabling things (e.g. debug output) , give no executable code on line calling (unless there other executable code around it). 1 way chec...

c# - JQuery bring expanded image to front -

hi working jquery expand image function , needed expanded image on front overlapping others somehow couldn't find way it, have tried place z-index on multiple locations no help, please kindly advice, thanks!: <style type="text/css"> .growimage {position:inherit ;width:80%;left:15px;top:15px; z-index:1;} .growdiv { left: 60px; top: 60px;width:130px;height:130px;position:inherit ; z-index:-1; } </style> <script type="text/javascript"> $(document).ready(function () { $('.growimage').mouseover(function () { $(this).stop().animate({ "width": "100%", "right": "10px", "top": "20px" }, 200, 'swing'); }).mouseout(function () { $(this).stop().animate({ "width": "80%", "right": "15px", "top": "15px" }, 400, 'swing');...

c - linking two shared libraries with some of the same symbols -

i trying link 2 different shared libraries. both libraries define symbols share name have different implementations. can't seem find way make each library use own implementation on other. for example, both libraries define global function bar() each calls internally. library 1 calls foo1() , library 2 calls foo2() . lib1.so: t bar t foo1() // calls bar() lib2.so: t bar t foo2() // calls bar() if link application against lib1.so , lib2.so bar implementation lib1.so called when calling foo2() . if on other hand, link application against lib2.so , lib1.so, bar called lib2.so. is there way make library prefer own implementation above other library? there several ways solve this: pass -bsymbolic or -bsymbolic-functions linker. has global effect: every reference global symbol (of function type -bsymbolic-functions ) can resolved symbol in library resolved symbol. lose ability interpose internal library calls symbols using ld_preload. the symbols ...

javascript - JQuery Animated Text -

it ridiculously hard find easy/simple animated text. "implosion" on website http://codecanyon.net/item/jquery-text-animation/full_screen_preview/233445 i'd have pay it. kind of simple onclick text fade in cool. suggestions, links, or help? its not hard create such effect using jquery. create single element vor every character, move somewhere , animate original position. a simple example: http://jsfiddle.net/doktormolle/dnxvx/

preg replace - PHP remove eveything between style="" tags? -

i interesting in removing in between , including inline style tags output. example: style="height:10px;" the issue have been having is, found php replacement expressions work, removing paragraph tags , such. any appreciated. thank you try: $html = preg_replace('%style="[^"]+"%i', '', $html);

ruby on rails - Why does ActiveResource Post not Send Any Parameters? -

i trying create new "user" in mongodb/sinatra server rails3 client using activeresource , json , object body or hash sent empty. in rails3, created "user" model , using rails console make activeresource call sinatra server. server correctly reads url, no parameters seem passed object. can please give me thoughts have missed or why not getting correct output? sinatra server uses ruby 1.8.7. rails3 client uses ruby 1.9.2. from rails3 client user model: class user < activeresource::base self.site = "http://127.0.0.1:9393/" self.collection_name = "user/add" self.format = :json end from rails3 console: u=user.new(:first_name=>"bill",:last_name=>"smith") => #<user:0xa8d7fac @attributes={"first_name"=>"bill", "last_name"=>"smith"}, @prefix_options={}> u.save => true the sinatra app server receives following object (which retrieve sinat...

php - Codeigniter omit where clause for empty criterion -

i have page browsing db records. viewer can filter records category, author, , tags. i'm using form instead of url segments filtering records (it feels more secure because can validate inputs.) for instance, when form inputs populated query looks this: select * (`posts`) `category` = 'technolgy' , `author` = 'lila' , `tags` = 'ebook' however if 1 input or more empty, no results. example: select * (`posts`) `category` = '' , `author` = 'lila' , `tags` = '' i want inputs optional example if author name entered, can return records made author regardless of category , tags. how can omit and where clause if empty? note: or_where clause not solution because doesn't return precise query if filter inputs filled. my model function filter($form_values) { $query = $this->db->get('posts'); $this->db->where($form_values); //adds clause array items...

c# - A point in 3D space from an angle -

i'm working on camera game. got stuck @ rotation. when move mouse across x- or y-axis, want camera rotate around character. what formula calculate vector, if distance character same? i doing in unity, c#, if of help. this function may help: transform.rotatearound(vector3 axis, float degree) can read unity script reference more info. -oh , think should tag next questions "unity3d" best unity3d-help @ unityanswers-forum http://answers.unity3d.com/index.html .

php - Is there a way to move/reset the search pointer in preg_match_all()? -

take following example, preg_match_all("/(^|-)[a-z]+(-|$)/i", "foo-bar-moo", $matches); this (correctly) returns following matches, foo- -moo however, need generate following matches output, foo- -bar- -moo is there way this? example moving search pointer 1 character after match? my other idea put in while() loop, removing matches on each loop, until matches found. thanks. edit : tried simplify issue make question clearer, in doing seem have misrepresented issue was. apologies. basically needed way match word in string character preceding or character following character, @ same time without capturing these leading , trailing characters in match. i under impression couldn't this, instead decided capture leading/trailing characters , remove them myself. led me issue above. as tim pietzcker pointed out, needed lookarounds . so example above, solution follows, preg_match_all('/(?<=^|-)[a-z]+(?=-|$)/', "foo-bar-moo...

sockets - Java Solaris NIO OP_CONNECT problem -

i have java client connects c++ server using tcp sockets using java nio. works under linux, aix , hp/ux under solaris op_connect event never fires. further details: selector.select() returning 0, , 'selected key set' empty. the issue occurs when connecting local machine (via loopback or ethernet interface), works when connecting remote machine. i have confirmed issue under 2 different solaris 10 machines; physical sparc , virtual x64 (vmware) using both jdk versions 1.6.0_21 , _26. here test code demonstrates issue: import java.io.ioexception; import java.net.inetsocketaddress; import java.nio.bytebuffer; import java.nio.channels.selectionkey; import java.nio.channels.selector; import java.nio.channels.socketchannel; import java.util.hashset; import java.util.iterator; import java.util.set; public class niotest3 { public static void main(string[] args) { int i, tcount = 1, open = 0; string[] addr = args[0].split(":"); ...

c# - Access and modify Console.Readline() programmatically -

in c# console.readline() implements history buffer of previous strings read through console. buffer can accessed arrows , down , f7 button. there way access , modify buffer programmatically within code? i'm pretty sure that's not part of console.readline() - that's native operating system. command window whether or not run console app. it may possible access input buffer, don't think you're going via standard clr objects. instead think you'll need use unsafe access win32 api (presuming you're on win32). this link talks console , it's available functions , properties via api that's can offer.

Dealing with larger traffic on ASP.net web site -

i have asp.net web site our company , handles 1000 - 2000 users every day. site have 4-5000 users every day. putting 2 servers , put them in hardware load balanced environment. i wondering if there else should asp.net web site perspective handle larger users. thanks. some things i'd take consideration.. session state management - going out-of-process? if so, make sure being stored in session serializable. do have large number (or any? may argue) update panels being used or many standard server-side postbacks? if so, try convert can simple ajax requests , marshal raw/json data , forth. minimize on number of full page life cycles , data traffic on server. on front-end/ui side, try leverage css sprites , go server images once , never again. for database connectivity, make sure leverage connection pooling . you may want consider js , css minification. additionally, these pages has tips: http://msdn.microsoft.com/en-us/magazine/cc163854.aspx (a bi...

wpf - Why does a format string that works in a Binding not work in a MultiBinding? -

i intrigued question: multibinding stringformat of timespan if have following binding defined starttime of type timespan: <textblock text={binding path=starttime, stringformat='{}from {0:hh\\:mm}'}" /> the above binding evaluates expected. however, scenario in original question shows, if try use same format string in multibinding, fails formatexception: <textblock> <textblock.text> <multibinding stringformat="{}from {0:hh\\:mm} {1:hh\\:mm}"> <binding path="starttime" /> <binding path="endtime" /> </multibinding> </textblock.text> </textblock> the question is, know why? bug or expected behavior? seems odd me same output in multibinding, have change "\:" ':' in format string (as discovered in answering original question). this appears bug in wpf 4, if not it's @ least breaking change wpf 3.5. take fol...

python - Is POS tagging deterministic? -

i have been trying wrap head around why happening hoping can shed light on this. trying tag following text: ae0.475 x mod ae0.842 x mod ae0.842 x mod ae0.775 x mod using following code: import nltk file = open("test", "r") line in file: words = line.strip().split(' ') words = [word.strip() word in words if word != ''] tags = nltk.pos_tag(words) pos = [tags[x][1] x in range(len(tags))] key = ' '.join(pos) print words, " : ", key and getting following result: ['ae0.475', 'x', 'mod'] : nn nnp nn ['ae0.842', 'x', 'mod'] : -none- nnp nn ['ae0.842', 'x', 'mod'] : -none- nnp nn ['ae0.775', 'x', 'mod'] : nn nnp nn and don't it. know reason inconsistency? not particular accuracy pos tagging because attempting extract templates seems using diffe...

jquery - making dynamic email input -

im trying make dynamic email input field uses autocomplete on input text field , places chosen receivers in span preceding input field. these 2 containers placed in div. div imitating input field, while span , input field not visible. i want make smooth in email software. making div box contain selected receivers , making sure empty input field not taking space. problem @ moment input field requires space , ends occupying last row of div. how can avoid this? here containers: <div class="message-userfield" ><span id="fake_to"></span><input type="text" name="auto" id="auto" /></div> i tried using jquery make width of input field smaller when not inputing data, input field doesn't "jump up" next span. how can make happen. $("#auto").focus(function(){ $(this).css({width:'200px'}); }); $("#auto").blur(function(){ $(this).css({widt...

c++ - How do I reverse set_value() and 'deactivate' a promise? -

i have total n00b question here on synchronization. have 'writer' thread assigns different value 'p' promise @ each iteration. need 'reader' threads wait shared_futures of value , process them, , question how use future/promise ensure reader threads wait new update of 'p' before performing processing task @ each iteration? many thanks. a promise / future pair designed carry single value (or exception.). you're describing, want adopt different tool. if wish have multiple threads (your readers) stop @ common point, might consider barrier .

regex - Regular expression and repeating character classes in perl -

i trying write regular expression can extract (possibly multiple) strings of 4 hexadecimal numbers/letters. i this: /^[a-fa-f0-9][a-fa-f0-9][a-fa-f0-9][a-fa-f0-9]/ but there better way? it seems repeat operator: a{n} matches 'a' repeated n times. a{n,} matches 'a' repeated n or more times. a{n, m} matches 'a' repeated between n , m times inclusive. would work, following regular expression not seem work: /^[a-fa-f0-9]{4}+/ i'm trying match strings like: aa00 aa00ffaa 0011ffaa0022 and on. each string on it's own line. thanks! try this: /^(?:[a-fa-f0-9]{4})+$/

Java - Store HashSet in mysql -

how go storing hashset unknown size in mysql table. know can loop through , store longtext field. however when retrieve field , store string temporarily use memory store huge string of info. is there easy way store hashset? a sql table indexed columns hash set. you shouldn't try store (persist) binary representation of hashset in table. should store (persist) data of hashset rows , columns , read data hashset on java side. in other words, should using database store data directly rather saving serialized representation of java collection holds data. that's database meant do... store/persist data in structured, consistent manner. if need serialize hashset why bother database @ all?

java - Eclipse "Build Automatically" not cascading -

Image
i have project in eclipse (indigo similar in helios) has files in src/main/resources processed generate *.java source files in target/generated-sources/xyz . project settings have "build automatically" enabled whenever these resource files edited , saved corresponding *.java files generated. i've added target/generated-sources/xyz projects build paths. works perfectly. the problem changes generated *.java files inconsistently rebuilt. if have 1 of files open in editor, notices changed , asks if want reload it. reloading *.java files enough recognize has changed , trigger rebuild. if don't have open doesn't automatically pick changes. any ideas on can let eclipse (indigo preferably) know these generated files being updated? or better yet tell monitor folders directly? thanks. try configuring eclipse automatically refresh. i'm not sure indigo, in helios, it's in preferences → general → workspace → refresh automatically. here in in...

ruby on rails - Help with Formtastic -

first of i'm no native speaker , begun rails 3 days ago. sorry mistakes. formtastic driving me crazy. have 3 tables: user, note, receiver: class user < activerecord::base has_many :receivers has_many :notes, :through => :receivers attr_accessible :id, :email, :password, :password_confirmation, :remember_me class note < activerecord::base has_many :receivers has_many :users, :through => :receivers attr_accessible :id, :text, :user_id accepts_nested_attributes_for :receivers class receiver < activerecord::base belongs_to :user belongs_to :note attr_accessible :user_id, :note_id, :note_attributes accepts_nested_attributes_for :user accepts_nested_attributes_for :note and here formtastic form: <%= semantic_form_for @note |form| %> <%= form.inputs %> <%= form.input :text %> <%= form.input :user_id, :as => :check_boxes, :collection => user.find(:all, :conditions => ["id != ?", current_user.id], :order => 'id...

Amazon EC2 -- Read Data From S3? -

i have many data files (let's call them input_files ) stored in amazon s3 . i start 15 independent amazon ec2 linux instances. these instances should load input_files (that stored in s3 ) , process them independently. i'd 15 independent amazon ec2 linux instances write the same output file . upon completion, output file saved in s3 . two questions: (1) possible amazon ec2 linux instances connect s3 , read data it? (2) how can arrange 15 independent amazon ec2 linux instances write same output file? can have file in s3 , , instances write it? (1) yes. can access s3 anywhere on internet using s3 public api (2) describing database seems. s3 file store, don't write files on s3 - save files s3. maybe should type of database instead.

php - How have foreach loop with this simplexml_load_string -

i parsing xml using simplexml_load_string : $xml = simplexml_load_string($response); echo '{'. '"date":"'.$xml->date[0].'",'. '"description":"'.$xml->shiptos->shipto->shippinggroups->shippinggroup->orderitems->orderitem->description[0].'",'. '"track":"'.$xml->shipments->shipment->track[0].'"'. '}'; this works ok if node appears in xml multiple times grabs once. can please me understand how write foreach loop description node? you referring 1 instance of each simplexmlobject . example $xml->date[0] refers first occurence of date object only. print date objects need loop through them foreach( $xml->date $date ){ print (string)$date; } alternatively, use children function: foreach( $xml->children('date') $date ){ print (string)...

Amazon API: How to find album title for mp3 downloads? -

i using amazon web services api allow search on website mp3 downloads. works, returning title, artist, price, , various other statistics, in results album name. on amazon's website, lists album names downloads ( example ) name exists somewhere. here arguments (signature , accesskey omitted): <argument name="operation" value="itemsearch"/> <argument name="service" value="awsecommerceservice"/> <argument name="count" value="20"/> <argument name="version" value="2010-11-01"/> <argument name="keywords" value="u2 joshua tree"/> <argument name="timestamp" value="2011-06-30t23:10:40z"/> <argument name="responsegroup" value="itemattributes,offers,images"/> <argument name="searchindex" value="mp3downloads"/> i tried adding relateditems responsegroup, , relationshiptype=author...

javascript - submitting when onchange event is triggered on an input element with type "file" -

i trying submit form using onchange event of input element type file problem empty form submitted instead though file chosen. here code: var form = document.createelement("form"); form.action="http://localhost:8084/upload/image"; form.method="post"; form.enctype ="multipart/form-data"; form.target="upload_target"; var input=document.createelement("input"); input.type="file"; input.accept="image/jpeg, image/gif, image/png"; input.onchange=function(ev){this.form.submit()}; form.appendchild(input); the form submits correctly when submit button clicked not when state of "file input" changed. is there way achieve trying do? are getting error? you have syntax error. line: input.onchange=function(ev){this.form.submit()); should be input.onchange=function(ev){this.form.submit()}; also, browser using, because technique hook event won't work in of them (like non-modern ie...

html - How to access web form programmatically? -

http://countrysize.com/ has 2 pulldown menus country names can selected. i trying make bash program automatically take screenshot of result given 2 countries. i.e. don't want manually select 2 countries in browser, , take screenshot. goal complete set of country area comparison results. how programmatically this? if form on page uses method=get, , query parameters passed in url there url every pair. however, if case, see resulting url in browser. if form uses method=post, choices sent part of form submission , included in body of web request. there command line tools can call bash script send form submission of type. tools "curl" , "wget" can both this. however, page looks else going on. page requires javascript, , code actual work in javascript. normally, mean not script command line script. however... there few links on page comparisons: http://countrysize.com/?cou1=pk&cou2=sp = kenya : france http://countrysize.com/?cou1...

asp.net - Crystal Reports and strongly typed datasets yields empty report -

i converting asp.net app vs 2003 vs 2005 starting point. app uses crystal reports , binds using ado.net typed dataset (xsd). had change of crystal code work newer version of crystal. now, when run page, report generates, none of fields fill in. have seen lots of people having same problem no real solutions out there. decided create fresh project same thing remove conversation vs 2003 2005 possible cause of problem. sample program has button runs query, fills dataset , assigns report. report displays headers only. code below. have no idea try next. dataset1 ds = new dataset1(); sqlconnection conn = new sqlconnection(configurationmanager.connectionstrings["myconnectionstring"].connectionstring); sqldataadapter da = new sqldataadapter("select * mytable", conn); da.fill(ds); reportdocument rep = new reportdocument(); rep.load(server.mappath("crystalreport.rpt")); rep.setdatasource(ds); crystalreportvie...

DynamicPDF api to render PDF forms in Java -

i have pdf forms , used adobe acrobat pro version 9 add hidden fields, buttons , validation in javascript it. also using dynamicpdf api (first time) in java read pdf , pre-populate few fields values (eg date current date , url fields) , drawing byte array , sending render. but while rendering dynamic pdf messing forms. not showing buttons added using adobe. buttons displayed no label on , if click shows * on it. don't know why. i using dynamic pdf replacement fdf merge. want same functionality dynamicpdf , total beginner both apis. any suggestion? this helper class write , pdf--- public class pdfmerge { private mergedocument document = null; public pdfmerge(file template) throws exception { if (templatepdffile == null) { throw new exception( ); document = new mergedocument(template.getabsolutepath(), new mergeoptions(true)); } } public mergedocument mergepdf(string pdfformid, string ...

bit manipulation - PHP - converting bitmask -

say assign following fruits: array ('1' => 'apple', '2' => 'banana', '4' => 'grape', '8' => 'orange') if wanted represent apple , banana , following: 0001 or 0010 0011 (or 3), right? given number 3 , how convert 1 , 2 ? all keys loaded $keys : $keys = array(); $value = 3; foreach ($arr $key => $val) { if ($value & $key) { $keys[] = $key; } }

python - Can webpy form work well with jinja2? -

as cookbook of webpy , jinja2, can use webpy's form or jinja2 independently. when try combining both in template file below, not work: template file: $def with(form) {% extends 'layout.html' %} {% block maincontents %} <h1>user</h1> <form method="post"> $:form.render() </form> {% endblock %} part of python code: render = render_jinja( 'templates', encoding='utf-8', ) class test: def post(self): pass def get(self): f = user_form() return render.test(f) $:form.render() templetor rendering instruction, taken verbatim docs, presume. i believe should use jinja2 syntax, like <form method="post"> {{ form.render() | safe }} </form> disclaimer: haven't tested snippet above.

asp.net - how to bind the data in gridview amount format 123,456.00? -

i have problem when binding data in gridview. attempting display amount field in usa format 123,456.00. how go data binding? the code have far is: <asp:templatefield headertext="amount"> <itemtemplate> <asp:label id="lblamount" runat="server" text='<%# eval("amount") %>'> </asp:label> </itemtemplate> <itemstyle horizontalalign="right" verticalalign="middle" /> </asp:templatefield> <asp:boundcolumn datafield="price" headertext="tax" dataformatstring="{0:c}">

php - what's wrong with this single PDO? -

here thing, other pdo works well, 1 doesn't. have tried execute(array(':t'=>$table)); with no success. ideas?. public function __construct($table){ try{ $pdocnx = new pdo("mysql:host=localhost;dbname=sigcat",'root',''); $stmt = $pdocnx->prepare('select * sigcat.:t'); $stmt->bindparam(':t', urldecode($table), pdo::param_str,45); $stmt->execute(); $row = $stmt->fetchall(pdo::fetch_assoc); var_dump($row); }catch(exception $e){ echo $e->getmessage(); } } i got many records in 'supplies' returns array(0) { }. i'm getting 'table' parameter $_get['table']. no exceptions though. you can't bind table names, values. maintain list of valid names , ensure string present in valid list. if can't build list of valid names, doing wro...

c# - DataGridView with ContextMenu assigned to column and a MessageBox -

i have dgv has datasource set bindinglist. there contextmenu assigned column in dgv. there menuitem set on contextmenu calls messagebox on click event. everything works fine , methods called , messagebox yesno responses susppose to. the problem having when messagebox's click event occurs (yes or no) it's job , goes away. if same routine called second time, again it's job no problem, reappears. if click yes or no goes away. if call third time messagebox appears again job , reappears twice. if everytime it's being called iterating , calling again amount of times. occur everytime it's called. the bindinglist built using class nested properties , data elements present. i tried using blank messagebox no dialogresults , no change. tried using dgv's raiselistchangedevents=false in contextmenu click event , dgv's cell enter click event. i've stepped through code , and no matter class nested properties gets called , causes contextmenu's click ev...

ruby - Sinatra and DataMapper Association -

i want make blog application in sinatra , datamapper, main application file this. %w[rubygems sinatra data_mapper].each{ |r| require r } datamapper.setup(:default , env['database_url'] || "sqlite3://#{dir.pwd}/development.db") class post include datamapper::resource property :id, serial property :title, string property :author, string property :body, text has n, :comments end class comment include datamapper::resource property :id, serial property :post_id, serial property :name, string property :body, text belongs_to :post end helpers def admin? request.cookies[settings.username] == settings.token end def protected! halt [401, 'not authorized'] unless admin? end end post '/comment/create' comment = comment.new(:name => params[:name], :body => params[:body]) if comment.save status 201 redirect '/post/'+post.id.to_s else status 412 redirect ...

asp.net - page numbers are too far in GridView -

Image
i trying change distance between pager numbers appearing in gridview. using css file in order control style of grid. .gridviewpager td { color: white; text-decoration: none; text-align:justify right; } .gridviewpager td a:hover { color: white; text-decoration: underline; text-align:justify right; } .gridviewpager span { text-autospace:none; color: black; text-align:justify right; } add following .gridviewpager td a: display: block; padding: 2px 5px; that give 2px on top , bottom, , 5px on either side of element.

How to get the screen DPI in java? -

i developing app need screen dpi.. checked few forums , got code snippet goes follows: dimension screen = java.awt.toolkit.getdefaulttoolkit().getscreensize(); system.out.println("screen width: "+screen.getwidth()); system.out.println("screen height: "+screen.getheight()); int pixelperinch=java.awt.toolkit.getdefaulttoolkit().getscreenresolution(); system.out.println("pixelperinch: "+pixelperinch); double height=screen.getheight()/pixelperinch; double width=screen.getwidth()/pixelperinch; double x=math.pow(height,2); double y=math.pow(width,2); but whatever value of screen resolution, pixelperinch value remains same @ 96. problem code?? i got swt code same thing goes follows: import org.eclipse.swt.graphics.device; import org.eclipse.swt.widgets.display; import org.eclipse.swt.widgets.shell; public class mainclass { public void run() { display display = new display(); shell shell = new shell(display); shell.settext(...

bitbucket - Cleaning up a mercurial repository for an external contractor -

i have active project sensitive files , directories. want hire external contractor simple ui work. however, don't want contractor have access directories , files. project in mercurial on bitbucket. what best way clean project , give him access commit changes? thought forking new repository, worried removing directories don't want him have access to. how remove them don't appear original changesets? how merge repo without removing directories in main repository? fork way go? naturally repository needs access whole history in order self-check integrity. don't know of way selectively hide parts of repository (there's acl extension , write access only). in case, would create new repository sensitive information has been stripped off (use convert extension task). then let external guy work repository. once work finsihed, pull repository clone of original 1 (using -f force pulling of unrelated repository), and rebase first changeset , ch...

.net - Print thread stack of all threads of a process -

i have .net application button. when click button want application print thread stack of threads debug console. is possible it? datte. you can use stacktrace class ( system.diagnostics ) stack trace of thread . you'd need enumerate threads, , (unfortunately) suspend them first, though. here's constructor of interest: http://msdn.microsoft.com/en-us/library/t2k35tat.aspx you may need create own threadpool implementation, or extend else's. far can see/tell there's no way enumerate them.

xna - Custom ContentPipeline with Browse facility -

i'm writing custom contentpipeline , i've added normal , specular map properties. compiles fine , works expected. i'd have normal , specular properties "browsable" when user clicks in box. currently, user has type name of normal or specular file , i'd like font property. when user clicks in font property has box 3 . s. how feature? possible? you want how customize property grid control: http://msdn.microsoft.com/en-us/library/aa302326.aspx#usingpropgrid_topic5 in particular, @ part deals type converters , how customize property grid editor property.

java - Pause ScheduledExecutorService -

i using scheduledexecutorservice execute task calls service @ fixed rate. service may return data task. task stores data in queue. other threads pick items queue import java.util.concurrent.blockingqueue; import java.util.concurrent.linkedblockingqueue; import java.util.concurrent.scheduledexecutorservice; import java.util.concurrent.timeunit; public class everlastingthread implements runnable { private scheduledexecutorservice executorservice; private int time; private timeunit timeunit; private blockingqueue<string> queue = new linkedblockingqueue<string>(500); public everlastingthread(scheduledexecutorservice executorservice, int time, timeunit timeunit) { this.executorservice = executorservice; this.time = time; this.timeunit = timeunit; } public void run() { // call service. if service returns data put queue queue.add("task"); } public void callservice() throws exception ...

asp.net - How to fetch and show image path from database into file upload control -

i have saved images using file upload control in asp.net want fetch path database , display file upload control please me out you have display image in image control using server.mappath("~/somedir/image.jpg")

delphi - How to update the VirtualStringTree scrollbars? -

i having hardtime fix problem on virtualstringtree. i have nodedata has having same node.nodeheight or defaultnodeheight, problem im going change each of nodeheight different size result virtualstringtree did not give me correct scrolling causing other node cannot seen. anyone help? thats because vt won't know total height of tree until nodes initialized (theyr height becomes known). 1 option force nodes initialized. thats of course against "virtual paradigm" of th vt, if have small number of nodes it's not bad. option set defaultnodeheight maximum nodeheight going use (if know beforehand) vt assume uninitialized nodes of height.

Stating CONSTANT values in a Ruby on Rails application -

i using ruby on rails 3.0.7 , state somewhere constant values accessible classes in application. use mentioned constants mostly "global" validation purposes considering use implement authorization system. where , how have state these constants? advice about? why dont u create .rb file in config/initilizers directory and define constants there. ps:-- need restart server access variables.

Best storage and retrieval practices for comments in PHP/MYSQL -

i'm having bit of problem when comes database , query design. here i'd have (honestly, lot stack overflow).: an item has many posts. a post has many comments. comments can flagged, liked, , disliked. comments cannot have subcomments. the table structure follows: items ----- iid desc ... posts ----- pid iid uid date desc ... comments ----- cid pid uid date desc ... the logic of is: posts item -> each post, comments. best in 1 query? best 1 query posts separate query each set of comments on each post? if 1 query, i'll potentially have 100 row behemoth i'll have ton of duplicate data. if separate call each post, i'll have far many queries. adivce? i imagine system going have 3 distinctive views , structure follows: a list of items - showing item description , number of posts attached item. e.g. select i.desc, ...., count(p.pid) items left join posts p on i.iid = p.iid group i.iid order i.date desc a list of posts selected item - sho...

numpy - matplotlib boxplot color -

Image
i'm trying create box & whisker plot of set of data binning y versus x. found useful example in making binned boxplot in matplotlib numpy , scipy in python . question simple. how can specify color of boxes in matplotlib.pyplot.boxplot set transparent in order let reader see original data. know there exists example shown in http://matplotlib.sourceforge.net/examples/pylab_examples/boxplot_demo2.html simpler this? looks strange impossibility set color of boxes directly in boxplot thank in advance you render original data scatter plot behind boxplot , hide fliers of boxplot. import pylab import numpy pylab.figure() data = [numpy.random.normal(i, size=50) in xrange(5)] x, y in enumerate(data): pylab.scatter([x + 1 in xrange(50)], y, alpha=0.5, edgecolors='r', marker='+') bp = pylab.boxplot(data) pylab.setp(bp['boxes'], color='black') pylab.setp(bp['whiskers'], color='black') pylab.setp(bp['fliers'], mar...

php - Make friendly url in zend framework -

i have built site on zend-framework 1.9.7. want make friendly url every page has url similar : http://mysite/search/detail/id/124 i want friendly url like: http://mysite/search/detail/ram where "ram" name of user has id=124 i have include rewriterule ^name/(.*)/$ guid/$1 in .htaccess file, doesn't work. i suggest take @ zend controller quickstart walks through steps of setting standard routing (which provides nice urls). if want more detailed info on routing, suggest take @ zend_controller_router's manual . specifically handle case through router route, example: <?php $router = zend_controller_front::getinstance()->getrouter(); $detailsroute = new zend_controller_router_route("search/detail/:name", array( 'controller' => 'search', 'action' => 'detail' )); $router->addroute('searchdetail', $detailsroute); the part :name parameter gets filled value ram of desired url...

silverlight - Windows phone 7 How to create events to update UI -

hi i'm making app when launches makes httpwebrequest, receives xml , puts in list. code in application_launching method in app.xaml.cs . list used in listpicker on first page of app. however because httpwebrequest executes on different thread list not populated when assign to listpickers itemsource. i've been told should have event fires after list full , listener on first page populate list when happens. how declare event , listener? you can use httpwebrequest , make asynccallback or use webclient class has event downloadstringcompleted. an example .

ruby - Modelling Company and Person Customers in Rails -

my rails application uses sti have different types of companies , persons. example have suppliers, manufacturers , customers types of company. have employees, contacts , customers types of people. now want refer customer can either company customer or person customer. method can use/should use combine these 2 different entities one? can refer customer, order? you either use: order belongs_to :company belongs_to :person end and have 2 foreign keys - , add validations make sure 1 of them filled in, , maybe add 'customer' method returns either related company or person, depending used. or, create separate customer model (and table), has 2 same 2 foreign keys, , order can belong_to :customer . second method may preferably if want store additional data @ customer level (such credit limit, or billing details), , may cleaner long-term. alternative, reconsider business logic, , insist orders belongs person, if person employee of company , purchasing o...

java - Which kind of test for which part of the software? -

i new tdd , want know kind oft test need part of software. currently team creates relative complex editor on netbeans platform, have integrate external editor , write own stuff. how can tests best gui, own code, integration code? create coded tests , should use test cases , testers? we considering use scala specs or junit coded tests. thank help! as general rule should consider writing test case every function/method write in class. in our tdd process follow rule every java class must have corresponding junit class contains @test method every method of java class. follow 'code coverage' tell how of code have written has been tested. suggest looking @ tool called cobertura ( link here ) provide easy visual way examine percentage of our code has been tested. works detecting how many line of code junit class has tested every java class. provide idea functionality in code has or has not been tested. aim have 80% of code tested (easier said done though) consi...

javascript - JS Looped appendChild producing strange behaviour -

i have function: //add links called classes function addlinks () { var classelements = []; var idelements = []; var finalrender; var expand = document.createtextnode("+"); var contract = document.createtextnode("-"); var elementslist = []; var count = 0; //create dom nodes renderpelements = document.createelement ("p"); renderaelements = document.createelement ("a"); renderaelements.setattribute("href", "#"); renderaelements.setattribute("class", "expander"); renderaelements.appendchild(expand); finalrender = renderpelements.appendchild(renderaelements); //get arrays of elements class or id set provided string (var = 0; i< show_hide_class_selectors.length; i++) { classelements[i] = document.getelementsbyclassname(show_hide_class_selectors[i]); //if prevents null value appearing in array , freezi...

iphone - Adding UIImageView or UIView to the cell of the grouped table -

i having problem setting uiimageview or uiview on cell of grouped table on iphone. for using code - (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath { static nsstring *simpletableidentifier = @"simpletableidentifier"; nsarray *listdata =[self.tablecontents objectforkey:[self.sotrekeys objectatindex:[indexpath section]]]; uitableviewcell * cell = [tableview dequeuereusablecellwithidentifier:simpletableidentifier]; if(cell == nil) { cell = [[[uitableviewcell alloc] initwithstyle:uitableviewcellstyledefault reuseidentifier:simpletableidentifier] autorelease]; } if(indexpath.section == 1 && indexpath.row ==1) { uiimageview *imageview = [[uiimageview alloc] initwithframe:cgrectmake(240, 14, 40, 40)]; imageview.image = [uiimage imagenamed:[nsstring stringwithformat:@"back.png",nil]]; ...