Posts

Showing posts from January, 2014

.net - good c# asp.net open source project for code study -

can recommend asp.net c# open-source project purpose of studying code become better programmer? just in case have missed it, scott hanselman covers exact topic on blog regularly. see if of these projects pick interest: http://www.hanselman.com/blog/categoryview.aspx?category=source+code

How to prevent 'over-testing' in a test case? (C#/nUnit) -

i'm working on test cases @ moment, , i'm regularly finding i'm ending multiple asserts in each case. example (over-simplified , comments stripped brevity): [test] public void testnamepropertycorrectlysetoninstantiation() { myclass myinstance = new myclass("test name"); assert.areequal("test name", myinstance.name); } this looks acceptable in principle, point of test verify when the class instantiated given name, name property set correctly, fails if goes wrong on instantiation, before gets assertion. i refactored this: [test] public void testnamepropertycorrectlysetoninstantiation() { myclass myinstance; string namepropertyvalue; assert.doesnotthrow(() => myinstance = new myclass("test name")); assert.doesnotthrow(() => namepropertyvalue = myinstance.name); assert.areequal("test name", namepropertyvalue); } but of course, i'm testing 3 things here; in test, i'm not interested in testing whet...

sql server - How to log in T-SQL -

i'm using ado.net access sql server 2005 , able log inside t-sql stored procedures i'm calling. somehow possible? i'm unable see output 'print'-statement when using ado.net , since want use logging debuging ideal solution emit messages debugview sysinternals. i solved writing sqlclr-procedure eric z beard suggested. assembly must signed strong name key file. using system; using system.data; using system.data.sqlclient; using system.data.sqltypes; using microsoft.sqlserver.server; public partial class storedprocedures { [microsoft.sqlserver.server.sqlprocedure] public static int debug(string s) { system.diagnostics.debug.writeline(s); return 0; } } } created key , login: use [master] create asymmetric key debugprockey executable file = 'c:\..\sqlserverproject1\bin\debug\sqlserverproject1.dll' create login debugproclogin asymmetric key debugprockey grant unsafe assembly debugproclogin imp...

performance - Push or Pull for a near real time automation server? -

we developing server whereby client requests interest in changes specific data elements , when data changes server pushes data client. there has vigorous debate @ work whether or not better client poll data. what considered ideal method, in terms of performance, scalability , network load, of data transfer in near real time environment? update: here's link gives food thought regards ui updates. there's no ideal method every situation, push better , used more often. allows optimize server caching , data transfers, helps performance , scalability, , cuts network traffic bit avoiding client requests , empty responses. can important advantage server operate in it's own pace , supply clients data when ready. industry standarts - such opc, gid - support both. server pushes updates subscribed clients, client can pull used data out without bothering subscription.

asp.net - Read first 3 paragraphs of a long string. [C#, HTML AgilityPack] -

i read long string , output first 3 paragraphs of string. how achieve this? wanted use code show (n) number of words have since changed paragraphs. public string mysummary(string html, int max) { string summaryhtml = string.empty; // load our html document htmldocument htmldoc = new htmldocument(); htmldoc.loadhtml(html); int wordcount = 0; foreach (var element in htmldoc.documentnode.childnodes) { // inner text strip out html, , give plain text string elementtext = element.innertext; // split space words in element string[] elementwords = elementtext.split(new char[] { ' ' }); // , if haven't used many words ... if (wordcount <= max) { // add *outer* html (which have proper // html formatting fragment) summary summaryhtml += element.outerhtml; wordcount += elementwords.count() + 1; } else { ...

java - What platforms JavaFX is/will be supported on? -

i have read javafx, , new technologies wanted hands "dirty" it. however, although talks of multiplatform support, can't find specifics on this. what platforms support javafx application? java se? me? depend upon apis in javafx use? javafx has 3 planned distributions. javafx desktop run on windows, mac, linux, , solaris @ fcs , require java se. support linux , solaris forthcoming. javafx tv , javafx mobile have no announce target platforms. unannounced whether run on me or se, , if me profiles. one important platform distinction javafx desktop support swing components while javafx mobile not (only scene graph graphics). javafx tv least publicly concrete of 3 @ time.

xaml - How do I make custom MenuHeaders in WPF with accelerators? -

i'd make custom menuheaders in wpf can have (for example), icon , text in menu item. normally using menuitems, if populate header field straight text, can add accelerator using underscore. eg, _file however, if wanted put in usercontrol, believe function break, how similar following? <menu> <menuitem> <menuitem.header> <usercontrol> <image source="..." /> <label text="_open" /> </usercontrol> </menuitem.header> </menuitem> ... i think icon property fits needs. answer original question, possible retain accelerator functionality when compose content of menuitem. if have nested content in menuitem need define accesstext property explicitly in first 1 below. when use inline form, automagically taken care of. <menu> <menuitem> <menuitem.header> <stackpanel orientation="horizontal"> <image source...

java - JAX-WS and character encoding questions -

i have question on sending xml string in webservice. 1 of our providers has developed webservice should use. webservice transport mechanism own request/response messages, e.g. class myrequest serialized xml string using jaxb passed setrequest method in webservice, because easiest way them or maybe because wanted high transparency in application... don't know. anyhow. here question. if have webservice has character encoding iso_8859-1 serialized xml has character encoding utf-8 (or other encoding supporting more characters iso_8859-1) these serialized , deserialized correctly? or have send information content of string? , if so, how can that? the server side of webservice written in .net. how compability between java , .net? there encodings in .net isn't supported in java or vice versa? / andreas if implement web service correctly (and too), don't need worry character encoding, because: (well-formed) xml has built-in metadata allows character encodin...

ado.net - Old-school SQL DB access versus ORM (NHibernate, EF, et al). Who wins? -

i've been successful writing own sql access code combination of stored procedures , parameterized queries , little wrapper library i've written minimize ado.net grunge. has worked me in past , i've been pretty productive it. i'm heading new project--should put old school stuff behind me , dig orm-based solution? (i know there vast high-concepts differences between nhibernate , ef--i don't want here. sake of argument, let's lump linq old-school alternatives.) i'm looking advice on real-world application of orm type stuff against know (and know pretty well). old-school ado.net code or orm? i'm sure there curve--does curve have roi makes things worthwhile? i'm anxious , willing learn, have deadline. a question controversial topic. this blog post frans bouma few years citing pros of dynamic sql (implying orms) on stored procedures sparked quite fiery flame war.

visual studio 2010 - VS2010 & SourceSafe 2005 - Logging into SourceSafe from the command line? -

i have custom application brings several resources , builds visual studio project exe file can use upgrade company's website , database. custom app uses system.diagnostics.process in couple of places access sourcesafe, use command ss ... -y, log sourcesafe , process events works expect. i'm not logged company's domain why manually logging sourcesafe. now when part start building vs2010 project, i'm using command devenv /build release /out ..\log.txt /project <myproject> not build project, , log file shows error... the following files specified on command line: <path vs project> these files not found , not loaded. the path project correct , if run command window loads project, asks sourcesafe credentials , builds. question is... there way can log sourcesafe using command line above, or adding processinfo parameters before execute command line? you may check out thread below , see if helps: http://social.msdn.microsoft.com/forums/en/vssourc...

Replacements for switch statement in Python? -

i want write function in python returns different fixed values based on value of input index. in other languages use switch or case statement, python not appear have switch statement. recommended python solutions in scenario? you use dictionary: def f(x): return { 'a': 1, 'b': 2, }[x]

iphone - NSURLConnection doesn't call delegate methods -

i saw similar questions here, couldn't find solution problem. have simple nsurlconnection in main thread (at least didn't create other threads), delegate methods aren't called [[[nsurlconnection alloc] initwithrequest:request delegate:self] autorelease]; and no methods called, e.g. - (void)connection:(nsurlconnection *)connection didreceiveresponse:(nsurlresponse *)response { nslog(@"didreceiveresponse"); } self delegate nsxmlparser, think should not problem, have working in other class in same project. checked 10 times already, can't find problem. i've seen hack solve here: http://www.depl0y.com/?p=345 don't it, may knows better solution? thanks the reason know separate thread (that terminated when delegate methods called). try nslog(@"is%@ main thread", ([nsthread ismainthread] ? @"" : @" not")); right before url connection creation

c# - Accessing <li> tag, ASP.Net -

i'm trying access <li> tag in first master page file. tried findcontrol(..) allways returns null. structure: first master page (which contains <li id="element" runat="server" > second master page default.aspx (need access here) what need access li element? you access server-side control so: page.master.findcontrol("controlid"); however, if tag not set runat="server" , you'll have find way, such getting resulting response.content , changing @ point. edit: since you're using nested master pages, may need go further in control hierarchy if want reach "root" master , find control in it. maybe: control li = page.master.master.findcontrol("controlid")

c# - Can I send only byte array with asynchronous Socket class? -

i work on server/client program based on asynchronous socket. far see send() method of socket class accept byte buffer. have convert byte array or there other method? what should send simple string example? string sendmessage = "this clarified example now"; byte[] bytemessage = system.text.encoding.ascii.getbytes(sendmessage) should need. i, one, fan of 30+ character function calls.

How to check if a path is absolute path or relative path in cross platform way with Python? -

unix absolute path starts '/', whereas windows starts alphabet 'c:' or '\'. python has standard function check if path absolute or relative? os.path.isabs returns true if path absolute, false if not. the documentation says works in windows (i can confirm works in linux personally). os.path.isabs(my_path)

internet explorer 6 - Is it possible to display the entity &#8659; in IE6 -

is possible display ⇓ entity in ie6? being display in every browser not ie 6.i writing markup such as: <span>&#8659;</span> according this page , symbol doesn't show in ie6 @ all. symbol character numeric description ⇓ &darr; &#8659; down double arrow - - * doesn't show ms ie6 if need particular symbol, may have go small graphic of arrow - not ideal solution, if need display in ie6 may option.

xslt - how to add xsl attribute -

i have xml img tag <img> source </img> i want generate: <img src="source.jpg"> i tried that: <img> <xsl:attribute name="src"> <xsl:text> <xsl:value-of select="node()" />.jpg </xsl:text> </xsl:attribute> </img> but doesng work the reason why doing not work cannot evaluate xslt expressions inside of <xsl:text> element. <xsl:text> can contain literal text, entity references, , #pcdata . if move <xsl:value-of> outside of <xsl:text> , following work: <img> <xsl:attribute name="src"> <xsl:value-of select="node()" /> <xsl:text>.jpg</xsl:text> </xsl:attribute> </img> however, selecting <xsl:value-of select="node()> <img> in example include carriage returns , whitespace characters inside of <img...

Sharepoint permissions. Require multiple groups -

i have permission question hope can me with. i have setup permission groups each department in organization, i.e. “dept-1”, "dept-2", etc. plan put people in these groups correspond department work for. next i’m setting groups correspond areas of work, i.e. “area-tech”, “area-manager”. i’d able give access list user needs in both “dept-1” , “area-manager” in order view , edit items. if user in “dept-1” shouldn’t have access. can done? maybe there way. thanks no, need 3rd group "dept1 area mgrs" or something. permissions in sharepoint "or"-based, not "and"-based.

Development directory Structure -

i wondering directory structure commonly used in development projects. mean idea of facilitating builds, deploys release, , etc. i used maven structure java project, not sure it's best structure non-maven driven project. so, have 2 questions: when guys start new projects, structure use? and: if need integrate 2 different languages, example java classes php application; php files source files, web files, you use /src, /classes, webapps/php ? choices in such scenarios. as note: wondering choices directories names. 3-letters names (src, lib, bin, web, img, css, xml, cfg) opinions descriptive names libraris, sources or htdocs/public_html ? after couple years working different structures found structure hols variations me: /project_name (everything goes here) /web (htdocs) /img /css /app (usually framework or sensitive code) /lib (externa libs) /vendor_1 /vendor_2 /tmp /cache /sql (sql s...

c# - Should I use int or Int32 -

in c#, int , int32 same thing, i've read number of times int preferred on int32 no reason given. there reason, , should care? ecma-334 :2006 c# language specification (p18): each of predefined types shorthand system-provided type. example, keyword int refers struct system.int32 . matter of style, use of keyword favoured on use of complete system type name.

windows - GDI+ DrawImage() with transparent bitmap to a printer -

does have pointers on how draw bitmap has alpha channel using graphics::drawimage() when graphics context created based on printer hdc? printer drivers don't support alpha blending - there alternative rendering offscreen bitmap , sending printer. not feasible, high res printing large format printers. what kind of printer that? regular printers don't print white. create in-memory image , 'flatten' (remove alpha channel) , print result.

php - writting files to a different directory -

possible duplicate: php write outside document root assume have script in somewhere in htdocs directory , want script write files in directory of same parent htdocs. how do it? your htdocs represents docroot . reading the php manual php.ini file : doc_root php's "root directory" on server. used if non-empty. if php configured safe mode, no files outside directory served. if php not compiled force_redirect, should set doc_root if running php cgi under web server (other iis). alternative use cgi.force_redirect configuration below. check if you're working in safe mode. check permissions folder you're writing to. should allow writing server-user (www, www-data, whatever). finally, question might a duplicate of one .

gwt lazy loading -

is possible in large gwt project, load portion of javascript lazy, on fly? overlays. ps: iframes not solution. check out gwt.runasync google i/o talk below, goes lazy loading of javascript in gwt projects. http://code.google.com/p/google-web-toolkit/wiki/codesplitting http://code.google.com/events/io/sessions/googlewavepoweredbygwt.html (around time 25:30)

javascript - Problem accessing the content of a div when that content came from an Ajax call -

here's simple prototype example. all is, on window load, ajax call sticks html div. <html> <head> <script type="text/javascript" src="scriptaculous/lib/prototype.js"></script> <script type="text/javascript"> event.observe(window, 'load', function(){ new ajax.request('get-table.php', { method: 'get', onsuccess: function(response){ $('content').innerhtml = response.responsetext; //at call, div has html in click1(); }, onfailure: function(){ alert('fail!'); } }); //at call, div empty click1(); }); function click1(){if($('content').innerhtml){alert('foun...

vb6 - Visual Basic 6 and UNC Paths -

i'm receiving feedback developer "the way visual basic (6) can deal unc path map drive." accurate? and, if so, what's underlying issue , there alternatives other mapped drive? here 1 way works. sub main() dim fs new filesystemobject ' add reference microsoft scripting runtime msgbox fs.fileexists("\\server\folder\file.ext") end sub

iphone - Global NSMutable array of a project -

i want know how can declare , use global nsmutable array of objective c project. mean need update here in 1 class , need use in class.... can give me kind of idea?? thanks rony pass reference around class class. or keep reference array instance in app delegate, can access class in application.

c++ - Minimal latency objects pooling technique in multithread application -

in application have 30 types of objects created repeatedly. some of them have long life (hours) have short (milliseconds). objects created in 1 thread , destroyed in another. does have clue pooling technique in sense of minimal creation/destruction latency, low lock contention , reasonable memory utilization? append 1. 1.1. object pool/memory allocations 1 type not related type (see 1.3 exception) 1.2. memory allocation performed 1 type (class) @ time, several objects @ time. 1.3. if type aggregates type using pointer (for reason) these types allocated in 1 continuous piece of memory. append 2. 2.1. using collection access serialization per type known worse new/delete. 2.2. application used on different platforms/compilers , cannot use compiler/platform specific tricks. append 3. it becomes obvious fastest (with lowest latency) implementation should organize object pooling star-like factories network. central factory global other thread specific factories. r...

sql server - Database schema for hierarchical groups -

i'm working on database design groups hierarchy used foundation of larger system. each group can contain other groups, , 'devices' leaf objects (nothing goes below device). the database being used ms sql 2005. (though working in ms sql 2000 bonus; solution requiring ms sql 2008 unfortunately not feasible @ time). there different types of groups, , these need dynamic , definable @ run-time users. example, group types might "customer", "account", "city", or "building", "floor", , each type going have different set of attributes, definable user. there business rules applied - eg, "floor" can contained underneath "building" group, , again, these definable @ runtime. a lot of application functionality comes running reports based on these groups, there needs relatively fast way list of devices contained within group (and sub-groups). storing groups using modified pre-order tree traversal technique ...

Refactoring Java factory method -

there's unsatisfactory code: /* given command string in first 8 characters command name padded on right whitespace, construct appropriate kind of command object. */ public class commandfactory { public command getcommand(string cmd) { cmdname = cmd.substring(0,8).trim(); if(cmdname.equals("start")) { return new startcommand(cmd); } if(cmdname.equals("end")) { return new endcommand(cmd); } // ... more commands in more if blocks here // else it's bad command. return new invalidcommand(cmd); } } i'm unrepentant multiple exit points - structure clear. i'm not happy series of near-identical if statements. i've considered making map of strings commands: commandmap = new hashmap(); commandmap.put("start",startcommand.class); // ... etc. ... using reflection make instances of appropriate class looked map. while conceptually ...

