Posts

Showing posts from June, 2015

refactoring - How to refactor singleton methods in Ruby? -

currently have code following (simplified somewhat). eventually, i've added more , more new classes d1/d2, , think it's time refactoring make more elegant. goal of course make adding new class dx use little duplicate code possible. @ least, duplicate parts of calling fileimporter.import inside singleton method dx.import should factored out. module fileimporter def self.import(main_window, viewers) ... importer = yield file # delegate d1/d2 preparing importer object ... end end class d1 def self.import(main_window) viewers = [:v11, ] # d1 specific viewers fileimporter.import(main_window, viewers) |file| importer = self.new(file) ... # d1 specific handling of importer return importer end end end class d2 def self.import(main_window) viewers = [:v21,:v22, ] # d2 specific viewers fileimporter.import(main_window, viewers) |file| importer = self.new(file) ... # d2 specific handling of importer ...

C# : WPF Mouse Over -

i need create wpf application , contains 2 windows.. window1 contains button. need show second window when cursor on button in first window [ tooltip ] . if mouse leaves, second window should close.. i'm new wpf. can 1 me sample code if possible without second window done in tooltip, has behaviour. (e.g. http://www.c-sharpcorner.com/uploadfile/mahesh/fancywpftooltip07132008214937pm/fancywpftooltip.aspx )

asp.net - Retrieve SelectedItems from a RadGrid -

i have radgrid telerik gridclientselectcolumn column. when user checks records , clicks action button selecteditems empty. is there way retrieve selecteditems? the selected items should there unless call rebind() grid explicitly outer control. tested on modified version of this sample , worked no issues.

math - WPF 3D - rotate a model around it's own axes -

suppose have simple wpf 3d scene set single rectangle rotated -45 degrees around x axis so: <viewport3d> <viewport3d.camera> <perspectivecamera position="0,0,4"/> </viewport3d.camera> <modelvisual3d> <modelvisual3d.content> <directionallight color="white" direction="-1,-1,-3" /> </modelvisual3d.content> </modelvisual3d> <modelvisual3d> <modelvisual3d.content> <geometrymodel3d> <geometrymodel3d.geometry> <meshgeometry3d positions="-1,-1,0 1,-1,0 -1,1,0 1,1,0" triangleindices="0,1,2 1,3,2"/> </geometrymodel3d.geometry> <geometrymodel3d.material> <diffusematerial brush="red"/> </geometrymodel3d.material...

prototypejs - Prototype $$ returns array, should return one element like $ -

when using dollar-dollar-function in prototype alway array of elements back, instead of 1 element dollar-function. how can combine power of css-selectors of $$ still 1 element back? changing structure of source not possible, can't select id. needs selected css, should return 1 element. it not make sense return single element when selecting class name because potentially there many elements in dom have class. use first element of returned array if sure unique. $$('.foo')[0]

c# - Problem Converting ipv6 to ipv4 -

