Posts

Showing posts from June, 2010

c++ - How much impact (time) can a single 'if' statement have within a tight loop? -

i'm working on application in c++ uses tight loop iterate through states in our fsm . right now, because of tight loop, uses 100% cpu, , our customers don't that. wanted try putting sleep(1) in tight loop loosen up, we're worried that make sleep long between states our large customers (whose states change quickly!). thinking of trying this: if(smallcustomer) { sleep(1); } and smallcustomer defined somewhere else when program started up. 'if' statement slow things down as sleep would, , defeating own purpose? your implication fsm shouldn't need 100% of cpu, leads me assume spending lot of time doing nothing except checking see if need move next state or not. worried sleeping "too long" larger customers, means concerned event missed: queue filling, mouse click, packet being received, completion of disk i/o, key being pressed, whatever. should refactor trigger asynchronously on event (or events) instead of hogging cpu doing nothi

php - How do I get next month date from today's date and insert it in my database? -

i have 2 columns in db: start_date , end_date , both date types. code updating dates follows: $today_date = date("y-m-d"); $end_date = date("y-m-d"); // date +1 month ?? $sql1 = "update `users` set `start_date` = '".$today_date."', `end_date` = '".$end_date."' `users`.`id` ='".$id."' limit 1 ;"; what best way make $end_date equal $start_date + 1 month? example, 2000- 10 -01 become 2000- 11 -01. you can use php's strtotime() function: // 1 month today $date = date('y-m-d', strtotime('+1 month')); // 1 month specific date $date = date('y-m-d', strtotime('+1 month', strtotime('2015-01-01'))); just note +1 month not calculated intuitively. appears add number of days exist in current month. current date | +1 month ----------------------------------------------------- 2015-01-01 | 2015-02-01 (+31 days) 2015-01-15 | 2015-02-15

sql - Search stored procedures/functions in all databases -

i want search specific text in procedures/functions etc. in databases. managed create required query answer looks object_definition(object_id(specific_name)) returns null dbs except current one. sp_msforeachdb 'select ''?'' db, specific_name, object_definition(object_id(specific_name)) [?].information_schema.routines' the problem object_id cannot used way. works on current database. try returning routine_definition directly information_schema.routines. have limit of 4000 characters. i'll try find other answer on gives workaround using ms metadata views. have @ this: can search sql server 2005 stored procedure content?

winforms - How to pause for user control in C#? -

i made little program while reading head first c# . i'm trying program pause user set numericupdown control level of difficulty. here's code... namespace wack { public partial class form1 : form { public int level; mole mole; random random = new random(); public form1() { initializecomponent(); mole = new mole(random, new mole.popup(molecallback)); messagebox.show("select level"); if (level == 1) { timer1.interval = random.next(500, 500); } if (level == 2) { timer1.interval = random.next(400, 400); } if (level == 3) { timer1.interval = random.next(300, 300); } timer1.start(); } private void timer1_tick(object sender, eventargs e) { timer1.stop(); togglemole();

branch - Mercurial, "Branching with bookmarks" -

i read document: a guide branching mercurial , section titled branching bookmarks . it says: now you’ve got 2 bookmarks (essentially tag) 2 branches @ current changeset. to switch 1 of these branches can use hg update feature update tip changeset of branch , mark working on branch. when commit, move bookmark newly created changeset. i tried this, ended moving both bookmarks @ same time. is guide wrong, outdated, or did wrong? note know having bookmarks on separate branches moves bookmark related branch i'm working on, guide (which lot of people says definite guide this) says above text, indicates should've worked "telling" mercurial bookmark (branch) i'm working on. testing shows otherwise though. any ideas? example: > hg init > echo 1 >test.txt > hg commit -m "initial" --addremove adding test.txt > hg bookmark main > hg bookmark feature > hg log changeset: 0:c56ceb49ee20 tag: feature tag:

iphone - Is it possible to solve a non-square under/over constrained matrix using Accelerate/LAPACK? -

is possible solve non-square under/over constrained matrix using accelerate/lapack? such following 2 matrices. if variables under constrained should equal 0 instead of being infinite. so in under constrained case: a, d & e equal 0, while b, c & f equal -1. in on constrained case variables equal -1. under constrained: ____ ____ | (a) (b) (c) (d) (e) (f) | | -1 0 0 1 0 0 | 0 | | 1 0 0 0 -1 0 | 0 | | 0 -1 1 0 0 0 | 0 | | 0 1 0 0 0 -1 | 0 | | 0 1 0 0 0 0 | -1 | |____ ____| over constrained: ____ ____ | | | -1 0 0 1 0 0 | 0 | | 1 0 0 0 -1 0 | 0 | | 0 -1 1 0 0 0 | 0 | | 0 1 0 0 0 -1 | 0 | | 0 1 0 0 0 0 | -1 | | 0 0 1 -1 0 0 | 0 | | 1 -1 0 0 0 0 | 0 | |____ ____| ye

Enabling scrollbar in EditText Android -