sql - Selecting a user's friend's events -

i have these information : table "users" => **id** **name** 1 2 b 3 c 4 d 5 e table "friends" => **senderid** **receiverid** **state** 1 2 x 2 3 ok 3 1 ok 3 4 ok 5 3 ok 5 4 ok table "events" => **senderid** **receiverid** **text** 1 1 3 ssss 2 3 1 dsadsa 3 2 3 safsdf 4 3 5 fgfdgfd 5 4 3 fgfhgfh 6 5 4 sad sad my question how events of user's friends in 1 sql statement using joins . for example :=> userid : 1 his friends : 3 (state = ok) f...

untagged - Best programming novel to take on holiday -

i enjoy 2 week break in spain expect have lots of time relaxing , reading. i read lot of non-fiction i'm looking novel suggestions. if there cryptonomicon out there i'd love hear it! update : in end took 4 books including quicksilver. quicksilver fantastic , forward continuing series. disappointed gen x (coupland) , pattern recognition (gibson). recommendations, i'm sure return list when have more free time. william gibson's neuromancer comes mind, although liked cryptonomicon better. neuromancer http://bks9.books.google.com/books?id=idffmpw32hqc&printsec=frontcover&img=1&zoom=1&sig=acfu3u21viqixnn1mjlgtmp4aj__8nummg stephenson's own baroque cycle trilogy , snow crash outstanding.

