Posts

Showing posts from February, 2014

awtrobot - Java print screen program -

i trying use robot in java make image file of print screen. far have: robot robot = new robot(); rectangle screenrect = new rectangle(toolkit.getdefaulttoolkit().getscreensize()); bufferedimage capture = new robot().createscreencapture(screenrect); imageio.write(capture, "bmp", new file("printscreen.bmp")); but can't seem create file. s/printscreen.bmp/"printscreen.bmp"

xslt - How to add @xml:base to my .xml files? -

i need stylesheet convert docbook xml files include xml:base element section tags. how go doing (since xml:base needs system , node info???) input: <section xmlns="http://docbook.org/ns/docbook" xml:id="voidvisit" version="5"> <title>void</title> <section> <title>screenshot</title> <mediaobject> <imageobject> <imagedata fileref="screenshots/dialog.png" /> </imageobject> </mediaobject> </section> </section> output: ... <section xml:id="void" version="5" xml:base="file:/c:/projects/my/proj/trunk/spec/module/components/void.xml"> <title>void</title> <section> <title>screenshot</title> <mediaobject> <imageobject> <imagedata fileref="screenshots/dialog.pn

xml - Java: Oracle XMLType + JDBC -

how can oracle xmlelement jdbc? java.sql.statement st = connection.createstatement(); // works oracle.jdbc.oracleresultset rs = st.execute("select xmlelement("name") dual"); rs.getstring(1); // returns null, why? oracle.sql.opaque = (opaque) rs.getobject(1); // works, wtf opaque ? basically, want read string <name> </name> or whatever xml formatted output. fail cast output reasonable. weird oracle.sql.opaque works, totally dont know that. tostring() not overriden! any ideas? how read oracle's (i using oracle 10.0.2) xmlelement (xmltype) ? you can't. oracle's jdbc driver not support jdbc xml type properly. the thing can do, convert xml part of query: select to_clob(xmlelement("name")) dual then can retrieve xml using getstring() alternatively can use xmlelement("name").getclobval() , again part of query , can accessed string within java class

How do I immediately load another page in JSP/Spring? -