i have edittext on layout. below attributes have: <edittext android:id="@+id/entryidea" android:layout_width="fill_parent" android:layout_height="225sp" android:gravity="top" android:background="@android:drawable/editbox_background" android:scrollbars="vertical"/> however, can see scrollbar can't scroll mouse/touch. thought may works if put corresponding listener since works on textview. apparently, isn't. edittext et = (edittext)findviewbyid(r.id.entryidea); et.setmovementmethod(new scrollingmovementmethod()); can guys me on this? thank in advance. sammy in xml try setting edittext height not in layout_height , rather use android:lines attribute (btw, using sp not practice when setting size except font size. using dp/dip more natural in case). meanwhile set layout_height wrap_content . otherwise xml presented (with changes i've mentioned) worked fine me without s

css3 emulation in ie6 and others -

is there somewhere 1 trick pony make nice feature of css3 (shadow, glow, round corner) , make ie6 compatible /look alike... i have try that ... oh boy it's ugly !... looking more javascript file ot else it's best thing have find far... still dont crazy http://www.smashingmagazine.com/2010/04/28/css3-solutions-for-internet-explorer/

soundpool - How do I know if a sound is finished playing in android? -

how know if sound has finished playing? i want play 2 sounds want 1 sound play , wait until 1st sound done before 2nd starts. also, if wanted else when sound finished show next view in view flipper, that? right i'm using soundpool play sounds. use mediaplayer class , oncompletionlistener

in jquery, how to make the right click of the mouse have the same behavior of left click -

&lta id="link1" href="link1"&gtlink1&lt/a&gt what want realize: when right click or left click these link, both go linked pages. have several questions: how can href jquery in firefox , ie? how can identify mouse event in firefox , ie, event.which has different behaivors in firefox , in ie thank much to href , attribute of a tag, can use var the_href = $('#link1').attr('href'); this works on major browsers.

database - ms-access: Why isn't this relationship not working? -

Image
just started today understanding relations between ms access databases. can figure out why isnt working? i can explain lot in way, think pictures says more 1000 words when have relationship set up, little plus sign in datasheet (third picture) , when click sign, see records matching relationship field (column). if there no matching records, can add them, indicated asterisk (*) the plus sign show related records. if have used relational integrity, can add records 'many' table have identical foreign key (matching field) 'one' table. not idea work tables, should use forms. if set form based on 'one' table , add subform based on 'many' table, foreign key filled in automatically (the wizard set link child , master fields you).

security - Can I use PBKDF2 to generate an AES256 key to encrypt and implicitly authenticate? -

i have 2 devices , want set secure communication channel between them. shared secret (7- 20- character ascii) passphrase. if use pbkdf2 (from rfc 2898) common salt, iterations, , passphrase generate aes256-cbc key , iv on both sides, think can authenticate user , provide encrypted channel in 1 step. true, or there reason why i've seen people use pbkdf2 verify passwords? my reasoning both sides need know passphrase generate same key , iv. if device b can decrypt data device a, both have demonstrated have same passphrase. pbkdf2 fine way generate common key shared secret (you should not generating iv in such way though - iv should random, , sent alongside ciphertext). however, cbc not authenticating cipher mode. because attacker can take encrypted message , make predictable modifications it, without needing able read message or know key. such attacks have broken real world systems in past. you can use authenticating cipher mode, galois counter mode (gcm) instea

c# - .NET Uri class query missing the semicolon reserved character, simple workarounds? -

this http://msdn.microsoft.com/en-us/library/system.uri.query.aspx , ietf. org/rfc/rfc1738 .txt (pardon formatting, can't post more 1 url) suggest .net uri class not recognize semicolon acceptable character represent query in url. this requires 1 line or workaround, code clean. if there solution allows me not string parsing myself outside .net set of uri classes, i'd prefer that. there existing .net code handles semicolons recognizing them part of query in url? rfc 3986 agrees rfc 1738 (which updates) in defining query portion following question mark ( ? ), , in stating semicolon can used separate parameter-value pairs "applicable segment". in prospero uri (the case given in rfc 1738 semicolon shown used) semicolons indicate parameter , parameter value in path of uri - not query. http uris have semicolons used in queries, after ? , e.g. http://example.net/search?q=something;page=2 . unfortunately actual usage has never quite replaced & charact

ios - translation after rotation view using CGAffine -

i have view contain textfield. set view's orientation (void)devicerotated:(id)sender { uideviceorientation orientation = [[uidevice currentdevice]orientation]; if (orientation == uideviceorientationportrait) { cgaffinetransform affine = cgaffinetransformmakerotation (0.0); [self.view settransform:affine]; } if (orientation == uideviceorientationportraitupsidedown) { cgaffinetransform affine = cgaffinetransformmakerotation (m_pi * 180 / 180.0f); [self.view settransform:affine]; } else if (orientation == uideviceorientationlandscapeleft) { cgaffinetransform affine = cgaffinetransformmakerotation (m_pi * 90 / 180.0f); [self.view settransform:affine]; } else if (orientation == uideviceorientationlandscaperight) { cgaffinetransform affine = cgaffinetransformmakerotation ( m_pi * 270 / 180.0f); [self.view settransform:affine]; } } my problem want make view mov

android - 3D rotation while object being translated -

i've been playing android animation framework , found following 3d rotation sample code: http://developer.android.com/resources/samples/apidemos/src/com/example/android/apis/animation/transition3d.html http://developer.android.com/resources/samples/apidemos/src/com/example/android/apis/animation/rotate3danimation.html it pretty want want imageview rotate while it's being translated point point b , should rotate along it's own center(which moving) instead of center of container of screen. does know how that? -rachel well it's pretty close posted. you're multiplying rotational matrix translation matrix. that's happens under covers. android hides detail it's api: matrix matrix = transformation.getmatrix(); matrix.rotate( rotatex, rotatey ); matrix.posttranslate( transx, transy ); rotate first translate rotate image around it's own axis first before translating it.

scripting - Visual Studio add-in for WSF and WSC files -

are there add-ins visual studio assist editing wsf , wsc files? wsf , wsc (windows script component) files xml files interpreted windows script host. contain script metadata in xml elements, , 1 or more scripts in cdata blocks. sapien primalscript great job of handling these files, , displays them "workspace" (or "solution" in vs parlance) embedded scripts shown, , editable, separately syntax highlighting, basic intellisense, etc. when open these files in vs displays xml file. is there add-in visual studio more primalscript does? can use primalscript if have to, i'd rather not install separate tool if can it. from comment , added wsc file extension in vs2010 > tools > options > text editor > file extension, , set editor html editor. this allowed me have intellisense working in cdata section of wsc file.

.net - adding files to listview in C# -

i have listview , "add" button,when click on add should able browse files in computer, select files , when click ok or open, file list should added in listview...how that...is listview correct or other alternative...? listview should fine file listing. aware longer file paths difficult see (have horizontally scroll bad!) if gonna add full path list. can toy idea of other representation like: file.txt (c:\users\me\documents) c:\users\..\file.txt etc as far doing using code concerned, need use openfiledialog control let user choose files. var ofd = new openfiledialog (); //add extension filter etc ofd.filter = "txt files (*.txt)|*.txt|all files (*.*)|*.*" ; if(ofd.showdialog() == dialogresult.ok) { foreach (var f in openfiledialog1.filenames) { //transform list better presentation if needed //below code adds full path list listview1.items.add (f); //or use below code add file names //listview1.item

regex - Regular expression for recognizing in-text citations -

i'm trying create regular expression capture in-text citations. here's few example sentences of in-text citations: ... , reported results in (nivre et al., 2007) not representative ... ... 2 systems used markov chain approach (sagae , tsujii 2007) . nivre (2007) showed ... ... attaching , labeling dependencies (chen et al., 2007; dredze et al., 2007) . currently, regular expression have \(\d*\d\d\d\d\) which matches examples 1-3, not example 4. how can modify capture example 4? thanks! i’ve been using purpose lately: #!/usr/bin/env perl use 5.010; use utf8; use strict; use autodie; use warnings qw< fatal >; use open qw< :std io :utf8 >; $citation_rx = qr{ \( (?: \s* # optional author list (?: # has start capitalized \p{uppercase_letter} # have lower case letter, or maybe apostrophe (?= [\p{lowercase_letter}\p{quotation_mark}] )

php - XSS, encoding a return url -

here vulnerable code <?php header("location: ".$_post['target']); ?> what appropriate way make sure nasty things come in target cleaned? first up, vulnerability owasp categorizes "unvalidated redirects , forwards". see owasp's guide more information . a few interesting attacks possible. see this thread on sla.ckers.org ideas on how can abused. how protect yourself? verify scheme of url. want support http , https. abort request other scheme. parse url, , extract domain. allow redirects known list of domains. other domains, abort request. that's it.

c - Program Segmentation Faults on return 0/fclose/free. I think I have memory leaks but can't find them. Please help! -

i trying write huffman encoding program compress text file. upon completetion, program terminate @ return statement, or when attempt close file reading from. assume have memory leaks, cannot find them. if can spot them, let me know (and method fixing them appreciated!). (note: small1.txt standard text file) here main program #include<stdio.h> #include<string.h> #include<stdlib.h> #define ascii 255 struct link { int freq; char ch[ascii]; struct link* right; struct link* left; }; typedef struct link node; typedef char * string; file * ofp; file * ifp; int writebit(unsigned char); void sort(node *[], int); node* create(char[], int); void sright(node *[], int); void assign_code(node*, int[], int, string *); void delete_tree(node *); int main(int argc, char *argv[]) { //hard-coded variables //counters int a, b, c = 0; //arrays char *key = (char*) malloc(ascii * sizeof(char*)); int *value = (int*) malloc(ascii * sizeof(int*)); //file pointers fil

.net - Exception coming when exporting data to excel -

i getting following error while exporting data excel sheet error: message : exception of type 'system.web.httpunhandledexception' thrown. error description : system.web.httpunhandledexception: exception of type 'system.web.httpunhandledexception' thrown. ---> system.data.sqlclient.sqlexception: timeout expired. timeout period elapsed prior completion of operation or server not responding. anybody suggest me have do. code: griddata.datasource = getdata() griddata.databind() response.clear() response.addheader("content-disposition", "attachment;filename=completiondatesreport.xls") response.charset = "" response.cache.setcacheability(httpcacheability.nocache) response.contenttype = "application/vnd.xls" dim stringwrite stringwriter = new stringwriter() dim htmlwrite htmltextwriter = new htmltextwriter(stringwrite) griddata.rendercontrol(htmlwrite) response.write(stringwrite.tostring()) response.end() witho

iphone - shadow effect for UINavigationbar like GameCenter -

i want add shadow effect uinavigationbar gamecenter. i think apply background image shadow nav bar, title's line height down. , draw shadow background, background image not scroll. what best practice of case?? you can subclass uinavigationcontroller , have shadow layer each navigation or if bar visible add shadow uiwindow (only 1 entire application) , make frontmost view each time add subview. cgcolorref darkcolor = [[uicolor blackcolor] colorwithalphacomponent:.5f].cgcolor; cgcolorref lightcolor = [uicolor clearcolor].cgcolor; cagradientlayer *newshadow = [[[cagradientlayer alloc] init] autorelease]; newshadow.frame = cgrectmake(0, self.navigationbar.frame.size.height, self.navigationbar.frame.size.width, 10); newshadow.colors = [nsarray arraywithobjects:(id)darkcolor, (id)lightcolor, nil]; [self.navigationbar.layer addsublayer:newshadow]; if choose latter case override didaddsubview make layer frontmost: calayer *superlayer = self.shadowlayer.superlayer;

objective c - iPhone's mail "To" field.. is that a UITextField or a UITextView? -

i trying replicate iphone mail box in app. wondering if "to" field using in app textfield or textview. if yes, adding multiple lines recipient names.. guidance 1 has worked on before helpful.. the mac version called nstokenfield , there's no public api equivalent ios. can use ttpickertextfield three20 project similar.

iPad Navigation Based Application -

i want build ipad application fetch data ms sql database, want show datas in parent child manner (tree view). how can show data in parent child manner using navigation based manner, possible load information automattically in navigation bars..? if asking if it's possible load navigation data sqlite database answer yes might require bit of processing

version control - SVN: Vendor branches + patching + history? -

we have rather large library need periodically import (and patch) our code base. the svn book seems reccomend "vendor branch" scheme keep our patched version of "vendor drops". work, except vendor uses svn , gives read access reop. it great have access history of vendor files when need update our patches. so question is: is there way have patched "vendor branch" somehow keeps access history vendor files? (i've seen mention of svn:external folders, i'm not sure understand full ramifications in terms of pegging revision, nor how maintain our own patches against that.) what correct route take here? (fwiw, vendor releases once month. intend pull updates once/twice year.) thanks okay, here's rub, want vendor's source along history, apply patch vendor's source. getting source history easy. getting source history , applying patches , continually this, tough. now assuming don't place vendor's source

How do I automatically show different resources for light vs dark themes in Android? -

as understand, there 2 built in themes android, light , dark. want application display different resources based on theme user using (not having user explicitly specify theme in app!). possible? if so, possible via xml resources, or programmatic approach required? note: yes, i've read http://d.android.com/guide/topics/ui/themes.html @ least thrice. seems tells me how set 1 specific theme or styles element, rather displaying light/dark elements correctly. this site can check alternative drawable folders. http://developer.android.com/guide/topics/resources/providing-resources.html also, document might helpful. http://developer.android.com/guide/topics/ui/themes.html for regular themes: i'm not aware of functions in android that, might need develop yourself.

Generating entity files into folders per schema with LLBLGenPro for NHibernate -

we have db multiple schemas same tables in different schemas. using llblgenpro generate nhibernate entities. however, llblgenpro falls over, complaining there duplicate table names. what want entities generated namespaces per schema (got working modifying templates), , each schema generated own folder. ...? edit: colleague of mine re-posted question more information on llblgen forums per request. (please post questions llblgen pro on our own forums @ http://www.llblgen.com/tinyforum our support team can pick them up, thanks) a db multiple schemas, mean 1 catalog multiple schemas (sqlserver) or multiple schemas oracle? anyway, supported. exact error got , when? use latest build? if not, please download latest build. if want have entities grouped per target schema, group them in project, , use group in custom template namespace. you can use grouping mechanism in designer generate vs.net project per group done in own namespace , folder. downside of relationshi

android - Remove User Input From Seekbar -

i ability remove ability user interact seekbar, within activity. the scenario: user slide's seekbar once.... onstoptrackingtouch: further user interaction seekbar denied.... button onclick... user interaction seekbar restored.. i cant find attribute seekbar allow this...? one possible solution have considered, overlaying image view containing clear image. not stop underlying seekbar taking user touch input..? seekbar descends view class why not disable it? https://developer.android.com/reference/android/view/view.html#setenabled(boolean)

java - How to reference class from external jar file in spring.xml -

this bean define in spring.xml <bean id="hello" class="test.hello" /> i export class hello hello.jar , place c:\customjar . , set folder windows classpath . this output caused by: org.springframework.beans.factory.cannotloadbeanclassexception: cannot find class [test.hello] bean name 'hello' defined in class path resource [spring.xml]; nested exception java.lang.classnotfoundexception: test.hello for xml file can reference classpath use this <import resource="classpath:xxxxxx.xml"/> but doesn't work in case. edit this class sourcecode. package test; public class hello { public void somemethod() { // here } } and classpath setting. %classpath% = xxxxxxxx;c:\customjar\hello.jar; spring can load classes different jars, without configuration. - me looks hello class not in running application.

has and belongs to many - Rails 3 collection_select helper method for a HABTM relationship -

i have 2 models, sessions , presenters habtm relationship between them. on create session page, provide drop down box user may select multiple presenters session. code in _form.html.erb (for sessions) is <%= f.label :presenters %> <%= collection_select(:session, :presenters, presenter.all, :id, :name,{:include_blank => ''},{:multiple => true})%> however on hitting create following error message on browser: presenter(#2176431740) expected, got string(#2151988680) the request log shows "presenters"=>["1","2"] i guessing array of strings containing ids of selected presenters being returned instead of presenter objects. cannot understand how work. (ps- have created presenters_sessions table , specified has_and_belongs_to_many in both models) thanks in advance. i haven't figured out, work if pass in :presenter_ids second parameter rather :presenters. in end, mapping selected ids model

css font issue in internet explorer -

i using following code in css render fonts, not working in ie @font-face{font-family: beloved; src: url('font/beloved.ttf');} any suggestions? you're better off going fontsquirrel.com , whipping @font-face kit maximum cross-browser. paul irish has slick bulletproof cross-browser example of how embed @font-face correctly.

Is there a good framework/sdk on wifi positioning with c#? -

i'm searching framework wifi positioning in c#. found need robot project in form of framework. primitive object recoginition!!! wonder if of know if there one, or whether have myself. so if searching kind of software. created it: http://code.google.com/p/wifi-positioner/

reducing timeout exception on MySQL on C# -

im trying control mysql tables using c#, though takes program 5 seconds load on 3mbps internet, , throws timeout exception because program taking long connect... follow question, time connection open thing hard on loading, or queries have effect? you have 2 time out values. connection has it's own timeout. period allow provider try , connect database. secondly have command timeout, , amount of time allow query execute before timeout exception raised.

c++ - show pop-up message in front of SaveAs dialog -

in windows application, possible show popup message in front of saveas dialog after saveas dialog being opened? managed popup shows after dialog closed. i need edit old application written in c++ (i not author) can't manage task. part of code: /* ---- called display save file dialog ---- */ ofn.hwndowner = hwnd; ofn.lpstrfile = lpstrfilename; ofn.lpstrtitle = lpstrtitlename; res = getsavefilenamew( &ofn ); /* ---- fix file extension ---- */ messagebox(null, "test", "testing", mb_ok); thanks, ilija if understand correct, want check stuff (for example, file extension) before closing dialog , show message withou closing. if it's please @ ofn_enablehook flag in openfilename structure . in case code like ofn.hwndowner = hwnd; ofn.lpstrfile = lpstrfilename; ofn.lpstrtitle = lpstrtitlename; /* enables hook function */ ofn.flags |= ofn_enablehook; ofn.ofn.lpfnhook = (lpofnhookproc) myhookproc; /* code here */ res = getsavefilena

internet explorer - Good way to display a series of images -

i'm embarking on creating new app requires display series of images consecutive. each follows on next. kind of comic book guess, not contained within larger grid. each image quite big, thinking i'd show thumbnails expand when mouse hovered on (or clicked?). i know of opinions on best way display on web page, thats perhaps more viewed set of images seperated arrows (i.e. image1.jpg --> image2.jpg --> image3.jpg). any abstract or out of ordinary ideas welcome. this nice comic book-like implementation http://www.20thingsilearned.com/ take @ jcarousel or jquery tools scrollable plugin http://flowplayer.org/tools/scrollable/index.html

.net - Weird linq-to-sql error -

the error happens in line: oldperson.personserial = context.db.persons.max(function(p) p.personserial) + 1 could not find key member 'id' of key 'id' on type 'nationality'. key may wrong or field or property on 'nationality' has changed names. there's person table containing foreign key nationality table. checked column names match what might cause of error? looks sharing base class partial linq generated classes causing issue. i removed inheritance base class , worked. no idea why though!

c++ - Can we have functions inside functions? -

i mean like: int main() { void a() { // code } a(); } no, c++ doesn't support that. edit: answer old. meanwhile, c++11 has lambdas can achieve similar result – see answers below. that said, can have local classes, , can have functions (non- static or static ), can extend, albeit it's bit of kludge: int main() // it's int, dammit! { struct x { // struct's class static void a() { } }; x::a(); return 0; } however, i'd question praxis. knows (well, do, anyway :) ) c++ doesn't support local functions, used not having them. not used, however, kludge. spend quite while on code make sure it's there allow local functions. not good.

database - NHibernate Desktop App : should it use multiple sessions? -

should nhibernate desktop app use sessionfactory , multiple sessions ? one session per transaction rule apply web applications ? regards, madseb yes, nhibernate desktop application should typically use multiple sessions. in two-tier scenario, you'll use session per logical "session of interaction," such given "view" or "screen." here can maintain session longer in web application, , reap full benefit of lazy-loading, @ point want user "save" or "cancel" , move on else, , place end session. using single session throughout application can cause lot of stuff cached, , client-side data may become stale or run concurrency problems. furthermore, once session encounters exception, no longer valid , you'll have abandon/reset whatever doing. if 1 form, isn't big deal, if have lots of objects throughout application referencing same session, they'll in compromised state.

asp.net - Draw image with rounded corners, border and gradient fill in C# -

Image
i've looked everywhere , googled , couldn't find good. need class able draw image (graphics) rounded corners (different on each corner plus) border , gradient fill. all examples find have flaws (like bad quality, missing functionality etc). i use ashx draw image , show user. thanks! the graphicspath allows draw relatively free form shapes can fill gradient brush. below example code create rectangle 2 differntly rounded corners , gradient fill. graphicspath gp = new graphicspath(); gp.addline(new point(10, 10), new point(75, 10)); gp.addarc(50, 10, 50, 50, 270, 90); gp.addline(new point(100, 35), new point(100, 100)); gp.addarc(80, 90, 20, 20, 0, 90); gp.addline(new point(90, 110), new point(10, 110)); gp.addline(new point(10, 110), new point(10, 10)); bitmap bm = new bitmap(110, 120); lineargradientbrush brush = new lineargradientbrush(new point(0, 0), new point(100, 110), color.red, color.yellow); using (graphics g

Android custom dialog height -

Image
i'm learning android dialogs , i'm confused determines height. if use xml dialog layout . . . <?xml version="1.0" encoding="utf-8"?> <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content"> <button android:id="@+id/abutton" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_alignparentright="true" android:layout_marginleft="10px" android:text="click me dismiss" /> <textview android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_toleftof="@id/abutton" android:text="click button: " /> <imageview android:id="@+id/an_image" an

c++ - Changing the linkage of a name -

an attempt change linkage of name i made in code. legal in c/c++? static int = 2; int i; int main() { return 0; } in c++ code ill-formed (you have multiple definitions of variable i ) i.e standard conformant compiler required issue error message $3.2.1 (c++03) no translation unit shall contain more 1 definition of variable, function, class type, enumeration type or template. in c99 code invokes undefined behaviour because 6.2.2/7 says if, within translation unit, same identifier appears both internal , external linkage, behavior undefined .

replication - Mysql 4.x LOAD DATA FROM MASTER; slave -

i have scenario there multiple mysql 4.x servers. these databases supposed replicating server. after checking things out on slave appears slave has not replicated databases in time. some of these databases > 4g in size , 1 43g(which resides on server). has out there replicated databases without creating snapshot copy on slave? cannot shutdown master server because of downtime. take on hour , 40 minutes create snapshot. out of question. i going perform load data master on slave pull scratch. idea how long take on databases ranging 1-4g , 43g database day. of tables on master myisam don't think have problem load master method. what best methods on slave clean things or reset things can start clean slate? any suggestions? thanks in advance you need snapshot start replication. snapshots require either database locked (at least) read-only. can have consistent place start from. downtime necessary thing, customers understand long doesn't happen

qt - How do I use the bootstrap and configure commands in Ubuntu? -

i trying solve problem getting qdevelop build code given me workstation , getting kinds of errors posted question havn't received responses. see: qdevelop qt ide in ubuntu 10.04 lts lucid lynx qwt i found having same problem , don't understand solution. see: http://www.ruby-forum.com/topic/202124 greetings, i removed libqwt-dev , did .bootstrap , .configure , make , well. rob my question how use .bootstrap command (./bootstrap)? , heck matter? can't find when google it. while @ .configure (./configure?) , how use also? i running ubuntu 10.04 lucid lynx thanks, demisheep i switched ide , os's. :)

Best crossplatform multiplayer text editor? -

i searching text editor allow other people work me on files hosted on local webserver. running windows machine, , coworkers using osx. just clarify in case not clear multiplayer, want text editor can work in real time, simultaneously. edit: well, want others able edit php files (actually html inside them) , javascipt , css too. using git atm, ok. mentioned in comments, saros need, have tried gobby, , not stable enough. edit 2:end wondering, subatha edit mac only. yep, there's saros : distributed collaborative editing , distributed party programming

How to list and edit html of all web part in sharepoint 2007? -

i new in sharepoint , have simple modification in web part. have lots of web part containing simple html. html contain link , image. web developers had put full links pages , images , cause problems. want scan of web parts html , replace full links relative links. is possible ? have tons of pages , links. doing manually take 2 weeks!!! thanks! edit #2: question is: possible list aspx files in website? know how access web parts content url : using (splimitedwebpartmanager manager = web.getlimitedwebpartmanager( "ca/pages/home.aspx", personalizationscope.shared)) { foreach (system.web.ui.webcontrols.webparts.webpart wp in manager.webparts) { system.console.writeline(wp.title); if (wp.gettype().equals(typeof(microsoft.sharepoint.webpartpages.contenteditorwebpart))) { microsoft.sharepoint.webpartpages.contenteditorwebpart thiswebpart = wp microsoft.sh

java - Validation doesn't work on EntityManager.merge() -

i have few validations on entity, @notnull , , generation, @id @generatedvalue(strategy = auto) @column(name = "id") private long id; @column @generatedvalue(strategy = generationtype.auto) private long referencenumber; however when calling entitymanager.merge() values not generated. null fields @notnull annotation passed without complain. id not generated. should switch generation on somehow? how, , where? in addition kraftan's answer: by default automatic bean validation in jpa 2.0 works if validation provider "present in environment", otherwise silently doesn't work. can add <validation-mode>callback</validation-mode> to persistence.xml in order generate error if validation provider not found. jpa doesn't support generation of arbitrary (non-id) properties. jpa providers may have extensions .

HTML Character Encoding -

when outputting html content database, encoded characters being interpreted browser while others not. for example, %20 becomes space, %ae not become registered trademark symbol. am missing sort of content encoding specifier? (note: cannot realistically change content to, example, &reg; not have control on input editor's generated markup) %ae not valid html safe ascii, can view table here: http://www.ascii.cl/htmlcodes.htm it looks dealing windows word encoding (windows-1252?? that) not convert html safe, unless sort of translation in middle.

xslt - How to read a .properties file inside a .xsl file? -

i have xsl file uses a static website link shown below: <xsl:template match="my_match"> <xsl:variable name="variable1"> <xsl:value-of select="sel1/label = 'variable1'"/> </xsl:variable> <xsl:copy-of select="sites:testpath('http://testsite.com/services/testservice/v1.0', $fname, $lname, $email , $zip, $phone, $comments, $jps, boolean($myvar), string(cust/@custid), string(@paid))"/> </xsl:template> my question how read properties file(key value pair) in xsl file. in properties file (e.g. site.properties) have key called site i.e. site=testsite.com/services/testservice/v1.0 i want use site key in place of specifying url value in xsl i.e. http://testsite.com/services/testservice/v1.0 . reason doing this link changes depending on various environments. is possible? please give suggestions or sample code if possible...also if not possible...is there work-around?

mysql - Best way to implement paging in queries -

i know best way implement paging in queries. currently, doing this: select columns (select columns table order column) rownum between start , end is best way go it? yes, that's best way know far. if working sql server, may combine row_number , cte together. take @ http://www.sqlteam.com/article/server-side-paging-using-sql-server-2005 and mysql select myfield sometable limit [offset], [pagesize] of course should replace [offset] , pagesize appropriate values.

.net - Thumbrule on which collections have the Length or Count property - C# -

some c# collections have count , of them have length property. there thumbrule find out 1 has , why discrepency? i'd general thumbrule following: count collections variable length, i.e. lists (from icollection ) length fixed length collections, i.e. arrays, or other immutable objects, i.e. string . update: just elaborate count comes through icollection , doesn't indicate variability, example (as per greg beech 's comment) readonlycollection<t> has count property not variable, implement icollection . perhaps more exact rule of thumb be: count indicates implements icollection length indicates immutability.

c# - Telerik RadGrid Binding Assuming Wrong Object Type -

we using radgrid control retrieve user objects repository uses nhibernate retrieve objects. using object data source defined as: <asp:objectdatasource id="usersdata" runat="server" selectmethod="getall" dataobjecttypename="testingapp.lib.domain.user" typename="testingapp.lib.repositories.userrepository"> </asp:objectdatasource> the method signature getall follows: public ienumerable<user> getall(); with nhibernate, users adminusers extends user. seems repository returning adminuser object first, , control seems assuming rest of objects adminuser rather user. causes following exception thrown: "unable cast object of type 'testingapp.lib.domain.user' type 'testingapp.lib.domain.adminuser'." is there way force control assume data bound objects user rather adminuser? thanks! follow-up it appears radgrid used nhibernate in way not compatible , not work. have decided roll our

How to use php to feed data to jQuery autocomplete? -

this continuation of earlier post . unfortunately, solutions posted didn't work , follow questions weren't addressed. in case because generous respondents didn't notice had replied, i'm reposting problem. i'm trying build form text fields , text areas have autocomplete. i've used formidable plugin wordpress build form. i'm using jquery autocomplete plugin autocomplete part. after implementing suggestions of 1 of respondents, code looks this: <script> $(document).ready(function(){ <?php global $frm_entry_meta; $entries = $frm_entry_meta->get_entry_metas_for_field(37, $order=''); ?> var data = new array(); <?php foreach($entries $value){ ?> data.push(unescape('<?php echo rawurlencode($value); ?>'); <?php } ?> $("#field_name-of-the-school").autocomplete(data); }) </script> // 37 field id want pull in database, // , #field_name-of-the-school css id // text field in form use

iphone - Navigation Controller and View not updating when navigating back -

i have navigation based app right bar button first view pushes second view navigation controller. upon clicking button (left bar button) while viewing second view, top bar updates contents view remains on second pushed view. ideas anyone? i have encountered problem today. secondary view uitableview , did serious mistake loading tableview data. mistake initializing nsindexpath +indexpathwithindex: rather +indexpathforrow:insection: while accessing table cells. unrelated plainly causes navigatorview malfunction. can control secondary view code if there issue this. other this, have no idea may be. luck!

ajax - In JavaScript, is there a way to retrieve the content-type of a URL without retrieving the entire file? -

i determine if given url image without relying on file's extension. in javascript, there way url's http response headers without retrieving entire contents of file? you can http head. covered in accessing web page's http headers in javascript the head method identical except server must not return message-body in response. metainformation contained in http headers in response head request should identical information sent in response request. method can used obtaining metainformation entity implied request without transferring entity-body itself. method used testing hypertext links validity, accessibility, , recent modification. http://www.w3.org/protocols/rfc2616/rfc2616-sec9.html

javascript - JQuery adding and then removing same image -

i using jquery show green check-mark , message on successful submission. image , message show correctly. want remove image , message using jquery's hide function. have used before no problem when html on page already. time not working , i'm wondering if since html being added jquery , removed. i'm not sure if element child of element or not, may problem. insight issue huge help, thanks. jquery code: $("<span id='checkmark'><img height='45' width='45' src='./img/checkmark_green.jpg'/>&nbsp;<span style='color: #33cc33; font-size: 14pt'>word added dictionary.</span><br/></br></span>").prependto("#div_dict"); //i tried '#div_dict > #checkmark' $('#checkmark').click(function(){ $(this).hide('slow'); }); html/php: echo('<div id="div_dict">'); echo('<big id="add">

NSUserDefaults: How to set up NSDictionary with NSString keys, and BOOL values? -

i want add nsdictionary item nsuserdefaults settings bundle, not sure how structure item inside root.plist file. dictionary needs contain nsstrings keys, , boolean values. at moment item inside .plist looks following pseudo code: item 0 -- dictionary key -- string -- values values -- dictionary item 0 -- string -- speed //key item 1 -- boolean -- no //value etc.... is correct? in order read boolean value in program want execute following code. bool speedvalue = [[[nsuserdefaults standarduserdefaults] objectforkey:@"values"] objectforkey:@"speed"]; almost. bool isn't object, you'll need out via nsnumber or something.

iphone - How can I send a PLIST through bluetooth? -

possible duplicate: how send nsdictionary (or plist file) nsdata using gamekit bluetooth? i'm looking simple way send plist file, or nsdictionary through bluetooth 1 device running app another. how convert plist file nsdata (which can sent through bluetooth) , convert later? (i'd appreciate if can me started code.) please see answer found here: https://stackoverflow.com/questions/4107004/how-to-send-an-nsdictionary-or-plist-file-as-nsdata-using-gamekit-bluetooth you can use following transform plist nsdata: `+ (nsdata *)datawithpropertylist:(id)plist format:(nspropertylistformat)format options:(nspropertylistwriteoptions)opt error:(nserror **)error` and transform nsdata plist: + (id)propertylistwithdata:(nsdata *)data options:(nspropertylistreadoptions)opt format:(nspropertylistformat *)format error:(nserror **)error of nspropertylistserialization class format nspropertylistbinaryformat_v1_0 use lowest byte count

How to create common/shared instance in vba -

i create 1 instance of class other use far create each instance in each class needes methods. is there way create 1 instance seen other classes. normaly create sort of static variable seen others. seems not possible in vba :/ in module: private objsharedclass myclass public function getshared() myclass if objsharedclass nothing set objsharedclass = new myclass end if set getshared = objsharedclass end function it's vb(a) implementation of singleton pattern. need consider whether or not it's appropriate, , if so, that's way it. when use it, put above code in module (except if i'm using more 1 singleton in application put them in single module). can add destruction routine same module , call application exit: public sub closesingleton() set objsharedclass = nothing end sub or can let go out of scope when app closes--not tidy, i've never seen cause problem (i clean up, though...). edit usage (just in case it&#

Android app with music streaming -

i want make android app stream music site users use app. so, question is, better - shoutcast server , stream app (i have know song playing @ moment), or streaming music files stored on server (is possible?). please point me @ right track, , recommend me libraries purpose (or android sdk have this). thank you. try looking @ android.media package android sdk http://developer.android.com/reference/android/media/package-summary.html in particular, asyncplayer , mediaplayer classes. as whether shoutcast server better local control of playback (with playlist example) difficult answer. shoutcast server 'single point of failure' if crashes, i.e., none of users music if happened. controlling playback app, however, add amount of code in app (albeit small amount).

Android: AsyncTask ProgressDialog will not open in ActivityGroup -

i trying have a progress dialog open when polling server. class activitygroup because nested within tab bar. keep view within frame, activitygroup needed. here declaration of activitygroup class: public class checkinactivity extends activitygroup{ ... public void oncreate(bundle savedinstancestate){ super.oncreate(savedinstancestate); setcontentview(r.layout.checkin); new locationcontrol().execute(this); now asynctask class within same checkinactivityclass such: private class locationcontrol extends asynctask<context, void, void> { private final progressdialog dialog = new progressdialog(checkinactivity.this); protected void onpreexecute() { this.dialog.setmessage("determining location..."); this.dialog.show(); } when run given app throughs error relating windowmanager$badtokenexception. stating cannot start window unknown token. tried making sampl

How can I trigger a jQuery alert when an iframe AND its CSS is loaded and rendered? -

i'm trying trigger alert when <iframe> , css files loaded , rendered. i have following far: $("#content_ifr").ready(function (){ alert('iframe ready'); }); the problem alert happening before css rendered on page, after alert closed, see css taking effect in browser. any ideas on how solve out sloppy timeout hack? thanks. since it's tinymce you're dealing with, have tried apis? http://wiki.moxiecode.com/index.php/tinymce:api/tinymce.editor i'm thinking onloadcontent best bet, i'm not sure if css magic. the way we've found pause loading until css loaded sloppy timeout hack. basically: set real specific rule, div.test-file-loaded{ color: #123456 } create div of class. check if color of element #123456, keep timeouting , retrying until is. would know if there's non hack way, don't think there is. since you're dealing iframe, more hackiness needed....

Can Fossil insert the SHA1 checksum of an immediate commit into a file? -

say want commit new version repository, i'd automatically insert checksum of new commit (unknown me) file (or somewhere file) needs me commited. there way in fossil?, or possible tell fossil run executable or script before every commit automatically edit file insert checksum? thanks the file manifest.uuid contains checksum of commit, , file manifest contains list of files in commit , individual checksums. ( manifest.uuid sha1 of manifest). both files plain text , easy parse. the build fossil shows 1 use. when building, file manifest.uuid converted awk) c string literal of form "[1234567890]" , used form text of revision name appears in html page footers. do note recent versions of fossil don't leave files behind unless "manifest" setting enabled command fossil setting manifest 1 . alternatively, can parse output of fossil info or fossil status , both of include value of current checkout's id. for single file, fossil finfo rep

javascript - How to store temporary data at the client-side and then send it to the server -

i need store data temporarily @ client-side allow users add, edit or delete items without having query server each of these actions; when user finishes adding items , clicks on add button, list sent server saved permanently. this image describes want achieve. know have use arrays in javascript, don't know how create 1 store objects (in case detail contains :id, price , description). i hope can me out. in advance. ps: i'm using jsp and... sorry english sure, since it's table makes sense have array of objects. note object surrounded curly braces , array surrounded brackets: var myarray = []; // initialize empty array var myobject = {}; // initialize empty object this should accomplish need: // initialize variables var newentry, table = []; // create new object newentry = { id: '', price: '', description: '' }; // add object end of array table.push(newentry); which same this: // initialize array var table = []; /

subtract from symbols in ruby -

i find first valid image among list in ruby. here code: if(params[:id]) @image = image.find_by_id(params[:id]) while @image.nil? :id-- ? @image = image.find_by_id(params[:id]) end in block, how can keep decreasing id # until valid image found? :/ thanks! you can't subtract symbol. symbol not number. what seem want decrease value of params[:id] , of course possible (after converting id string integer) doing params[:id] = params[:id].to_i - 1 or id = params[:id].to_i while @image.nil? @image = image.find_by_id(id) id -= 1 end the latter better first because not mutate params (which there no reason do). however should not either of those, because can achieve much less hassle, letting db work: image.find(:first, :order => "id desc", :conditions => ["id <= ?", params[:id]]) ps: ruby doesn't have -- operator, have use -= 1 decrement number.

python - Is there any database model designer that can output SQLAlchemy models? -

i implementing database model store 20+ fields of ical calendar format , faced tediously typing in these sqlalchemy model.py file. there smarter approach? looking gui or model designer can create model.py file me. specify column names , attributes, e.g, type, length, etc. at minimum, need designer output model 1 table. additional requirements, in decreasing order of priority: create multiple tables support basic relationships between multiple tables (1:1, 1:n) support constraints on columns. i open other ways of achieving goal, perhaps using gui create tables in database , reflecting them model. i appreciate feedback in advance. there's way yet generate sqlalchemy model. can use vertabelo - it's online tool visual database designing. it's free small projects. after created model in vertabelo, have convert sqlalchemy mapping classes using script available on github . simply follow provided below steps: download diagram xml file (simply pre

c - Why do these swap functions behave differently? -

#include <stdio.h> void swap1(int a, int b) { int temp = a; = b; b = temp; } void swap2(int *a, int *b) { int *temp = a; = b; b = temp; } void swap3(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } main() { int = 9, b = 4; printf("%d , %d\n", a, b); swap1(a, b); printf("%d , %d\n", a, b); swap2(&a, &b); printf("%d , %d\n", a, b); swap3(&a, &b); printf("%d , %d\n", a, b); } c has value semantics function parameters. means a , b 3 swap variants local variables of respective functions. copies of values pass arguments. in other words: swap1 exchanges values of 2 local integer variables - no visible effect outside function swap2 exchanges values of 2 local variables, pointers in case, - same, no visible effect swap3 gets right , exchanges values pointed to local pointer variables.

java - Write a simple interpreter, or find one I can use? -

i need simple interpreter written in java. language going simple. i need string operators, "contains , equals". need logically and, or. along parenthesis. "some string" contains "ring" , ("some string" equals "input" or "some other string" contains "other") this needs evaluate true or false. are there open source intrepetors evaluate language similar this? better off writing own? may overkill, use javacc generate parser language, traverse generated syntax tree input in order evaluate expression.

regex - Find and replace with reordered date format in notepad++ -

i have file few thousand rows added mysql database. there date values in rows in dd-mm-yyyy format need them in yyyy-mm-dd format. e.g., '11-04-2010', needs become '2010-04-11', in every row. is there simple way in notepad++ or text editor? you can textpad: find: ([0-9]+)-+([0-9]+)-+([0-9]+) replace: \3-\2-\1

visual studio 2008 - to calculate no of working days in a current month excluding sunday in windows application in .net -

to calculate no of working days in current month excluding sunday in windows application in .net.please helpfull possible.. this compute number on non-sunday's in month (example shows current month). var daysthismonththatarenotsundays = enumerable.range(1, datetime.daysinmonth(datetime.now.year, datetime.now.month)).where( d => new datetime(datetime.now.year, datetime.now.month, d).dayofweek != dayofweek.sunday).count();

ruby on rails - Problem with associations -

i have built ruby on rails app lets users track workouts. user has_many workouts. in addition, user can create box (gym) if gym owner. purpose filter activity of users such can see information related gym. in case workouts. on box show page...i show users associated box through membership , consequently associated users workouts. here set up. user class user < activerecord::base has_many :boxes has_many :workouts, :dependent => :destroy end workout class workout < activerecord::base belongs_to :user belongs_to :box end box class box < activerecord::base belongs_to :user has_many :users, :through => :memberships has_many :workouts, :through => :users has_many :memberships end membership class membership < activerecord::base belongs_to :user belongs_to :box end in /views/boxes/show.html.erb view have following: <% @box.workouts.each |workout| %> <%= workout.title %><br/> <%= workout.user.username %&