Is there any algebraic structures used in functional programming other then monoid? -

i getting know functional programming (in haskell , scala). it's capabilities , elegance quite charming. but when met monads, makes use of algebraic structure named monoid, surprised , glad see theoretic knowledge have been learning mathematics made use of in programming. this observation brought question mind: can groups, fields or rings (see algebraic structures others) used in programming more abstraction , code reuse purposes , achieving mathematic-alike programming? as know, language named fortress (which surely prefer on language once when compiler completed) defines these structure in library code. uses saw far numeric types, familiar with. there other uses of them? best regards, ciun you can model many structures. here's group: class group mult :: -> -> identity :: inverse :: -> instance group integer mult = (+) identity = 0 inverse = negate -- s_3 (group of bijections of 3-element set) data s3 = abc | acb | ba...

oscommerce - PHP named constant prints/concats as the variable name, not value -

i have old oscommerce site php4, running on php5. named constants defined define() being evaluated incorrectly: $string = '<a href="http://www.oscommerce.com" target="_blank">' . box_entry_support_site . '</a><br>'; will show box_entry_support_site , not value placed in box_entry_support_site . something needs changed in php.ini ? i never ran problem when putting oscommerce sites on php5 php4. most probably, define isn't being define() 'd correctly. default behaviour (with error reporting relaxed) show constant when isn't found.