i have code in asp.net app needsto ipv4 address of client computer (the users on our own network). upgraded server app runs on windows 2008 server. request.userhostaddress code returns ipv4 when client on older os , ipv6 when on newer os (vista , higher). feature relys on works clients , not others. i added code supposed convert ipv6 ipv4 try fix problem. it's online tutorial: http://www.4guysfromrolla.com/articles/071807-1.aspx .i'm using dsn.gethostaddress , looping through ips returned looking 1 "internetwork" foreach (ipaddress ipa in dns.gethostaddresses(httpcontext.current.request.userhostaddress)) { if (ipa.addressfamily.tostring() == "internetwork") { ip4address = ipa.tostring(); break; } } if (ip4address != string.empty) { return ip4address; } foreach (ipaddress ipa in dns.gethostaddresses(dns.gethostname())) { if (ipa.addressfamily.tostring() == "internetwork") { ip4address = ipa...

Use interface or type for variable definition in java? -

arraylist alist = new arraylist(); list alist = new arraylist(); what's difference between these 2 , better use , why? list<t> interface, arraylist<t> class, , class implements list<t> interface. i prefer 2nd form, more general, ie if not use methods specific arraylist<t> can declare type interface list<t> type. 2nd form easier change implementation arraylist<t> other class implements list<t> interface. edit: many of users commented both forms can arguments method accept list<t> or arrraylist<t> . when declare method prefer interface: void showall(list <string> sl) ... and use: void showallas(arraylist <string> sl) ... only when method uses method specific arraylist<t> , ensurecapacity() . response information should use typed list<t> instead of list (of course if not use ancient java).

SQL Server 2008 - use cmd to output with headers to .csv -

i have pretty simple question (and these typically ones spend of time tearing hair out about). using batch file execute .sql queries in same directory batch, , save results various .csv file. here code: @echo off rem check parameters present @if "%1"=="" goto error @if "%2"=="" goto error @if "%3"=="" goto error @if "%4"=="" goto error rem every *.sql file in folder "." , subfolders (/r), following: @for /r "." %%f in (*.sql) ( rem print command executed: @echo database : @sqlcmd -s %1 -u %2 -p %3 -d %4 -i -l60 -i "%%f" -o "%%f.output.csv" -h-1 -s"," -w 1000 -w rem execute command: @sqlcmd -s %1 -u %2 -p %3 -d %4 -i -l60 -i "%%f" -o "%%f.output.csv" -h-1 -s"," -w 1000 -w ) goto :eof :error @echo incorrect syntax : @echo extract.cmd [servername] [user id] [password] [databasename] @echo @pause goto :eof ...

c# - Hiding forms on startup: why doesn't this.Hide() hide my form? -

i wanted hide main window of app on startup, put in constructor: this.hide(); this doesn't hide form though. seems can buttons hide form. doing wrong here? you can use line of code. wont hide it, minimized: this.windowstate = formwindowstate.minimized; in addition, if don't want showing on task bar either, can add line: this.showintaskbar = false; but why create form if don't want visible in first place?

java - Why can't I use a String array with a method taking an Iterable as a parameter? -

i'm trying write own "functional" little lib in java. if have function : public static <t> list<t> filter(iterable<t> source,booleantest predicate) { list<t> results = new arraylist<t>(); for(t t : source) { if(predicate.ok(t)) results.add(t); } return results; } why can't use snippet: string strings[] = {"one","two","three"}; list<string> containingo = iterablefuncs.filter(strings,new booleantest() { public boolean ok(string obj) { return obj.indexof("o") != -1; } }); as far know, java array implements iterable, right? needs changed make function work arrays, collections? choosing iterable first parameter, figured got cases covered. i agree, it's annoying. you overload filter() thusly... public static <t> list<t> filter(t[] source, booleantest predicate) { return filter(arrays.aslist(source), pred...

php - MySQL Query for displaying all rows of one table with yes/no if matching other table? -

i apologize in advance non technincal description on problem! i have 2 tables: usersoptions , optionslist.. for simplicity sake, optionslist below: id - name 1 - red 2 - blue 3 - orange usersoptions has many rows eg; id - client - option 1 - john - red 2 - john - orange 3 - mary - red 4 - jill - blue 5 - jill - orange etc.. is there query can run give me following output? (yes/no not essential) john's output: option - yes/no red - y blue - n orange - y mary's output: option - yes/no red - y blue - n orange - n this driving me crazy! can help! you can use case statement exists sub-query: select name, case when exists (select id usersoptions client = 'john' , `option` = optionslist.name) 'y' else 'n' end `yes/no` optionslist

Mixing Assert and Act in AAA unit testing syntax -

is ok mix assert , act steps? aaa more of guideline rule? or missing something? here test: [testmethod] public void cancelbuttonselected_dontcanceltwicethencancel_dialogcloses() { // arrange iaddaddressform form = substitute.for<iaddaddressform>(); // indicate when show cancelmessage called // should return cancel twice (saying want cancel cancel) // should return ok form.showcancelmessage().returns(dialogresult.cancel, dialogresult.cancel, dialogresult.ok); addaddresscontroller controller = new addaddresscontroller(form); addressitem item = testhelper.createaddressbob(); // act enteraddressinfo(form, controller, item); controller.cancelbuttonselected(); assert.istrue(form.dialogresult == dialogresult.none); controller.cancelbuttonselected(); assert.istrue(form.dialogresult == dialogresult.none); controller.cancelbuttonselected(); // assert assert.istrue(form.dialogresult == dialogresu...

WPF - Build a string of pressed keys using KeyDown in ListView -

i have listview dozen of rows binded xml. i'd have possibility locate , position cursor record. example: have these id, name, value: 1, johny, cash, usa 2, jean-michel, jarre, france 3, jeanette, , usa when type "je", selectedrow positioned id 2. when type "jeane", selectedrow positioned id 3. i'd have possibility search , go proper record in listview. started building searchstring , @ point got stuck: the 1 , possibility in wpf use keydown event. unfortunately, event return kind of key, not able convert string. e.g. when press "a", searchstring "a". when continue typing "b", searchstring "ab" etc. when selecteditem changes, searchstring set string.empty. no keycode or other useful property/method available. and here comes head rubbing. how can build searchstring need? when tried e.key.tostring(), got funny strings - e.g. 0 on numpad key "numpad0", "," "oemcomma" etc. trying t...

c++ - Converting: #define xxxxxx ((LPCSTR) 4) -

in wincrypt.h see: #define cert_chain_policy_ssl ((lpcstr) 4) wincrypt32api bool winapi certverifycertificatechainpolicy( in lpcstr pszpolicyoid, in pccert_chain_context pchaincontext, in pcert_chain_policy_para ppolicypara, in out pcert_chain_policy_status ppolicystatus ); the first argument takes cert_chain_policy_ssl. appears pointer c string, yet integer!? the pointer 32bit integer, pointing at? if number < 255 take single byte, c string in fact single byte "string" (ie byte)? when conveting language support byte variables, can create bvar (a byte variable) , assign 4. can pass pointer byte variable? sometimes api take parameter can 'cookie' or id well-known object or pointer name (for example),which appears case here. 4 cookie/handle/id well-known cert_chain_policy_ssl policy. users of api might specify policy that's not known library ahead of time, specified name can somewhere (or registry, config file or ...

java generics and SuppressWarnings -

i have classes abstract class { //.... } class b extends { //.... } class c extends { //.... } then have interface maker<t extends a> { someclass make(t obj); } implementations maker class class makerforb implements maker<b> { /*... */ } class makerforc implements maker<c> { /*... */ } and class factory 1 static method class factory { public static someclass makesomeclass(a obj) { maker maker = null; if(obj instanceof b) maker = new makerforb(); /* ... */ return maker.make(obj); } } in case warning maker raw type, when declare maker way maker<?> maker = null; i exception (make not applicable arguments a) on return maker.make(obj); what best way rid of these warnings without using @suppresswarnings("unchecked") get rid of generics on maker - don't need it: interface maker { someclass make(a obj); } class makerforb implements maker { some...

getters and setters in php -

i have been coding in php , using codeigniter well, never got concept of getter , setter. mean ? class foo { protected $_bar; public function setbar($value) { $this->_bar = $value; } public function getbar() { return $this->_bar; } } the getter , setter here methods allow access protected property $_bar . idea not directly allow access property, control access through api client code consume. way can change underlying state, while leaving public facing methods is. thus, less break client if changes occur. another reason have them, when need add logic before or set property. instance, setter might validate , uppercase value public function setbar($value) { if(!is_string($value)) { throw new invalidargumentexception('expected string'); } $this->_bar = strtoupper($value); } or getter may lazy instantiate object public function getbar() { if($this->_bar === null) { $this->_...

c# - HttpWebResponse with MJPEG and multipart/x-mixed-replace; boundary=--myboundary response content type from security camera not working -

i have asp.net application need show video feed security camera. video feed has content type of 'multipart/x-mixed-replace; boundary=--myboundary' image data between boundaries. need assistance passing stream of data through page client side plugin have can consume stream if browsed camera's web interface directly. following code not work: //get response data byte[] data = htmlparser.getbytearrayfromstream(response.getresponsestream()); if (data != null) { httpcontext.current.response.outputstream.write(data, 0, data.length); } return; well, if want client see mjpeg stream, need send whole http response. http client browser or media player vlc need mjpeg stream looks : http/1.1 200 ok content-type: multipart/x-mixed-replace; boundary=myboundary --myboundary content-type: image/jpeg content-length: 12345 [image 1 encoded jpeg data] --myboundary content-type: image/jpeg content-length: 45678 [image 2 encoded jpeg data] ... note: ergousha said in an...

c# - How to ensure certain properties are always populated when returning object from DAL? -

i have question class has property optionlist , nothing list. questions , options stored in diff tables in db. now there times when need question object without relational properties, properties entities mapping different table in db. in case not need optionlist populated. but again there times when need optionlist property populated. the approach thinking of right having 2 different methods. public question getquestionbyid(int qid) public question getquestionwitoptions(int qid) so if call second metho, ensure optionlist populated in returned question object. is way achieve such result? alternate ideas , suggestions? i'd it's pretty method. you're using defined names obvious purpose , function. the other suggestion can think of create second class: public class questionextended : question { public questionextended(ienumerable<option> options) : base() { optionlist = new list<option>(options); } public list...

c# - How should I be using GridViews? -

recent problems i've had making me question whole philosophy , assumptions regarding gridviews. currently, have used along lines of following model. in markup: <asp:updatepanel id="pnlsearch" updatemode="conditional" runat="server"> <contenttemplate> <asp:textbox id="txtsearch" runat="server" ontextchanged="txtsearch_textchanged"></asp:textbox> </contenttemplate> </asp:updatepanel> <asp:updatepanel id="pnlgridview" updatemode="conditional" runat="server"> <contenttemplate> <asp:gridview id="gridview1" enableviewstate="false" allowpaging="true" pagesize="20" datasourceid="mydatasource" runat="server" autogeneratecolumns="false"> <columns> <asp:boundfield datafield="col_1...

android - ExpandableListView with buttons -

i'm considering ui change such: there list of items in expandablelistview. clicking on item expands 1 more item below it. item have own view contain number of things pertaining item expanded from. basically, imagine clicking on original list item , being taken new screen information on item. expanded item in new list screen. i know there troubles list items containing controls buttons , checkboxes , such. long list item controls resting on not clickable, should work, right? expanded item doesn't need clicking capabilities, parent item (so can expanded/closed!)

ruby on rails - Shoulda: unknown error with validates_each -

i'm having awful time trying understand validation method having trouble with. i installed shoulda , when tried use it errors out strange undefined method nomethoderror: undefined method '[]' false:falseclass odd. i narrowed down piece of offending code: validates_each :name |record, attr, value| name_hash = self.parse_name(value) record.errors.add attr, 'must have first , last name' if ( name_hash[:first_name].nil? || name_hash[:last_name].nil? ) end you can see full error, offending model (simplified), test case, , environment info @ gist-596202 any insight appreciated. your parse_name method starts line: return false unless name.is_a?(string) this indicate value not string (probably nil) when you're trying validate it. shoulda matcher validate_presence_of test nil value, why you're getting failure.

sql server 2008 - wait for transactional replication in ADO.NET or TSQL -

my web app uses ado.net against sql server 2008. database writes happen against primary (publisher) database, reads load balanced across primary , secondary (subscriber) database. use sql server's built-in transactional replication keep secondary up-to-date. of time, couple of seconds of latency not problem. however, have case i'd block until transaction committed @ secondary site. blocking few seconds ok, returning stale page user not. there way in ado.net or tsql specify want wait replication complete? or can i, publisher, check replication status of transaction without manually connecting secondary server. [edit] 99.9% of time, data in subscriber "fresh enough". there 1 operation invalidates it. can't read publisher every time on off chance it's become invalid. if can't solve problem under transactional replication, can suggest alternate architecture? there's no such solution sql server, here's how i've worked around in othe...

flash - Creating a .swc - why don't interfaces work, when classes do? -

i'm making game loads map .swfs @ runtime. maps contain graphics , code, can both vary map map. i've decided make maps implement interface, can used in same way game. i'm using .swc contain interface, in this page . i can classes work in .swc, not interfaces! i'm using flash cs5, , flashdevelop editing, in as3. here's how i've been doing it: 1- create map.fla symbol called map, , map.as: public class map extends movieclip { public function test():void { trace("woohoo"); } } 2- in flash, right click map symbol , choose "export swc..." , "export swf...". 3- create new .fla , flashdevelop project called loader in new folder, , copy in .swf , .swc created in 2 4- in flashdevelop, right click swc , choose "add library" 5- in flash, actionscript settings -> lirbary path, add swc , set link type: external now in loader.as can access map class after loading in map.swf: public class loader...

regex - Escaping a Ruby String for TextMate's $DIALOG command -

calling regex gurus. i'm having trouble right escaping string in ruby can pass command line utility using exec , %x{} or similar. command line command textmate dialog feature, works (run shell script in textmate.): $dialog -mp "items=('string1','string2', 'string3');" requestitem but can use nib file specify "path/to/my/nib/file.nib" so, need pass whole command string exec command = <<string $dialog -mp "items=('string1','string2', 'string3');" "path/to/my/nib/file.nib" string exec command this works fine naturally. problem running components of items array determined programmatically, need programmatically escape string in way pass $dialog command properly. so far, have determined need escape single quotes, double quotes, , newline , tab characters. i've tried ton of potential regular expression solutions haven't yet been able land on reliable escaping mechanism. b...

Asp.Net MVC Identify Site via Url -

i have application support multiple sites. site determined based on url. for example http://myapp/site/abc123/ ... , http://myapp/site/xyz123/ ... the site code drive lot of functionality example themes, available modules, etc... questions: 1-)i need validate site code valid , if isn't, should direct user info page. looking @ using irouteconstraint , appropriate? there other/better options? 2-)any gotchas approach (using url identify site)? there better approach? solution i ended creating custom actionfilter , check sitecode in onactionexecuting event. seems work , fit better irouteconstraint. the system have implemented uses urls identify unique page content within single site , routing process pretty straightforward. being said, may want consider making use of areas in mvc application. areas can have multiple sections website have own mvc structure can run semi-independently. essentially, have 1 base routing definition lays out defaults , rest of ...

asp.net mvc - How to render an action link with an image? -

i know use html.actionlink() render textual <a href..."> links actions. how render link action has underlying image link? <a href="foo"><img src="asdfasdf"/></a> here code imagelink htmlhelper extension use. /* * image link html helper */ /// <summary> /// return image link /// </summary> /// <param name="helper"></param> /// <param name="imageurl">url image</param> /// <param name="controller">target controller name</param> /// <param name="action">target action name</param> /// <param name="linktext">anchor text</param> public static string imagelink(this htmlhelper helper, string imageurl, string controller, string action, string linktext) { return imagelink(helper, null, controller, action, linktext, imageurl, null, null, null, null...

animation - Continually update and replace image with jQuery -

i have image update many times second. want able display updates fast can. have bit of code flickers , isn't good. plus limited updating twice second. want able display faster if possible. essentially creating crude video using jpeg stills. image files few k max , run locally - not on internet. i expect need kind of double buffering system unsure how in jquery. i'd need load image in background before switching it. cannot seem able tell when image has loaded. here code far <div id="vidcontent"> <img src="" width="255" height="255" id="vidimg" /> </div> <img src="title.png" id="title" /> <script type="text/javascript"> $(document).ready(function() { setinterval('loadimage();', 500 ); }); function loadimage() { var img_src = "http://10.1.9.12/web/data/vid_jpg0.jpg"; var img = $("...

load testing - Web Capacity Analysis Tool (WCAT) Tutorial -

i'm finding difficult find decent tutorials on how , running wcat quickly. have link decent tutorial on found useful when trying grips wcat? for me best thing used going wcat "sample" running, tied base iis installation single file. once got done, found documentation easy understand, initial setup tricky. otherwise, blog posting pretty straightforward well.

php - How to create object from String? -

i tried code below: $dyn = "new ". $classname . "(" .$param1 . ", ". $param2 . ");"; $obj = eval($dyn); it compiles it's null. how can instance object in php dynamicaly? $class = 'classname'; $obj = new $class($arg1, $arg2);

iphone - app's designed area -

this question has answer here: apps read or write data outside designated container area rejected 1 answer the apple guidelines say: apps read or write data outside designated container area rejected what designed container area? basically, means should not write or read data to/from other directory other own applcations directory. e.g. can update sqlite db of app own app unless there public api allows that

windows - Deleted file recovery program using C C++ -

i want write program can recover deleted files hard drive ( fat32/ntfs partition windows). don't know start from. should starting point of this? should read pursue this? required. system level structs should study? it's entirely matter of filesystem layout, how "file" looks on disk, , remains when file deleted. such, pretty need understand filesystem spec (for each , every filesystem want support), , how direct block-level access hd data. might possible reuse code existing filesystem drivers, need modified process structures that, point of view of filesystem, gone. ntfs technical reference ntfs.com fat32 spec

c# - jquery and ASP.Net AJAX framework -

i developing using vsts 2008 + c# + .net 3.5 + asp.net. new jquery , asp.net ajax framework. suppose need use jquery function (e.g. jquery-1.3.2.js). want confirm jquery , asp.net ajax framework totally 2 different things, no dependencies? so, no need install , configure asp.net ajax framework in order use jquery function? thanks in advance, george yes correct. don't need both function. can find information on ajax toolkit here . might find jqueryui quite useful. i'm quite new jquery , found jqueryui quite time saver. if want, can let google host jquery and/or jqueryui you, bandwidth doesn't taken ( info here) . add, if want intellisense jquery code, this blog shows how setup vs2008 so.

awt - How to display Java dialog using alternate event queue? -

i have code detects if java awt event queue frozen (busy processing event or waiting lock) excessive amount of time, due buggy foreign code fails use swingworker or similar, , want offer recover. killing event dispatch thread thread.stop works, hazardous (and eq might blocked because computer temporarily overloaded), prefer prompt user confirmation. displaying dialog requires waiting eq unblocked, not possible. is there way, reasonably portable java program, display dialog (or kind of ui element can respond input events) without involving normal event queue? i tried running systemtray.add(trayicon) , manage display tray item when called thread... icon not painted, , actionevent s not delivered, not helpful. it seems possible display new jframe , paint label on using paintimmediately , there still no apparent way receive mouse events. following tom hawtin's hint, tried create new appcontext . on jdk 6u18, dialog shown in new context seems paint correctly not receive m...

.net - Understanding CLR object size between 32 bit vs 64 bit -

i trying understand object size difference between 32 bit , 64 bit processors. let’s have simple class class myclass { int x; int y; } so on 32 bit machine, integer 4 bytes. if add syncblock ( 4 bytes), object size 12 bytes. why showing 16 bytes? 0:000> !do 0x029d8b98 name: consoleapplication1.program+myclass methodtable: 000e33b0 eeclass: 000e149c size: 16(0x10) bytes (c:\mytemp\consoleapplication1\consoleapplication1\bin\x86\debug\consoleapplication1.exe) fields: mt field offset type vt attr value name 71972d70 4000003 4 system.int32 1 instance 0 x 71972d70 4000004 8 system.int32 1 instance 0 y on 64 bit machine, integer still 4 bytes thing changed syncblock 8 bytes ( pointers 8 bytes on 64 bit machines). mean object size 16 bytes. why showing 24 bytes? 0:000> !do 0x00000000028f3c90 name: consoleapplication1.program+myclass methodtable...

cck - Drupal: how to rate node filefields? -

i have node type called 'movie' may contain several subtitle files using cck filefield module. i'm dealing fivestars module, need rate each subtitle separately! user should rate subtitles associated movie, not movie itself. confused enough! idea? this going tough 1 whole fivestars module isn't built rating nodes. (so rating fields out) you use " content multigroup " , allow pair file fields integer field. note content multigroup standalong module being integrated cck3 still in development. this, have attach javascript ratings tool (not drupal module persay) field on own i'm pretty sure fivestars designed work against nodes, not specific fields, less multigroup fields. so, if want stick using fivestars , it's designed (not rewriting work individual fields/multigroup), i'm pretty sure option split subtitles separate content type , associate using nodereference. give unfortunate side effect of having separate page reviewing. won...

html - Is there a specific order that HTTP tag attributes should be listed in? -

should attributes of particular html tag listed in specific order? there convention order? example, have following image tag in html strict page... <img src="http://example.com/media/graphics/border_bottom.png" class="border" height="5px" width="600px" alt="lower border" /> should src listed first, or height, or width, etc? proper order? thanks in advance! no there isn't, anyway should follow make own standard , follow it

iPhone: UITableView not refreshing -

i have read many topics uitableviews not refreshing on iphone, couldn't find matching situation, i'm asking help. in class, extends uiviewcontroller, have tableview , 'elementlist' (which wrapper nsmutablearray) used data source. a separate thread adds new element array via 'updatelist:' method. when happens, want tableview refreshed automatically, doesn't happen. by debugging app, can see 'cellforrowatindexpath' never called , can't figure out why. i tried add observer, calls 'reloadtableview' method (it called) tableview not updated. this code: #import <uikit/uikit.h> @interface listviewcontroller : uiviewcontroller <uitableviewdelegate, uitableviewdatasource> { uitableview *tableview; elementlist *elementlist; // wrapper nsmutablearray } // called else, triggers whole thing -(void)updatelist:(element *)element; // added out of desperation -(void)reloadtableview; @end @implementation listviewc...

php - What is the algorithm for parsing expressions in infix notation? -

i parse boolean expressions in php. in: a , b or c , (d or f or not g) the terms can considered simple identifiers. have little structure, parser doesn't need worry that. should recognize keywords and or not ( ) . else term. i remember wrote simple arithmetic expression evaluators @ school, don't remember how done anymore. nor know keywords in google/so. a ready made library nice, remember algorithm pretty simple might fun , educational re-implement myself. recursive descent parsers fun write , easy read . first step write grammar out. maybe grammar want. expr = and_expr ('or' and_expr)* and_expr = not_expr ('and' not_expr)* not_expr = simple_expr | 'not' not_expr simple_expr = term | '(' expr ')' turning recursive descent parser super easy. write 1 function per nonterminal. def expr(): x = and_expr() while peek() == 'or': consume('or') y = and_expr() ...

To pass a value on runtime from HTTPContext as response -

i trying pass value http handler module redirected response. planning change view respect value. //httpmodule if (!authorizer.isauthorized(controller, action, context.user)) { context.response.redirect(authorization_failure_url); } appaccess appaccess = appauth.getapplicationaccessstatus("app1", context.user.identity.name.tostring(), avlaccessmode, edit); // getting application access mode depending on appaccess , need pass value response httpcontext.current.response.cache.setcacheability(httpcacheability.nocache); httpcontext.current.response.cache.setexpires(datetime.now.addseconds(-1)); //httpmodule ends in view, passed value need change view. any idea in passing value http module view helpful. i tried this httpcontext.current.items.add("mode", "read"); i able set value in httpmodule , same can accessible view. worked. thanks.

iphone - What is autoresizesForKeyboard and how does it work? -

i trying find way adjust screen when keyboard slides text field being edited (uitextview in case) slides , stays in focus instead of getting hidden behind keyboard. i saw few discussion on google groups mentioning - autoresizesforkeyboard - http://groups.google.com/group/three20/browse_thread/thread/38bdadc89a1f35f8/2f8b92a6058cf136?lnk=raot&pli=1 i not able figure out how use or find documentation it. then saw how apple recommends - http://developer.apple.com/library/ios/#documentation/stringstextfonts/conceptual/textandwebiphoneos/keyboardmanagement/keyboardmanagement.html however autoresizesforkeyboard sounds intriguingly simple. can please shed light on this? autoresizesforkeyboard part of three20 library , property of ttviewcontroller class. http://api.three20.info/interface_t_t_view_controller.html#acc0ff2c5d115eb977aaac419cb64f62b "three20 iphone development library. it's code powers facebook iphone app , many other apps in app store."...

Calendar Class in Javascript - unable to keep the reference. -

i wrote datepicker in javascript, not working properly, as lose reference calendar object. here example http://asexpress.de/calendar/ by clicking within input field calendar displayed. what should reference calendar object remains in contact. from can tell far of script, following code block: kalender.prototype.writemonth = function() { var = this; contains code further down: else if ( this.istoday(displaynum, length) && this.islink(displaynum, length) ) { sbuffer.push('<td class="date" onclick="that.changedate(this,\'' + this.id + '\'); that.returndate('+ this.month +','+ this.year+')">' + displaynum + '</td>'); } this cause problem, since that variable declared within scope of function , onclick event fire outside of scope. imo, building html isn't best method here. best build table cells using dom , add event handler...

jquery enabling a button after some time -

this code not working , disables code , after must enable , how it? wrong? doing avoid multiple clicks <% html.enableclientvalidation(); %> $(document).ready(function () { $('#form1').submit(function () { $('#btn').attr("disabled", "disabled"); settimeout('enablebutton()', 50); }); function enablebutton() { $('#btn').removeattr('disabled'); } }); <% using (html.beginform("create","organizationgroups",formmethod.post,new {id="form1"})) {%> %> <%= html.validationsummary(false)%> <div> <%= html.actionlink("back list", "manageorganizationgroup")%> </div> you can't pass string settimeout() here, since function isn't global, instead pass direct reference function, change this: settimeout('enablebutton()', 50); to this: setti...

safari - Developing an out-of-process browser plugin on Mac OS X v10.6 -- restriction against platform APIs? -

i'm developing browser plugin macosx 10.6, , planning use netscape api portability across browsers , architectures. according apple's documentation , of 10.6 such plugins run out-of-process improve integrity of browser session. i'm concerned following directive give in documentation: use platform apis sparingly. wherever possible, should use new plug-in apis need. if no such apis exist, file bugs requesting them. i'm not sure nature of directive is. advice improve portability of plugin, reminder accessing operating system's other apis can open possibility of crashing client or corrupting user's data, or indication access platform apis in way "broken?" its portability advice. npapi is, although not officially standardized, stable , wraps platform specific apis you. if try use npapi whenever possible, avoid quite porting e.g. happened relatively apple deprecating carbon when transitioning 64 bit.

database - Would you ever create a relationship on a natural ID or use an internal ID and emulate the natural ID relationship? -

possible duplicate: surrogate vs. natural/business keys if given 2 tables, level1 [id, title, number] level2 [id, fkid???, title, number] a user of system understands level2 related level1 based on level1's number, question is, make relationship based on internal id , "emulate" relationship "number" or use "number" field , done it? the 2 standard reasons relating on database id rather natural id are: it's difficult guarantee natural id never change under circumstance generally natural id takes more space , not efficient index database id (though of course not hard , fast - depends on data constituting natural id). using database id, can avoid duplication of business data.

lambda expressions in c# vs. vb.net -

functionally, there difference (apart syntax onbviously) between lambda expressions in c# , vb.net? edit: following on craigtp's answer: references situation in .net 4? edit: i'm asking because i'm used c#, next project customer asks vb.net. we're not priori against that. realize language constructs supported in both languages. however, we're particularly fond of way c# implements lambda expressions. have overview of differences vb.net edit: accepted craigtp's answer pointing out consider important difference. so summarize: vb.net 9 not support multiline statements in lambda expression, , lambda must return value. both of these issues addressed in vb.net 10 there's no functional difference, however, joe albahari says in this forum post : vb.net doesn't support multi-statement lambda expressions or anonymous methods. note based upon c# 3.0 , vb.net 9.0 (ie. visual studio 2008 versions of languages) - i'm not sure if ...

coding style - Unwrapping datatypes in Haskell without extraneous code -

say have x = 2 is there way (preferrably builtin mechanism/function) use x in single statement such if just, 2 automatically unwrapped , used, , if nothing, exception raised? that is, (f x) + 2 == 4 if x == 2 , , raises exception if x == nothing . data.maybe.fromjust has been mentioned other answers already: fromjust :: maybe -> fromjust nothing = error "maybe.fromjust: nothing" fromjust (just x) = x there's maybe (found in both prelude , data.maybe ): maybe :: b -> (a -> b) -> maybe -> b maybe n _ nothing = n maybe _ f (just x) = f x fromjust can written using maybe : fromjust = maybe (error "maybe.fromjust: nothing") id as can see, maybe allows flexibility in handling both cases without requiring pattern matching: \x -> maybe 0 (+ 2) x -- nothing -> 0, 2 -> 4 similarly, prelude , data.either have either :: (a -> c) -> (b -> c) -> either b -> c : \x -> either (subtract 1...

Continuous integration & eclipse plugin development -

i developing set of eclipse plugins, , have several junit plugin tests start instance of eclipse, create mock workspace , mock project , runs various operations on them. want put on continuous integration , @ loss start. using hudson, there plugins makes easier? can tests launch eclipse in headless mode or on ci server? pointers appreciated. i think best solution building eclipse-based software tycho - based on maven , uses standard eclipse files (like manifest, target platform, product definition). got started using intro blog: http://mattiasholmqvist.se/2010/02/building-with-tycho-part-1-osgi-bundles/ , , worked well. use hudson, , since tycho maven-based, hudson integration trivial , worked calling maven, hudson supports out of box.

linq to sql - Linq2EF: Return DateTime with a TimeZone Offset -

our database has times stored utc, , know user's current timezone, want return relative that. want incorporate offset in linq projection so: var users = u in this.context.users select new userwithcorrecteddate { id = u.id, firstname = u.firstname, lastname = u.lastname, registrationdate = u.registrationdate.value.addhours(-5) }; of course, linq2ef cannot convert " addhours " canonical function. there way this? update: another thought, if timezone offset stored in database column, there way have db perform calculation (date + offset)? linq entities supports sqlfunctions. if know offset number of hours this: var users = u in this.context.users select new userwithcorrecteddate { id = u.id, firstname = u.firstname, lastname = u.lastname, registrationdate = sqlfunctions.dat...

ASP.NET ReportViewer works in development, is empty when deployed -

i have asp.net web app utilizes reportviewer show local reports. works beautifully on development machine (xp pro, visual studio 2008). when deploy app production server (windows server 2008, iis 7), site works well, except report viewer. when generate report, report viewer remains empty. i have written debugging code verify records being received database, , are. no error occurs but, no records show in report viewer. also, images appear in menu bar of reportviewer control (export button, print button, forward , buttons, etc) not load either. i ran reportviewer.exe on server install appropriate files, , have verified in gac of machine. can suggest way debug this...it easier if error being generated (i can't believe said that)? please verify have required web.config entries. suspicion missing entry in system.webserver/handlers, required in iis7. iis7 pretty ignores system.web/httphandlers section, may explain why works in iis 5.1 (xp) not in 7. version numbers m...

windows xp - Persistent Shadow Copy in XP SP2? -

i'm wondering if xp supports persistent shadow copying windows vista/7 do. read wikipedia article shadow copy , had paragraph (emphasis mine): the creation of persistent snapshots (multiple snapshots remain available across reboots until deleted system) has been added in windows server 2003 , allowing 512 snapshots exist simultaneously same volume. in windows server 2003, vss therefore used create incremental periodic snapshots of data or deltas (differences) of changed files on time. maximum of 64 snapshots stored on server , accessible clients or on same server through network shares. feature known shadow copies shared folders , designed client-server model. shadow copies shared folders client required installed on windows 2000 , windows xp rtm , sp1. copy of client 32-bit windows platforms available on server or downloadable microsoft. it built os beginning windows xp sp2 . i interpreted xp having ability create persist...

iphone - UITextField - Switch Between Keyboard and UIPickerView -

i'm working on iphone app uses core data. 1 of view controllers allows user edit information coffee, , has uitextfield in user can enter 1 descriptive "tag" type of coffee. i'd set uitextfield show keyboard if user clicks main area of uitextfield (to enter new tag), , use button rightview display uipickerview allow user select list of known tags have been entered, i.e.: --------------------------------------------- |this area should display keyboard | button | --------------------------------------------- what i'm confused how switch , forth between firstresponder keyboard , uipickerview , again if user clicks , forth. surely out there has done this, hints on how set (or if i'm using iphone's ui elements correctly) great! thanks! you can keep track of active text fields , pickers using 2 references like: uitextfield *activefield; uipickerview *activepicker; whenever text field starts editing, assign activefield point it. same thin...