i'm not experienced in jsp. have application, uses spring framework, search. show these results in jsp page. when search returns 1 item, want jump page shows information item. is possible in jsp/spring? i've seen tags like: <c:redirect url="/somepage.html"/> that's jsp file. want (this naive bit of code)... <c:when test="${cmd.totalresults = 1}"> <c:redirect url="/loaditeminfo.html?id=someid"/> </c:when> thanks in advance advice , help! can omit regarding parameters involved; can figure out. i'm asking making happen. page loads. page sees there 1 result. page goes page result, happens anyway when user clicks search result. saves click. you should check number of items logic in spring controller not in jsp file. inside spring controller may have this: if(items.size==1){ //query items[0] info return new modelandview("iteminfo",model); } else{ return new model

regex - How to compare Unicode characters in SQL server? -

hi trying find rows in database (sql server) have character é in text executing following queries. select count(*) t_question patindex(n'%[\xe9]%',question) > 0; select count(*) t_question patindex(n'%[\u00e9]%',question) > 0; but found 2 problems: (a) both of them returning different number of rows , (b) returning rows not have specified character. is way constructing regular expression , comparing unicode correct? edit: the question column stored using datatype nvarchar . following query gives correct result though. select count(*) t_question question n'%é%'; why not use select count(*) t_question question n'%é%' ? nb: like and patindex not accept regular expressions. in sql server pattern syntax [\xe9] means match single character within specified set . i.e. match \ , x , e or 9 . of following strings match pattern. "elephant" "axis" "99.9"

c# - Associate data with a thread: How do you do that? -

while writing aysnc controllers in asp.net mvc2, ran against situation had call asyncmanager.sync . got me wondering: when retrieve httpcontext.current , what's going on? how asp.net know httpcontext i'm after? how current context associated thread, , how retrieved? thread scoped storage used, called thread local storage . this mechanism allows data affinitized thread i.e. thread allocates data sees data. useful creating called ambient programming models such httpcontext.current , transactionscope. mechanism allows data accessible @ time on executing thread without having "tramp" data through method parameters instance. it's elegant solution context\orthogonal problems. there number of ways of using tls including threadstaticattribute , thread.setdata\getdata.

asp.net - Report Viewer Control Version 10 Not Paging -

i upgraded report viewer control version 9 version 10, , paging controls don't work. whether use next button, last page button, or type in page number, after postback page reset one. i know dataset has more 1 page of data, , returned me in full if export excel via report toolbar. the chrome javascript console shows no errors, , inspection of postback generated paging control in fiddler yields nothing wrong. when manually set page number 2 , inspect form fields in fiddler, see form field looks currentpage property, , value indeed 2. when reloading page, number reset 1. the report viewer displays local rdlc report. opened in vs2010 , opted upgrade format, in case, no avail. i have tried async rendering on , off, no good. i using ajaxcontroltoolkit script manager on master page, instead of asp:scriptmanager. a possibly related issue: getting assembly load error looking system.web.ajax. unable find dll in add reference dialog. ended copying bin folder, machine on proble

Populate text boxes in VB.net -

i retrieving single row (using method) table, want populate each column row text boxes. how can done in vb.net. thanks help. for = 0 table.rows.count -1 dim row datarow = table.rows(i) dim txt new textbox txt.text = row(i) panel1.controls.add(txt) next where panel1 flowlayoutpanel(it automatically positions textboxes you)

ruby on rails - Auto-removing all newlines from Haml output -

i'm using haml in rails 3 app, , newlines drive me nuts! example, %span foo renders as <span> foo </span> but i'd rather want <span>foo</foo> the reason (apart being cleaner xml) newlines problem selenium tests because mess ability xpath queries "//span[.='foo']" . i'd have write '\nfoo\n' instead (ew!), or use //span[contains(text(), 'foo')] , matches broadly. i know use alligator operators ("<" , ">") strip whitespace, since don't ever have case want newlines appear in output, i'd end adding them mechanically @ end of each line. , seems undry. so see 2 solutions: force haml never emit newlines unless come ruby expression. see nuke_inner_whitespace / nuke_outer_whitespace variables spread around haml code might job, i'm not sure how change them without resorting gratuitous monkey-patching. hook rails apply gsub!("\n", "") re

Calling external jQuery functions w/o document.ready(); -

kinda new jquery , looking on how keep script in 1 external file , not have nested in document.ready();. i'm hoping able call functions specific pages , have rest handle ready();. i'm not 100% sure best practice call function page either :/ thanks. there nothing wrong having multiple document.readys i add unique id each page, , have javascript check id exists before executing. can create simple wrapper function check , waits document.ready: var pageready = function (id, callback) { $(function () { if ($(id).length) { callback(); } }); }; then, similar document.ready, can have: pageready("#home-page", function () { // code run home page here }); pageready("#search-page", function () { // code run search page here }); just remember add ids... <body id="home-page">

How to disable R from changing the "-" character into '.' character when writing to a file? -

i want write results of table file , names of columns contain '-' character, when write file replaces '-' '.'. function(result,path) { num<-0 for(i in 1:length(result[,1])) { if(length(which([result[i,]>0))>0) { temp<-which(result[i,]>0)] val<-paste(names(temp),sep="\n") write(val,file=paste(path,"/result",num,".txt",sep="")) num<-num+1 } } } do 1 know how disable option? my column names names of proteins of them written in way yer060w-a thank in advance. it takes special care make such entity. can use col.names argument , assign colnames(dfrm) it. > tst <- data.frame(`a-b`= letters[1:10], `1-2`=1:10, check.names=false) > colnames(tst) [1] "a-b" "1-2" > write.table(tst, file="tst.txt", col.names=colnames(tst) ) pasted editor: "a-b" "1-2" "1" "a"

Android/MonoDroid custom Ringtones question -

i trying figure out how take audio file assets folder (included androidasset) , add list of ringtones see when make call: this.startactivity(new intent(android.media.ringtonemanager.actionringtonepicker)); i adding ringtone via call: inputstream inputstream = assets.open("filename.mp3"); does know how accomplished? have been searching on , haven’t figured out. thank you something this: private void setasringtone(){ try { //open inputstream assets inputstream fis = assets.open("filename.mp3"); if (fis == null) return; //open file save ringtone in sd (/sdcard/android/data/com.your.package/) file path = new file(environment.getexternalstoragedirectory().getabsolutepath() + "/android/data/com.your.package/"); if(!path.exists()) path.mkdirs(); //create proper file file f = new

User management in asp.net without using cookie or session -

is possible perform user management (store user info, login , logout etc) without using session or cookie? thanks in advance. there cookieless sessions http://msdn.microsoft.com/en-us/library/aa479314.aspx if don't want server-state @ all, need keep passing state around in urls. login, can use http auth browser understands.

iphone - gamekit over the internet -

the gamekit on wifi documentation talks local wifi , it's built on top of bonjour. mean not work on internet, locating user/players in different subnet, different isp ... etc if need connect players/users on internet in general assume need setup server, right ? yes , game kit can used connect peers on internet. but in case application must respond peerpickercontroller:didselectconnectiontype: , handle private handshake protocol discover peers , establish communication. web service on server required (unless users type in ip address). good luck sam! references: apple ios reference library, game kit programming guide . sanford university online course, iphone development, lecture 17: bonjour, nsstream, gamekit (see @ 48 min 28 sec).

wpf - How to define a default tooltip style for all Controls -

i define style template when there validation errors , display first error message tooltip. it works fine when targeting specific control datepicker in following xaml. <style targettype="{x:type toolkit:datepicker}"> <style.triggers> <trigger property="validation.haserror" value="true"> <setter property="tooltip" value="{binding relativesource={relativesource self}, path=(validation.errors)[0].errorcontent}"/> </trigger> </style.triggers> </style> i cannot work control though, i.e. following doesn't give tooltip <style targettype="{x:type toolkit:control}"> <style.triggers> <trigger property="validation.haserror" value="true"> <setter property="tooltip" value="{binding relativesource={relativeso

java - How to get GWT to compile multiple modules? -

i've set new gwt project in netbeans 6.9 , created multiple gwt modules i've tried adding them in gwt.properties file follows: *# names of modules compile (separated space character) gwt.module=com.company.mymodule1 com.company.mymodule2 com.company.mymodule3* i'm getting error @ compilation time saying doesn't find second module. now, can compile fine 1 module. doesn't matter one. i'm doing wrong or it's bug in gwt/nbgwt ? i tried this: *# names of modules compile (separated space character) gwt.module=com.company.mymodule1 gwt.module=com.company.mymodule2 gwt.module=com.company.mymodule3* in case last module in list gets compiled. you need create gwt.xml file per module. then can compile of them ant task <target name="gwtc" depends="javac" description="gwt compile javascript"> <java failonerror="true" fork="true" classname="com.google.gwt.dev.compiler&

c# - How to make the gridcolumn have some text in it -

i using gridcontrol , has 4 columns. coded in such way validation occurs when column field empty. used string.empty . my problem occurs when user enters whitespace in column , saves. "empty" text gets saved , don't want happen. need column have text before can saved. how can prevent empty strings being saved? instead of string.empty can first trim() , apply string.empty.....or can use regex(regular expressions) validations.... check these links :- 1st link , 2nd link

Javascript "Unresponsive Script" adding Jquery event handlers -

i've created little javascript web page movember let users "shave" beard moustache, or off. i've done covering shaved picture grid of divs holding bearded picture differing offsets. when user moves mouse on 1 of divs, disappears, showing shaved skin in picture underneath. the problem in creating 4000 little divs, jquery.min.js script keeps popping "unresponsive script" error. i'm hoping can spot inefficient in code, or suggest how jquery take breath. tried having "loading..." spinning wheel gif show while code running, javascript threw hourglass gif never showed up. here's code: <script type="text/javascript"> var iserase = false; var iscover = false; var size = 4; var = 0; var j = 0; $(document).ready(function(){ (i = 0; < 400; += size) { (j = 0; j < 250; j += size) { $('#picture').append('<div class="piece" style="background-position: -' + j + 'px -' + +

android - I lost my .keystore file? -

ok folks.. long story short, developing on computer no longer have access to. able retrieve source code, not .keystore file used sign , publish application market (with several updates). i, , poor users, out of luck if ever want update? i know password used sign key (at least 1 of 3 be), can create another? there must way around this.. hard drive fail? faced same problem. trying restore via deleted files restoring tools, failed. so, there no other way: should issue application. generally, advise exists on keystores: "always up!"

Problem in Developing for multiple screen resolution in Android? -

i want develop android applications support multiple screen resolutions. have gone through support multiple screen resolution article. i tried creating folder layout-hdpi , had 1 layout file in that. layout file similar name in layout folder too. changed values in layout file in layout-hdpi changed values in layout file in layout folder. to more specific hierarchy this res | -->layout | --------> main.xml | -->layout-hdpi | --------> main.xml any change in main.xml under layout-hdpi changes value in main.xml under layout. can let me know why happening? i faced same issue, think copied actual layout , pasted in other directory, how ides map copied files , when save them changes applies on copies. try restarting ide , fixed.

java - Eclipse error: "The import XXX cannot be resolved" -

i'm trying work hibernate in eclipse. i'm creating new simple project , i've downloaded collegue project too, via cvs. both don't work, while on collegue's eclipse do. problem that, each import of hibernate class, eclipse says: the import org.hibernate cannot resolved but hibernate jars in build path, is: antlr-2.7.6.jar cglib-2.2.jar commons-collections-3.1.jar dom4j-1.6.1.jar hibernate3.jar hibernate-jpa-2.0-api-1.0.0.final.jar javassist-3.12.0.ga.jar jta-1.1.jar slf4j-api-1.6.1.jar try cleaning project going following menu item: project > clean... if doesn't work, try removing jars build path , adding them again.

Metric-fu in my Rails 3 app won't run -

installed metric-fu in rails 3 app putting in gemfile. when run rake task fails. error below, idea how solve anyone? $ rake metrics:all --trace (in /home/pma/documents/boss-mocha) ** invoke metrics:all (first_time) ** execute metrics:all parse error on value ")" (trparen) skipping app/views/software_projects/_form.html.erb parse error on value ")" (trparen) skipping app/views/instruction_items/_form.html.erb parse error on value ")" (trparen) skipping app/views/companies/_form.html.erb parse error on value ")" (trparen) skipping app/views/instructions/_form.html.erb parse error on value ")" (trparen) skipping app/views/company_groups/_form.html.erb parse error on value ")" (trparen) skipping app/views/replies/_form.html.erb parse error on value ")" (trparen) skipping app/views/replies/edit.html.erb parse error on value ")" (trparen) skipping app/views/devise/unlocks/new

c# - Convert a word into character array -

how convert word character array? lets have word "pneumonoultramicroscopicsilicovolcanoconiosis" yes word ! take word , assign numerical value it. = 1 b = 2 ... z = 26 int alpha = 1; int bravo = 2; basic code if (testvalue == "a") { debug.writeline("true found in string"); // true finalnumber = alpha + finalnumber; debug.writeline(finalnumber); } if (testvalue == "b") { debug.writeline("true b found in string"); // true finalnumber = bravo + finalnumber; debug.writeline(finalnumber); } my question how the word "pneumonoultramicroscopicsilicovolcanoconiosis" char string can loop letters 1 one ? thanks in advance what about char[] myarray = mystring.tochararray(); but don't need if want iterate string. can do for( int = 0; < mystring.length; i++ ){ if( mystring[i] ... ){ //do want here } } this works since string class implements it's own indexer

.net - Hit Test behavior -

i have following code public partial class mainwindow : window { public mainwindow() { initializecomponent(); } list<uielement> ucs = new list<uielement>(); private void window_previewmouseleftbuttondown(object sender, mousebuttoneventargs e) { ucs.clear(); point p = e.getposition((uielement)sender); visualtreehelper.hittest(this, null, new hittestresultcallback(myhittestcallback), new pointhittestparameters(p)); console.writeline("ucs.count = {0}", ucs.count); foreach (var item in ucs) { console.writeline("item: {0}", item.tostring()); } } hittestresultbehavior myhittestcallback(hittestresult result) { ucs.add(result.visualhit uielement); return hittestresultbehavior.continue; } } this window <window> <grid> <my:usercontrol1 horizontalalignment="le

iphone - Help needed for s7graphview -

Image
if have used s7graphview plotting graph want know changes in code maintaining incremental value of values been plot on x-axis. maintains according count of array being return it. want maintain incremental gap of 5 units. i replace in drawrect: of s7graphview class next lines (~220 line in s7graphview.m): if (xvaluescount > 5) { nsuinteger stepcount = 5; nsuinteger count = xvaluescount - 1; (nsuinteger = 4; < 8; i++) { if (count % == 0) { stepcount = i; } } step = xvaluescount / stepcount; maxstep = stepcount + 1; } else { step = 1; maxstep = xvaluescount; } with this code : if (xvaluescount > 5) { nsuinteger stepcount = 5 - 1; step = xvaluescount / stepcount; maxstep = stepcount + 1; } else { step = 1; maxstep = xvaluescount; } on demos7graphview project s7graph google code page gives me next result: hope helps.

c# - How to retrieve the selected date in window phone application? -

i developing window phone 7 application. new window phone 7 application development. have added datepicker control application. able select required date whichever want. want submit information in application through submit button along date selected through datepicker. unaware of how retrieve selected date. using following code <toolkit:datepicker valuechanged="datepicker_valuechanged" margin="296,0,0,552" /> now have following function private void datepicker_valuechanged(object sender, datetimevaluechangedeventargs e) { } in above function how should retrive date selected application ? can please provide me code or link through can resolve above issue ? you should give name datepicker: <toolkit:datepicker name="mydate" valuechanged="datepicker_valuechanged" margin="296,0,0,552" /> then, in code-behind: var date = (datetime) mydate.value;

php - Does VARCHAR size limit matter? -

possible duplicate: importance of varchar length in mysql table when using varchar (assuming correct data type short string) size matter? if set 20 characters, take less space or faster 255 characters? in general, varchar field, amount of data stored in each field determines footprint on disk rather maximum size (unlike char field has same footprint). there upper limit on total data stored within fields of index of 900 bytes ( 900 byte index size limit in character length ). the larger make field, more people try use purposes other intended - , greater screen real-estate required show value - practice try pick right size, rather assuming if make large possible save having revisit design.

silverlight 4.0 - Can you create an event in a user control, if so, how? -

i have created user control containing datepicker , want create event in user control linking datepicker datechanged event. custom user control used in itemscontrol. yes. add public event control. , add method looks delegates attached event. if there delegates, raise event. here's example: in user control: public partial class controls_usercomments : system.web.ui.usercontrol { // event delegates may listen public event eventhandler commentediting; protected void page_load(object sender, eventargs e) { // handle event in user control , bubble event delegates gridview_comments.rowcancelingedit += new gridviewcancelediteventhandler(gridview_comments_rowcancelingedit); } void gridview_comments_rowcancelingedit(object sender, gridviewcancelediteventargs e) { gridview_comments.editindex = -1; gridview_comments.databind(); // raise event attached delegates if (commentediting != null)

iphone - How to change TTLauncherItem's text label frame/position -

i need custom ttlauncheritem displaying text on of image. there way working? default looks like: +----+ | | +----+ text and want this: +----+ |text| +----+ thanks help! you can modify image parameter in ttlauncheritem init function. [[[ttlauncheritem alloc] initwithtitle:@":)" image:nil url:@"tt://tabbartest" candelete:no] autorelease]

bluetooth - Is it possible to communicate with an iPhone over a serial-bt-bridge? -

i have device rs-232 port , btm222-bt-serial bridge. possible communicate iphone using setup? does iphone have bluetooth serial port profile? it not directly possible. you have change rs322 device firmware (and possibly hardware) compatible apple accessory (joining apple mfi give more details). can done if can ground design change.

java - How to design Database for this situation? -

i'm working minimal game java , mysql. encountered difficulties how design tables correctly. need advices: let me specific, have 3 classes: node public class node { private integer id; private integer position; private integer foodtax; private boolean hastreasuremap; private integer currentplayer; // playerid treasure public class treasure { integer id; private integer position; // nodeid private integer goldvalue; player public class player { private integer id; private integer wealth; private integer strength; private integer start; private integer goal; private integer currentposition; // nodeid private integer currentgoal; // nodeid private vector<integer> path; private vector<integer> treasureids; private int currentmoveindex; graph<integer> telescope; i'm newbie mysql, , database in general. think have use foreign key in case. however, i'm still vague how implement it. besides, t

visual studio 2008 - Add custom version information to "Special Build Description" property of the final exe C# application -

application c# .net 3.5 wcf service. i'd dynamically add build information appear in "special build description" property of final exe. i.e. i'd right click on file , see information in version tab file. thanks in advance.

etl - ravendb from console app -

i'm trying raven working in rhino.etl console import date sql raven. i have raveninstaller: public class raveninstaller : iwindsorinstaller { public void install(iwindsorcontainer container, iconfigurationstore store) { container.register( component.for<idocumentstore>().implementedby<documentstore>() .dependson(new { connectionstringname = "someravenconnectionstring" }) .oncreate(doinitialisation) .lifestyle.singleton ); } static idocumentsession getdocumentsesssion(ikernel kernel) { var store = kernel.resolve<idocumentstore>(); return store.opensession(); } public static void doinitialisation(ikernel kernel, idocumentstore store) { store.initialize(); } } however - when call _documentsession.opensession() app hangs. is th

Using Amazon MapReduce -

how work exactly... if have data mining system built in php, how work differently on mapreduce on simple server? mere fact there's more 1 server doing processing? if code made partition work between multiple processes already, mapreduce adds ability split work among additional servers.

Can I add a property dynamically in javascript? -

is okay add properties object @ runtime? seems run okay there issues should aware of? i'm using 3rd party javascript api has object class, i've instantiated , added own property after instantiation, code below: for example can this: var car = function (id, type) { this.id = id; this.type = type; }; var mycar = new car(1,"nissan"); // can this: (needswork not property of object car) mycar.needswork = true; yea, called object augmentation. key feature in javascript.

c++ - While inserting nodes in heap how to use bubble up? -

following code doesnot bubbles larger value .can 1 out .the problem @ count++ . #include<iostream> using namespace std; class heap{ public: int count; heap(int c) { count=c; } int arr[10]; void insert(int num); void deletemax(); void print(); }; void heap::insert(int num){ if(count==10){ cout<<"heap full\n"; exit(1); } else{ arr[count]=num; count++; //the real problem arises here compiler adds 1 count , when code moves ahead sets position var count++ value , tries compare value @ arr[pos] parent whereas there no value @ place set uptill. } int pos=count; while(arr[pos]>arr[(pos-1)/2]){ int temp; temp=arr[pos]; arr[(pos-1)/2]=temp; pos=(pos-1)/2; } } void heap::print(){ for(int i=0; i<10; i++){ cout<<arr[i]<<endl; } } int main(){ heap h(0); int a; int b=0; while(b<10){

ios4 - How to put or create UItabbar above UItoolbar using UINavigation based application in iphone? -

i want create tabbar based application..but want tab bar should above toolbar....means below screen 1. first toolbar banner add 2.then above toolbar,ther 1 tab bar 3 tabs 3.now middle of screen there view 4. finaly on top of screen there 1 navigation bar create 1 toolbar on bottom of screen , pro-grammatically create tabbar view height = self.view.frame.size.height - tool bar height, width = self.view.frame.size.width, x = 0, y = 0, , add subview on view

build R pacakge for windows -ERROR: compilation failed for package xxx -

i having trouble build dummy testing package r on windows. testing purpose,in r terminal, input: a=rnorm(10) package.skeleton("pkgtest") then run r cmd check pkgtest on dummy package , got error like * using r version 2.12.0 (2010-10-15) * using platform: i386-pc-mingw32 (32-bit) * using session charset: iso8859-1 * checking file 'pkgtest/description' ... ok * checking extension type ... package * package 'pkgtest' version '1.0' * checking package dependencies ... ok * checking if source package ... ok * checking executable files ... ok * checking whether package 'pkgtest' can installed ... error installation failed. edit ,the full log file: * installing *source* package 'pkgtest' ... ** libs cygwin warning: ms-dos style path detected: c:/r/r-212~1.0/etc/i386/makeconf preferred posix equivalent is: /cygdrive/c/r/r-212~1.0/etc/i386/makeconf cygwin environment variable option "nodosfilewarning" turns off wa

c# - Calling Invoke/BeginInvoke from a thread -

i have c# 2.0 application form uses class contains thread. in thread function, rather call event handler directly, invoked. effect owning form not need call invokerequired/begininvoke update controls. public class foo { private control owner_; thread thread_; public event eventhandler<eventargs> fooevent; public foo(control owner) { owner_ = owner; thread_ = new thread(foothread); thread_.start(); } private void foothread() { thread.sleep(1000); (;;) { // invoke performed in thread owner_.invoke((eventhandler<eventargs>)internalfooevent, new object[] { this, new eventargs() }); thread.sleep(10); } } private void internalfooevent(object sender, eventargs e) { eventhandler<eventargs> evt = fooevent; if (evt != null) evt(sender, e); } } public partial class form1 : form {

java - Cross-platform file path building and representation -

i in refactoring stage project working on , make improvements how build , represent file system paths. things should take consideration when representing relative paths in java code ensure compatibility on ubuntu, osx, , windows 7. currently instance of file referencing "myproject/foo/bar.f" have code along lines of: file bar = new file(projectdirectory + "/" + fooresourcedirectory + "/" + barname); this seems wrong several reasons, of best practices? perhaps use constructors provided sort of thing: new file(parent, child) you have "nest" them, it's trivial handle (e.g. make function path built taking string... .) see file constructors.

Perl - Summarize Data in File -

whats best way summarize data file has around 2 million records in perl? for eg: file this, abc|xyz|def|egh|100 abc|xyz|def|fgh|200 sdf|ght|www|rty|1000 sdf|ght|www|tyu|2000 needs summarized on first 3 columns this, abc|xyz|def|300 sdf|ght|www|3000 chris assuming there 5 columns, fifth of numeric, , want first 3 columns key... use warnings; use strict; %totals_hash; while (<>) { chomp; @cols = split /\|/; $key = join '|', @cols[0..2]; $totals_hash{$key} += $cols[4]; } foreach (sort keys %totals_hash) { print $_, '|', $totals_hash{$_}, "\n"; }

java - Playing live http stream in vlcj -

i'm trying use vlcj play live internet radio stations in project. i've played around sample programs few hours, cannot either sample programs or programs i've played around play stream url. an example of url i'm trying play is: http://network.absoluteradio.co.uk/core/audio/wmp/live.asx?service=vr is there special have in order vlcj play stream? couldn't find in api. (assuming can because can played through vlc media player!) thanks lot ok, mrl have provided http://network.absoluteradio.co.uk/core/audio/wmp/live.asx?service=vr mms server may pull asx (xml) metafile may contain @ least 1 sub-item. http://all-streaming-media.com/faq/streaming-media/metafiles-asx-advanced-stream-redirector.htm to able play type of streaming media , go through each sub-item, need following code snippet: videopanel.getmediaplayer().setrepeat(true); videopanel.getmediaplayer().setplaysubitems(true); videopanel.getmediaplayer().preparemedia(media, options); try {

if statement - Erlang equivalent to if else -

i have 2 parts of code want execute. both conditionals if value1 < n else if value1 >= n if value2 < n else if value2 >= n i want @ 1 statement of each execute. how if work in erlang? there no else. use multiple guards, looks have 4 if statements. in groups of 2. if condition code; if other condition code end. i syntax error. the form if is: if <guard 1> -> <body1> ; <guard 2> -> <body2> ; ... end it works trying guards in if-clauses in top-down order (this defined) until reaches test succeeds, body of clause evaluated , if expression returns value of last expression in body. else bit in other languages baked it. if none of guards succeeds if_clause error generated. common catch-all guard true succeeds, catch-all can true. the form case is: case <expr> of <pat 1> -> <body1> ; <pat 2> -> <body2> ; ... end it works first evaluating , tr

orm - Fluent NHibernate Mapping (one to one with conditional) -

i'm trying "clean" poorly designed database structure (at least in orm). the table structure this: table: members memberid (int pk) username (varchar) table: addresses addressid (int pk) memberid (int, not set fk - awesome) firstname (varchar) lastname (varchar) addressline1 (varchar) isbillingaddress (bit) so created 2 classes (entities), 1 customer , 1 address. public class customer { public virtual int customerid { get; set; } public virtual string firstname { { return billingaddress.firstname; } set { billingaddress.firstname = value; } } public virtual string lastname { { return billingaddress.lastname; } set { billingaddress.lastname = value; } } public virtual address billingaddress { get; set; } public virtual address shippingaddress { get; set; } } public class address { public virtual customer customer { get; set; } public virtual int addressid { get; set; } public virt

apache2 - CakePHP HTML helper CSS tag and Apache Alias -

as relative newcomer cakephp, i'm hoping advice on "right" way of configuring apache , cakephp find included files (css, javascript, etc). if server's documentroot set /var/www , install , configure cakephp in /var/www/somepath/cakeapp can access application expected @ url http://example.com/somepath/cakeapp . however, if use html helper generate css link tag in default layout, start run trouble. example, code echo $html->css('styles'); produces tag: <link rel="stylesheet" type="text/css" href="/somepath/cakeapp/css/styles.css" /> however, css lives in /somepath/cakeapp/app/webroot/css . if cakephp app thing on domain, point documentroot @ /var/www/somepath/cakeapp/app/webroot documentation suggests , (presumably) well. however, that's not option me. is there accepted correct way of configuring apache , cakephp html helper can produce correct link tag? edit: feel there must combination of

c# - Open file from byte array -

i storing attachments in applications. these gets stored in sql varbinary types. i read them byte[] object. i need open these files dont want first write files disk , open using process.start() . i open using inmemory streams . there way to in .net. please note these files can of type you can write bytes file without using streams: system.io.file.writeallbytes(path, bytes); and use process.start(path); trying open file memory isn't worth result. really, don't want it.

Is there a way to automate fixing missing parens in Emacs? M-x fix-parens? -

updated following dirk's suggestion after finding out emacs' check-parens , show-parens modes in previous question , value of fix-missing-parens mode, comment raised point nice automate process of finding , adding missing or parens. is there way automate fixing such mismatched parens? mark region , call m-x indent-region -- indent code comprises parens (and more).

android - How to render a tricky ass NinePatch? -

this thebasic idea, image ugly , pixelated. why??? public class main extends activity { /** called when activity first created. */ @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); imageview iv = (imageview) findviewbyid(r.id.iv); bitmap bmap = bitmapfactory.decoderesource(getresources(), r.drawable.btn_default_normal); ninepatchdrawable npd = new ninepatchdrawable(bmap, bmap.getninepatchchunk(), new rect(0,0,512,512), "name"); npd.mutate(); npd.setbounds(new rect(0,0,512,512)); npd.invalidateself(); bitmap bp = bitmap.createbitmap(512,512, bitmap.config.rgb_565); canvas canvas = new canvas(bp); npd.draw(canvas); fileoutputstream ofo=null; try { ofo = openfileoutput("image", mode_world_readable); } catch (ioexception e) { e.printstacktrace(); } bp.compress(bitmap.compressformat.png, 100, ofo); inte

update database from gridview having dropdownlist Asp.net -

webpage: i have gridview , have 5 dropdownlist on it, mentioned below. first column normal boundfield (client list) , rest dropdownlist (contains userid) , default value on dropdownlist "select user". database: first column has clientname , rest 5 columns null. on button click want to: 1) update rows database user have made changes (any dropdownlist in row) on form particular client. 2) , if there userid present in database client should selected on dropdownlist on form. <asp:gridview id="gridview" runat="server" autogeneratecolumns="false" onrowdatabound="gridview_rowdatabound"> <columns> <asp:boundfield datafield="name" headertext="name" /> <asp:templatefield headertext="csm"> <itemtemplate> <asp:dropdownlist datasource= '<%# getcsm()%>' datatextfield="userid" datavaluefield="userid" id =&qu

Best way to generate java with python? -

whats best way generate java python? i want write decorator generates java code call json version of function (i can use existing decorators export json api). whats best way generate java, should consider stuff fsms here? ideally can write code once, server , generate code interface various languages (java first). edit (pulled comment on deleted answer): java code running on android, while python code in django server... also, want able statically generate java code, , have part of api people can use. you can create java code same way webapps create html: template. can have java source code compiled bytecode using regular java compiler ( see: package javax.tools ) not best option, option ( , quite simple btw )

url rewriting - How to write a url rewrite in nginx? -

i want people type in http://www.myweb.com/like/1234456 redirect http://www.myweb.com/item.php?itemid=1234456 i wrote in config doesn't work. location = ^~/like/ { rewrite ^1234456 ../likeitem.php?item=1234456break; return 403; } this test. haven't used $ matching yet. i restart ngnix server still.. doesn't redirect. the code above not work because of missing $ , poor use of return command. code above works nginx, including version 0.8.54. format below : desiredurl actual url nginx_rule they must inside location / {} http://example.com/notes/343 http://example.com/notes.php?id=343 rewrite ^/notes/(.*)$ /notes.php?id=$1 last; http://example.com/users/blackbenzkid http://example.com/user.php?username=blackbenzkid rewrite ^/users/(.*)$ /user.php?username=$1 last; http://example.com/top http://example.com/top.php rewrite ^/top?$ /top.php last; complex , further http://example.com/users/blackbe

C++ error: "Array must be initialized with a brace enclosed initializer" -

i getting following c++ error: array must initialized brace enclosed initializer from line of c++ int cipher[array_size][array_size]; what problem here? error mean? below full code: string decryption(string todecrypt) { int cipher[array_size][array_size] = 0; string ciphercode = todecrypt.substr(0,3); todecrypt.erase(0,3); decodecipher(ciphercode,cipher); string decrypted = ""; while(todecrypt.length()>0) { string unit_decrypt = todecrypt.substr(0,array_size); todecrypt.erase(0,array_size); int tomultiply[array_size]=0; for(int = 0; < array_size; i++) { tomultiply[i] = int(unit_encrypt.substr(0,1)); unit_encrypt.erase(0,1); } for(int = 0; < array_size; i++) { int resultchar = 0; for(int j = 0; j<array_size; j++) { resultchar += tomultiply[j]*cipher[i][j]; } de

visual studio - Are there any drawbacks to having 1 solution per project -

we working on big application, comprising around 100 projects (40 views, 40 controllers/models, 20 utilities libraries). have outsourced bulk of work , deliverables come in randomly. when deliverable (a project), need run fxcop, stylecop, associated unit-tests, etc, etc. before committing source control. make easier, have mandated every project has solution file. allows run automated script on solution file tests before checking in. my question "can think of drawbacks having 1 solution each project?". drawbacks have discussed include: additional maintenance required developers. doesn't bother have outsourced development on fixed-price contract. sourcesafe bindings in solution file. have been huge issue, luckily migrated tfs year ago. we're in similar boat 200 projects, many of them common use, accross our various solutions of varying sizes. while disadvantage load time, 1 advantage debugging - i.e. if code calling other assemblies, it's

c# - Passing BeginInvoke as a parameter -

suppose want have method passes begininvoke method of object parameter. how that? call looks this: myrandommethod(somecontrol.begininvoke); what method definition myrandommethod be? part of problem begininvoke has overloads, compiler gets confused 1 try pass parameter. maybe need find way version of begininvoke referring to? (though imagine decided parameter type) myrandommethod have have parameter delegate matches 1 of overloads somecontrol.begininvoke . example: public void myrandommethod(func<delegate, iasyncresult> foo) or public void myrandommethod(func<delegate, object[], iasyncresult> foo) (but please don't overload myrandommethod both of these signatures, otherwise you're asking confusion.)

c++ - How to create openCV image of certain (R, G, B) color and get that color name? -

i need create image filled (r,g,b) color. , color name (r,g,b) = black or red , on. can such thing opencv, , how it? opencv doesn't create images color, easiest way either fill or draw filled rectangle chosen color. see http://opencv.willowgarage.com/documentation/drawing_functions.html specifically http://opencv.willowgarage.com/documentation/drawing_functions.html#rectangle there isn't (afaik) function return color name, easiest way list of colors somewhere , check rgb values against pixel. if need closest rather exact match (rememebr there aren't names 244bit colors!) @ hsv color space

What is userdata and lightuserdata in Lua? -

what userdata , lightuserdata in lua? where need it? i have been trying wrap head around time now, can't seem find tutorials/explanations understand. why need them, why can't directly bind c functions lua metatables? a userdata garbage-collected value of arbitrary size , content. create 1 c api, lua_newuserdata() , creates , pushes on stack , gives pointer content initialize see fit c. it comparable calling malloc() . key distinction malloc() never need call free() , rather allow last reference evaporate , garbage collector reclaim storage eventually. they useful holding data useful c, must managed lua. support individual metatables, key feature allows binding c or c++ objects lua. populate metatable methods written in c access, modify, and/or use content of userdata, , result object accessible lua. example of io library , stores c file * pointers in userdata, , provides bindings implement familiar read , write , similar methods. implementing __gc m

svn - Can I (and how to) apply a patch created from trunk to a branch? -

i working on trunk , changed did thought others might need them created patch before committing. now fellow dev working on branch (which comes trunk couple of weeks back) needs changes go on new server. i'm trying apply patch tortoise svn does'nt seam disparities of working copies. have : my trunk @ : d:\svn\trunk the branch @ : d:\svn\branches\thebranchineedtopatch am trying impossible ? there i'm missing ? can apply trunk patch branch working copy ? thanks help! perquisite: let's working on branch. check use svn info . url should pointing branch then can merge changes trunk branch using merge command svn merge -r from_revision:required_revision url/to/trunk . or svn merge -r 26:32 url/to/trunk . this bring change sets rev 26 32 of trunk branch. ah, there discussion on how tortoisesvn: using tortoisesvn how merge changes trunk branch , vice versa?

Regex expression to parse an interesting CSV? -

i need parse csv file using awk. line in csv this: "hello, world?",1 thousand,"oneword",,,"last one" some important observations: -field inside quoted string can contain commas , multiple words -unquoted field can multiple worlds -field can empty having 2 commas in row any clues on writing regex expression split line properly? thanks! as many have observed, csv harder format first appears. there many edge cases , ambiguities. example ambiguity, in example, ',,,' field comma or 2 blank fields? perl, python, java, etc better equipped deal csv because have tested libraries same. regex more fragile. with awk, have had success this awk function. works under awk, gawk , nawk. #!/usr/bin/awk -f #************************************************************************** # # file in public domain. # # more information email lorancestinson+csv@gmail.com. # or see http://lorance.freeshell.org/csv/ # # parse csv string array. # numb