algorithm - Packing rectangles for compact representation -

i looking pointers solution of following problem: have set of rectangles, height known , x-positions , want pack them in more compact form. little drawing (where rectangles of same width, width may vary in real life), like, instead of. -r1- -r2-- -r3-- -r4- -r5-- something like. -r1- -r3-- -r2-- -r4- -r5-- all hints appreciated. not looking "the" best solution. your problem simpler variant, might tips reading heuristics developed "binpacking" problem. there has been lot written this, this page start.

java - Finding the start and end of a match with Lucene -

i find start , end positions of match lucene (version 3.0.2 java) query. seems should able info highlighter or fastvectorhighligher, these classes seem return text fragment relevant text highlighted. there way info, either highlighter or scoredoc itself? update: found related question: finding position of search hits lucene but think answer allasso won't work me because queries phrases, not individual terms. if i'd take code fastvectorhighlighter. relevant code in fieldtermstack: list<string> termset = fieldquery.gettermset(fieldname); vectorhighlightmapper tfv = new vectorhighlightmapper(termset); reader.gettermfreqvector(docid, fieldname, tfv); // <-- @ line string[] terms = tfv.getterms(); foreach (string term in terms) { if (!termset.contains(term)) continue; int index = tfv.indexof(term); termvectoroffsetinfo[] tvois = tfv.getoffsets(index); i...

c# - Panel.Dock Fill ignoring other Panel.Dock setting -

if create panel on form , set dock=top , drop panel , set dock=fill, may fill entire form, ignoring first panel. changing tab order nothing. docking layout depends on order of sibling controls. controls docked "button up", last control in collection docked first. docked control take layout of previously docked siblings account. hence control dock=fill should first (top) in sibling order, if want take other docked controls account. if not first control, earlier controls overlap it. this can confusing because sibling-order not same visual order, , sibling order not apparent design view. the document outline window (view -> other windows -> document outline) gives useful tree-view on control hierarchy , order, , allows change sibling order of controls. you can change sibling order directly in designer context menu -> bring front / send back, moves control first or last of siblings. these menu labels may confusing since actual effect depends on layo...

Is it necessary to override the membership and the role providers? -

i'm working on web app , don't want store connection strings in web or app config because of requirements. so far have found way achieve - override membership , role providers. i don't understand why have override role provider when authentication apparantely handled membership provider? thank you while sqlroleprovider , sqlmembershipprovider separate concerns, both talk same database (typically). they each have distinct configuration section , require instance of connections string. i approve of strategy discovered on other question , if wish use roles have same thing, configuration in code, doing membership. you should link other question give context , prevent getting flagged duplicate.

command line - How do I shutdown - restart - logoff Windows via a bat file? -

i've been using remote desktop connection workstation, i'm not able use shutdown/restart function in start menu while doing this. i've put few helpful options in answer below. note: wanted make sure answers mentioned along own on this. and here in no particular order. force shutdown josephstyons executing dll file vonc run run box dean remote shutdown kip here's how shutdown functions via batch file: shutdown -r — restarts shutdown -s — shutsdown shutdown -l — logoff shutdown -t xx — xx number of seconds wait till shutdown/restart/logoff shutdown -i — gives dialog box fill in function want use shutdown -a — aborts previous shutdown command....very handy! shutdown -h — hibernate. easy mistake - it's not help shutdown -y — removes prompts @ shutdown (help not available in documentation) additional options: -f — force selected action -t <seconds> — set time shutdown. use -t 0 "now"

jQuery slideToggle jumps around -

i'm using jquery slidetoggle function on site reveal 'more information' something. when trigger slide, content gradually revealed, located right 100 pixels until end of animation when jumps correct position. going other way, content jumps right same amount before starts 'hide' animation, gradually hidden. occurs on ie7/8, ff, chrome. any ideas on how fix this? thanks in advance. i have found workaround, i'm still not sure of details. seemed when 'overflow: hidden' style added jquery, effect nearby floated element had changed. workaround place permanent 'overflow: hidden' on slidetoggle'd div, , negative margin-left counterbalance effect. i surprised changing overflow value has such effect on layout, there have it...

cruisecontrol.net - CCNet live updates to LCD TV -

i working on agile project , use automated build runs on build server using cruise control.net. have alse integrated various things nunit test execution code coverage using ncover fxcop code analysis stylecop source code analysis we fail builds if criterieas acceptable code coverage not met. i know if there free tool can used display various outputs of cruise control , reports onto lcd tv @ periodic interval. these outputs should show near realitime status of latest build including build summary nunit test summary fxcop summary stylecop violation ncovercovergae summary report when near real time mean should refresh tv screen every few minutes, may 10 or 15 minutes. have various projects running display each of above mentioned reports. any in regards highly appriciated. displaying information mentioned above might pretty confusing. there tool can display ccnet build status: cradiator . perhaps suits needs.

sql - Question about accessing data -

if 2 users accessing same database table, how prevent users overwriting each other’s data? thank you, -nimesh look @ this discussion review of different strategies or techniques database locking in application.

java - How to write DDL in the criteria API? -

consider code in how delete jpa entities? documentation here http://download.oracle.com/docs/cd/e17410_01/javaee/6/tutorial/doc/gjitv.html describes queries. the documentation of criteria api describes queries because criteria api not made ddl operations. actually, i'd whole jpa api not made that. and way, code of other question doesn't show ddl operations, it's shows bulk dml operations described in jpa 2.0 specification: 4.10 bulk update , delete operations bulk update , delete operations apply entities of single entity class (together subclasses, if any). 1 entity abstract schema type may specified in or update clause. the syntax of these operations follows: update_statement ::= update_clause [where_clause] update_clause ::= update entity_name [[as] identification_variable] set update_item {, update_item}* update_item ::= [identification_variable.]{state_field | single_valued_object_field} = ...

Nhibernate Generat wrong SQL for Oracle with locking -

yesterday i've been trying make code work inspite fact it's working fine nhibrnate , sql server when come oracle generate wrong sql unitofwork.current.createcriteria<bill>().add(restrictions.isempty("reqid")) .setmaxresults(batchsize).setlockmode(lockmode.upgrade).list<bill>(); the generated sql select * (select bill_0.id,bill_0.billno ...... bill bill_0 bill_0.reqid not null ) rownum < 10 update of bill_0.id so wont run because allies bill_o defined inside inner sql statement got solution ? the correct sql tried , worked on oracle db select bill_0.id,bill_0.billno ...... bill bill_0 bill_0.reqid not null , rownum < 10 update of bill_0.id since, say, nhibernate generating invalid oracle sql, suggest file bug nhibernate people. sql work if in-line view had been assigned alias of "bill_0", or if update clause didn't use table alias ("for update of id"). whether can modify nhibernate calls make eithe...

objective c - Getting CFMutableDictionaryRef Values -

i access values cfmutabledictionaryref , math on them. using code below have managed print properties of battery. able print out single values (although in doing warning:invalid receiver type:cfmutabledictionaryref ). then try convert string values nsnumber , program bugs. gives me unrecognized selector sent instance 0x5d65f70 help? cfmutabledictionaryref matching , properties = null; io_registry_entry_t entry = 0; matching = ioservicematching( "iopmpowersource" ); //matching = ioservicenamematching( "applesmartbattery" ); entry = ioservicegetmatchingservice( kiomasterportdefault , matching ); ioregistryentrycreatecfproperties( entry , &properties , null , 0 ); nslog( @"%@" , properties ); nsstring * voltage = [properties objectforkey:@"voltage"]; nsstring * currentcapacity = [properties objectforkey:@"currentcapacity"]; nsnumberformatter * f = [[nsnumberformatter alloc] init]; [f setnumberstyle:nsnumberformatterde...

c# - Creating an asp:Button programmatically? -

i'm using code-behind page create save button programmatically: button btnsave = new button(); btnsave.id = "btnsave"; btnsave.text = "save"; however think must create html button or perhaps needs else cannot seem set onclick attribute in following line, can specify onclientclick isn't 1 want set. button btnsave = new button(); btnsave.id = "btnsave"; btnsave.text = "save"; btnsave.click += new system.eventhandler(btnsave_click); protected void btnsave_click(object sender, eventargs e) { //do when button clicked. }

obfuscation - How can I obfuscate (protect) JavaScript? -

i want make javascript application that's not open source, , wish learn how can obfuscate js code? possible? obfuscation: try yui compressor . it's popular tool, built, enhanced , maintained yahoo ui team. you may use: google closure compiler uglifyjs private string data: keeping string values private different concern, , obfuscation won't of benefit. of course, packaging source garbled, minified mess, have light version of security through obscurity . of time, it's user viewing source, , string values on client intended use, sort of private string value isn't necessary. if had value never wanted user see, have couple of options. first, kind of encryption, decrypted @ page load. 1 of secure options, lot of work may unnecessary. base64 encode string values, , easier.. wanted string values easily decode them . encryption way prevent accessing data, , people find more security need. sidenote: obfuscation in javascript has been kn...

java - Concurrent periodic task running -

i'm trying find best solution periodic task running in parallel. requirements: java (spring w/o hibernate). tasks being managed front-end application , stored in mysql db (fields: id , frequency (in seconds), < other attributes/settings task scenario >). -- crontab, frequency (seconds) field, instead of minutes/hours/days/months/days of weeks. i'm thinking about: taskimporter thread polling tasks db (via tasksdao.findtoprocess() ) , submitting them queue. java.util.concurrent.threadpoolexecutor running tasks (from queue) in parallel. the tricky part of architecture tasksdao.findtoprocess() : how know tasks time run right now? i'm thinking next_run task field, populated ( update tasks set next_run = timestampadd(second, now(), frequency) id = ? straight after selection ( select * tasks next_run null or next_run <= now() update ). problem: have run lots of updates lots of select'ed tasks (update each task or bulk update) + concurrency...

c# - Is there a perceptual DeltaRGB comparison of two colours (i.e., like DeltaE2000)? -

is there reliable delta rgb formula or code snippet colour delta of full rgb tri stim values, how deltae 2000/cmc lab/lch takes perceptual differences account? the rgb colourspace any, if needed particular 1 keep srgb calculations. c# preferred, can convert language. i have basic rgb delta formula, implement gets truer sense of perceptual colour difference. current right is float delta = math.sqrt(math.pow(r1-r2, 2) + math.pow(g1-g2, 2) + math.pow(b1-b2, 2)); this similar deltae 76(lab), has same drawbacks perceptual difference not taken account. please don't google search , paste first thing see! there lots of delta rgb formula's out there may found, not take perceptual differences account. if have knowledge of this, please comment and/or paste links code samples. also, have conversion rgb lab/lch , de2000/cmc. not looking that. i'm afraid gave right answer: conversion perceptual color space, simple delta formula makes sense. brilliant color scien...

java - Primary key from inserted row jdbc? -

is there cross database platform way primary key of record have inserted? i noted this answer says can calling select last_insert_id() , think can call select @@identity 'identity'; there common way accross databases in jdbc? if not how suggest implement piece of code access of sql server, mysql , oracle? copied code: pinsertoid = connection.preparestatement(insert_oid_sql, statement.return_generated_keys); where pinsertoid prepared statement. you can obtain key: // fill in prepared statement , pinsertoid.executeupdate(); resultset rs = pinsertoid.getgeneratedkeys(); if (rs.next()) { int newid = rs.getint(1); oid.setid(newid); } hope gives starting point.

windows - How do I find out the browser's proxy settings? -

i writing command-line tool windows uses libcurl download files internet. obviously, downloading doesn't work when user behind proxy server, because proxy needs configured. want keep tool simple possible however, , not have burden user having configure proxy. tool doesn't have config file, user otherwise have pass in proxy settings on every command, or set environment variable or somesuch -- way hassle. so thought, everyone's browser set properly, proxy configured , everything. true basic user because otherwise "their internet wouldn't work". so figure can find out whether use proxy looking @ ie's proxy settings. how go this? more specifically: is there 1 set of "proxy settings" in windows, used browsers (probably ie's), or have write different routines ie, firefox, opera, etc? i know can read values directly out of appropriate registry locations if configured manually, work "automatically detect proxy server?" have ...

php - How to read big file by 100 lines? -

i have rather big .txt file (~220mb) , need read 100 lines (\n symbol) chunks (for example). how can using php? thank you. fopen , fgets . fgets manual page has example on reading file line-by-line without loading memory @ once.

c# - Exception messages in English? -

we logging exceptions happen in our system writing exception.message file. however, written in culture of client. , turkish errors don't mean lot me. so how can log error messages in english without changing users culture? this issue can partially worked around. framework exception code loads error messages resources, based on current thread locale. in case of exceptions, happens @ time message property accessed. for exceptions, can obtain full english version of message briefly switching thread locale en-us while logging (saving original user locale beforehand , restoring afterwards). doing on separate thread better: ensures there won't side effects. example: try { system.io.streamreader sr=new system.io.streamreader(@"c:\does-not-exist"); } catch(exception ex) { console.writeline(ex.tostring()); //will display localized message exceptionlogger el = new exceptionlogger(ex); system.threading.thread t = new system.threading.thread(el.dolog)...

What is the binary representation of a boolean value in c# -

i know boolean value 1 byte (8 bits long) know binary representation. e.g. decimal => binary 4 => 100 (0000 0100) 8 => 1000 (0000 1000) bool value => ??? bool built-in basic type in c#. underlying representation implementation detail. the c# 4.0 language specification states in section 4.1.8: the bool type represents boolean logical quantities. possible values of type bool true , false . no standard conversions exist between bool , other types. in particular, bool type distinct , separate integral types, , bool value cannot used in place of integral value, , vice versa. in c , c++ languages, 0 integral or floating-point value, or null pointer can converted boolean value false , , non-zero integral or floating-point value, or non-null pointer can converted boolean value true . in c#, such conversions accomplished explicitly comparing integral or floating-point value zero, or explicitly comparing object referen...

Objective-C : Properties question -

as far understand when use properties compiler still converts them accessor methods during compilation. got little irritated when read need osx 10.5 or later use properties. why so? if in compiled application in fact still accessor methods see no need osx 10.5. or there else going on during run-time? because objective-c 2.0 runtime not ported 10.4. need compiler , runtime support handle of objc 2.0 properly.

c# - How to determine whether an interface type implements a custom attibute -

how determine whether interface type implements custom attibute? use getcustomattributes : typeof(iwhatever).getcustomattributes(typeof(customattribute), false) will return array of attributes. empty if doesn't implement 1 you're searching for.

Defining point of functional programming -

i can enumerate many features of functional programming, when friend asked me define functional programming me? couldn't. i defining point of pure functional programming computation done in functions no side effects. is, functions take inputs , return values, not change hidden state, in paradigm, functions more closely model mathematical cousins. this nailed down me when started playing erlang, language write-once stack. however, should clarified there difference between programming paradigm , , programming language . languages referred functional provide number of features encourage or enforce functional paradigm (e.g., erlang it's write-once stack, higher order functions, closures, etc.). functional programming paradigm can applied in many languages (with varying degrees of pain).

GIT vs. Perforce- Two VCS will enter... one will leave -

so i'm in process of getting git sold @ work. first thing need convince git better @ they're used doing. use perforce. else go through similar sale? links/advice? one of big wins can work disconnected network. win imo way adds/checkouts handled. more points welcome! have 10-20 devs total. the perl 5 interpreter source code going through throes of converting perforce git. maybe sam vilain’s git-p4raw importer of interest. in case, 1 of major wins you’re going have on every centralised vcs , distributed ones raw, blistering speed . can’t imagine how liberating have entire project history @ hand, mere fractions of fractions of second away, until have experienced it. generating commit log of whole project history includes full diff each commit can measured in fractions of second. git fast hat fly off. vcss have roundtrip on network have no chance of competing, not on gigabit ethernet link. also, git makes easy selective when making commits, thereby allowing chan...

mysql - Return perl array to MATLAB -

is there way return perl array matlab? or have return string , parse it? i'm using call matlab perl script interface mysql database. after results of query, want pass matlab. edit: i'm using modified version of perl.m call perl script. calls version of perl dbi installed, rather copy comes matlab. i changed line 65 of perl.m from perlcmd = fullfile(matlabroot, 'sys\perl\win32\bin\'); to perlcmd = 'c:\perl64\'; how calling perl script? if doing system call, can return string output. you wrapping call in mex file, or writing .mat files perl, suspect string parsing may easier, small arrays edit think did once in similar situation (had transfer data matlab) generate .m file creates matlab matrix, i.e. array = [ 1, 2, 3; 4, 5, 6; ]; and save disk. when program finished called m-file data workspace

android - SVN - how does removing a bin folder cause the src folder to be removed instead? -

there bin folder in version control bunch of .class files , other junk should not versioned. please explain me how following commit: 529 svn rm --force bin/ 530 svn ci -m "bin should not under version control." leads following: revision 249 author: ndunn date: mon jul 26 14:52:14 2010 utc (62 minutes, 34 seconds ago) log message: bin should not under version control. trunk/projname/src/ deleted i went through svn logs reminded me had happened before - sure enough, 1 2 separate occasions developers had attempted remove bin folder , instead src folder disappeared. any idea heck going on? android project that's under version control. i think this post solves mystery my problem when start working project, /bin folder generated sdk , copy of .svn folder /src copied /bin/.svn, breaks subversion structure. so using eclipse android had better prepared have changes made bin folder reflected in src... wow. picture solution:...

Does powershell have an equivalent to popen? -

i need able launch process , read output variable. based on return of command can choose show full output or selected subset. so clear, want launch text based process (psexec actually) , read output command (stdout, stderr, etc) variable rather have directly outputted console. you left off details regarding kind of process, think this article powershell team blog has whatever you'd do, either piping executable's output somewhere or utilizing system.diagnostics.process . now second option sounds want do, can use processstartinfo class feed in true redirectstandardoutput property, , read standardoutput property of process object whatever want output. standarderror works identically.

asp.net - Application_Start works fine on workstation, is not called when deployed -

i have application works great on development workstation fails when application deployed live environment. seems application_start not being called in live environment. i able fix removing precompiledapp.config file in root directory of web site on our test server. i'm guessing file holdover when project web site project. converted on web app project. if building web app project, make sure don't have precompiledapp.config file on target server.

windows - How to globally map AltGr key to Alt key? -

Image
i want altgr key behave left alt . usually, kind of stuff autohotkey , i'm open different solutions. i tried this: lcontrol & ralt::alt and autohotkey displayed error alt not being recognized action. tried following code: lcontrol & ralt:: send {alt down} keywait lctrl keywait ralt send {alt up} return which sort of works - i'm able use altgr key accessing hotkeys, still behaves differently: when press , release left alt , first menu item in current program receives focus. pressing , releasing altgr script nothing. any ideas? possible autohotkey? (remapping right ctrl , shift left siblings piece of cake) note: tried switching alt lalt in code , made no difference. thank answers. unable solve using autohotkey -- phillho's answer close, needed exatly same behaviour left alt key. however, registry thing worked needed. save altgr_to_leftalt.reg file , run it: windows registry editor version 5.00 [hkey_local_ma...

vba - access 2007 bug - intermittent query parameter prompts -

i working on access 2007 application created else. has strange, intermittent bug in prompts user query parameters when main form opened. query parameters not necessary, because error not occur. the strange "fix" problem open , close particular module before opening main form. form opens without parameter prompts. however, of course can't ask end users open , close modules. i tried using macro open , close module when database opened. fixes bug, leaves vba code window open, that's no good. has run before? suggested solutions, workarounds, debugging tips, etc? if use "database documenter" feature , check "yes" options, obtain exhaustive report should let trap problem parameter. export report .rtf or .pdf document, searchable. identify keyword dialog prompt, , search on that. once check query objects using documenter, check vba code. you'll stepping through code in ide. if main form has subforms, opened (within) main f...

asp.net mvc - Is ViewPageBase the right place to decide what master page to load? -

as can tell title, i'm n00b mvc. i'm trying decide master load based on route configuration settings. each route has masterpage property (in addition usual url, controller , action properties) , i'm setting masterpage in onpreinit event of viewpagebase class (derived viewpage). however, i'm not sure if mvc way of doing it? need controller supplies masterpage info view? here's code snippet. public class viewpagebase : viewpage { protected override void onpreinit(eventargs e) { routeelement currentroute = mvcroutes.getcurrentroute(); //set master page this.masterpagefile = string.isnullorempty(currentroute.masterpage) ? mvcconfiguration.defaultmasterpage : currentroute.masterpage; base.onpreinit(e); } } i'm huge fan of ignoring seems webformish , trying find right mvc hook. in case creating custom view engine correct extensibility hook this. if think engine deci...

excel - getting started with processing data with python -

i have excel spreadsheet of 3 million cells. asked following question , liked answer saving spreadsheet csv , processing python: solution perform lots of calculations on 3 million data points , make charts is there library can use read csv matrix or should write 1 myself? does python speak vba @ all? after done processing data, simple put in form of csv can open in excel viewing? is there library can use read csv matrix or should write 1 myself? the csv module handles want. does python speak vba @ all? iron python might. after done processing data, simple put in form of csv can open in excel viewing? the csv module handles want. suggestion: read this: http://docs.python.org/library/csv.html

.NET: What attribute would you use to describe an Enum value? -

lets have enum: public enum applicationstatus <foo("active")> active = 1 <foo("inactive")> inactive = 2 <foo("retired")> retired = 3 <foo("in development")> indevelopment = 4 end enum what attribute should use in place of foo plain-text descriptions of enum? i've used description mine, in cases when enumeration needs display differently, otherwise displays string of enum value. i've use method checks case of each character in enum item , if it's uppercase character after 1st, adds space before character. public enum applicationstatus active = 1 inactive = 2 retired = 3 indevelopment = 4 <description("radical display name")> radical = 5 end enum

objective c - Ipad Error: 'Program received signal EXC_BAD_ACCESS' -

i getting error when deploy ipad. not occur in simulator. my ipad app has 3 uiwebviews. majority of application written web app, , uses css make more native. links clicked in various web views open in 1 depending on value of request variable "ipadtarget." - (bool)webview:(uiwebview *)webview shouldstartloadwithrequest:(nsurlrequest *)request navigationtype:(uiwebviewnavigationtype)navigationtype { nsurl *url = [request url]; //extract value request variable 'ipadtarget' in url string. nsstring *test = [url query]; int index = [test rangeofstring:@"ipadtarget="].location; int target = index + 11; nslog(@"%i", target); char c = [test characteratindex:target]; nslog(@"%c",c); if (navigationtype == uiwebviewnavigationtypelinkclicked) { if (c == '1') { [viewone loadrequest:request]; return no; } else if (c == '2') { [viewtwo loadrequest:request]; return no; } else if (c == '3...

c# - update wpf datagrid cell from other thread -

i'm trying implement simple spreadsheet using wpf datagrid. when users input formula in cell, engine calculates formula , update cell calculated value. of calculations handle take long time, want calculate in other threads. i tried implement using celleditending event below. (the itemssource of datagrid1 bound datatable dtab.) private void datagrid1_celleditending(object sender, datagridcelleditendingeventargs e) { action calc = () => { int r = datagrid1.items.indexof(e.row.item); int c = datagrid1.columns.indexof(e.column); dtab.rows[r].setfield(c, "x"); // calculated value }; action update = () => { if (datagrid1.dispatcher.checkaccess()) calc(); else datagrid1.dispatcher.begininvoke(calc); }; //update(); // run same ui thread task.factory.startnew(update); // run different thread } when update cell value same ui thread, cell updated value "x", different thread, not. h...

xpath - What is // in XSLT? -

what // in xslt? (e.g. $currentpage//node ) what // in xslt? e.g. ($currentpage//node) in xpath abbreviation: // short /descendant-or-self::node()/ the value of attributes of xslt instructions (such select attribute) must xpath expression. therefore, ($currentpage//node) stands for ($currentpage/descendant-or-self::node()/node) this selects elements named node children of nodes either contained in variable $currentpage or descendents of nodes contained in variable $currentpage . do note in provided expression node() node-test (it selects node types on descendant-or-self:: axis, such elements, text nodes, comments , processing-instructions. on other side, somepath/node shorthand somepath/child::node , selects elements named node children of context node. i recommend not use name node element in order avoid confusion.

c# - Randomize a List<T> -

what best way randomize order of generic list in c#? i've got finite set of 75 numbers in list assign random order to, in order draw them lottery type application. shuffle (i)list extension method based on fisher-yates shuffle : private static random rng = new random(); public static void shuffle<t>(this ilist<t> list) { int n = list.count; while (n > 1) { n--; int k = rng.next(n + 1); t value = list[k]; list[k] = list[n]; list[n] = value; } } usage: list<product> products = getproducts(); products.shuffle(); the code above uses criticised system.random method select swap candidates. it's fast not random should be. if need better quality of randomness in shuffles use random number generator in system.security.cryptography so: using system.security.cryptography; ... public static void shuffle<t>(this ilist<t> list) { rngcryptoserviceprovider pro...