Posts

Showing posts from June, 2015

c# - Appending Streams with SevenSharpZip -

i've been knocking head on 2 days. we're using 7zipsharp create .7z files several source files (incoming emails in fact). in order optimize application, want avoid hard disk access switched compressstreams function family. the code using filenames instead of streams works perfectly. when switching streams, "keynotfoundexception", when compressionmode = append. my test code: for (var = 0; < numfiles; i++) { //if(i > 0) // compressor.compressionmode = compressionmode.append; console.writeline("adding copy num " + (i + 1) + " archive"); sevenziputil.addstream(file.openread(samplefile), "email-" + + ".eml", outfile); } helper method code: public static void addstream(stream instream, string filename, string destinationfile) { sevenzipcompressor comp = new sevenzipcompressor(); comp.archiveformat =...

java - Guaranteed memcached lock -

so, i'm trying implement distributed lock using memcached , add()'s store if not exist contract (java & spymemcached, applicable in language of course). of course, if instance goes away, lose lock thought add lock 3 times (e.g. mylock1, mylock2, mylock3) hash out 3 different instances. but, i've realized if instances goes down hash changes (using spymemcached's redistribute failure mode) , it's when attempt made add() locks, hashes of 3 lock's not match of 2 remaining locks in memcached cluster. so...any other ideas distributed locks using memcached? or impossible guaranteed lock i'm referring to? edit: ok, in looking through spymemcached source code, redistribute mode, goes next active memcached instance in it's list, rather re-hashing anything, should work ok. if want use memcached avoid introducing more stuff/complexity environment, consider small dedicated memcached config locking. but if you're open solutions don't r...

sql - Reporting database synchronization -

we building application. have ms sql database put data wee need. want use database reporting denormalized version of main database, optimized fast data retrieval. there couple of questions have: what type of database best suited reporting job (sql, ravendb) how synchronize these 2 databases? as data access use nhibernate 3.2. please help. thanks you use sql server analysis services house proper data warehouse, question sounds way you're going. sql server integration services can used perform etl (extract-transform-load) process populate , keep warehouse up-to-date. there ton of comprehensive guides on process.

forms - Rails 3 select and onchange without Ajax -

i struggling whole day idea, how build simple form contains select item. select item contains 3 or 4 static values. i don't know, how make form -- need after select item select offer form sent controller action. i tried search , reading lot of articles, unfortunately can't find working solution... don't need ajax, basic functionality. i ask help, how simple form... thank you, m. add onclick handler select calls method submits form. use method create select: collection_select(method, collection, value_method, text_method, options = {}, html_options = {}) in html_options hash put in :onclick => "some_javascript_method()" in javascript method have submit form. suggest using jquery form element call submit on.

ruby on rails 3 - Benefits of Presenter pattern for controller testing -

i'm participating in project, extersively uses presenter pattern. i don't see benefits of it, because methods of presenter class trivial, this: class checkout::newpresenter def initialize(customer, order) @customer, @order = customer, order end def customer @customer end def order @order end end guys talking me, pattern makes testing of controllers more simpler. abstracted controller's logic , need test presenter object on return values. but, effect can achieved examining instance variables of controller, without presenter layer. i've ready simplifying ruby on rails code: presenter pattern, cells plugin , agree first case: you have logic in view, uses models extensively. there no places in other views such logic. classic recommendation move code model, after short time models become bloated stupid one-off helper methods. solution: pattern presenter. i don't understood second case. your constructor contains lot of...

c++ - UnitTest++ command line arguments -

i want use command line argument in 1 of tests. couldn't find example of on web. test(sometest) { std::string file("this command line argument"); check(something); } int main(int argc, char** argv) { return unittest::runalltests(); } any ideas? answer there's no real reason test command-line arguments directly. instead, write unit tests check behavior of code (functions , classes) given different arguments. once satisfied code working under unit test, plug main , should work there, well. clarification imagine have unit test on argument std::string constructor. test(sometest) { std::string file("this command line argument"); check(something); } then plug main . int main(int argc, char** argv) { std::string file(argv[1]); // stuff.... return 0; } because nothing should happen command-line argument before passed constructor, you have tested already . if, on other hand, main mess, suggest refac...

vb6 - Password Changer using VAccess -

hey working on password changer. user logs in ( successfully), loads global var user initials, launch password expired form. try , use initials on password expired form retrieve user info db. vauserlog.fieldvalue("userinit") = userinitials vauserlog.getequal vastat = vauserlog.status vastat keeps giving me error of 4. using pervasive v9. connection va looks like: with vauserlog .refreshlocations = true .ddfpath = datapath .tablename = "userlog" .location = "userlog.mkd" .open if .status <> 0 errmsg = "error opening file " + .tablename + " - status " + str$(.status) + vbcrlf + "contact department" end if end in db table, userinit char, 3. userinitials string. probably missing small can't think right now. appreciate. lemme know if require more info. cheers status 4 means record not found. in case, case of value being search...

wcf ria services - Silverlight: Access element in DataForm EditTemplate by name -

how 1 access control in dataform 's edittemplate code behind? the following edittemplate applies: <toolkit:dataform itemssource="{binding elementname=somedomaindatasource, path=data, mode=twoway}"> <toolkit:dataform.edittemplate> <datatemplate> <stackpanel> .... <sdk:datepicker displaydate="{binding duedate, mode=twoway}}" x:name="dpcustommaterialduedate"/> .... </stackpanel> </datatemplate> </toolkit:dataform.edittemplate> </toolkit:dataform> is possible access datepicker code-behind file using variable name dpcustommaterialduedate ? intellisense seems unable find it. also tried access in dataform 's contentloaded event, no luck, i.e. dataformprintorders.contentloaded += (sender, args) => { datepicker d = (datepicker) ...

branch - jQuery branching backwards button -

i working built jquery wizard on site: http://kflorence.github.com/jquery-wizard/examples/ , 1 working "branching wizard." based on selections, go different questions/answers. my problem built wizard 4 questions far, when hit "backwards" button go once. want able keep clicking "backwards" button go through previous questions went through. i guessing section of code need edit? can't figure out: select: function( event, step, branch, relative, history ) { // args: step, branch, relative, history if ( !( event instanceof $.event ) ) { history = relative; relative = branch; branch = step; step = event; event = undefined; } if ( step == undefined ) { return; } // args: [ step, branch ], relative, history if ( $.isarray( step ) ) { history = relative; relative = branch; branch = step[ 1 ]; step = step[ 0 ]; // args: step, relative, h...

Ruby on Rails application Redmine returns text/plain header causing pages to be downloaded instead of being rendered -

i upgrading redmine installation 1.0.5 1.2 enable backlogs plugin. upgraded application , installed plugin without errors in console. when returned browser test seem getting page content plain text. seems content type header being set text/plain. content generated page seems valid html corresponding page. how application spit out correct text/html content header? i'm not 100% sure related, may help. i'm not sure version of rails using or if using mongrel. problems running ruby on rails apps on shared hosted server this applicable rails -v 2.3.9

sharepoint - Missing fields in the Edit Item View -

i have stumbled across problem after doing successful migration. on 1 of list, there missing fields when go edit item. these same fields show when go view item. not recall hiding fields , with 2 of 25 fields not showing puzzling. ideas in programming world may have taken place? are migrating code 2007 2010? if so, should @ these views in sharepoint designer. should have ability create new view (with desired fields), make default , omit older view.

java - Preserve sort order of SOAP result -

i've built soap service jax-ws, , returns number of sorted results, sorted in order customer finds aesthetically pleasing. i've got handled no problem in end, , results coming through consistently in right order. client piece, being generated wsimport, using arraylists when receives these results, not guaranteed preserve order when iterated. there way override this? or better can on soap side in schema tell client needs preserve order?? ( cause know i'm going have c# client ) tia!! is using arraylists when receives these results, not guaranteed preserve order when iterated. where assumption come from? the java.util.list interface represents ordered collection . order of elements in collection essential. implementation of java.util.list did not return correct order of elements in collection when iterating breaking contract of interface. the javadoc list.iterator() method states (emphasis mine): returns iterator on elements in list in proper ...

delphi - Indy TIdSSLIOHandlerSocketOpenSSL - it works on my PC, not on my friend's -

my application using tidhttp.get access clickbank's api. in order work, have assign tidssliohandlersocketopenssl tidhttp.iohandler . the problem is, above setup works fine on pc (the dev box), when send out friends, forbidden (403) error. could missing openssl libaries? did search on pc, , bunch of apps buddys have, includes sll libraries. am missing something? my bad - libeay32.dll , ssleay32.dll has in either windows directory, or in app's directory.

actionscript 3 - Preventing default arrow key behavior when a UIComponent is focused? -

i'm trying creating text-input-like real-time tokenizer consists of block (shape/visual) components (extended uicomponent) , dummy textinputs, ordered in hgroup component. i.e. typing expression "x+5" this: ["x" block][textinput]["+" block][textinput]["5" block"][textinput] <- cursor here logically want pressing left or right arrow keys moves focus between block , textinputs. i overrode keydownhandlers this, doesn't focus correctly. when i'm focused in block component, pressing left , right moves correct textinput, when moving textinput block focuses other unrelated component in parent application. i tried using trace() statements, , seems focus being set twice, this: 1) if textinput focused initially, focus goes correctly block component on side, goes unrelated component. 2) if block focused initially, focus goes unrelated component, focuses on right textinput. preventdefault() , stopimmediatepropagation()...

ruby on rails - Edit a serialized hash in a form? -

i'm serializing hash stored in settings field in table, , able edit hash in form field. class template < activerecord::base serialize :settings end but <%= f.text_area :settings %> text area shows serialized data instead of hash. how can hash show in text area? maybe setting accessor model work. class template < activerecord::base serialize :settings attr_accessor :settings_edit before_save :handle_settings_edit, :if => lambda {|template| template.settings_edit.present? } def settings_edit read_attribute(:settings).inspect # should display hash want end protected def handle_settings_edit # may want perform eval in validations instead of in # before_save callback, can show errors on form. begin self.settings = eval(settings_edit) rescue syntaxerror => e self.settings = settings_edit end end end then in form use <%= f.text_area :settings_edit %> . i have ...

sockets - Java Server and Client Help -

i'm trying write server , client program in java. i've not done before, figured i'ld start examples provided @ links below. server code: http://java.sun.com/developer/onlinetraining/programming/basicjava2/code/socketserver.java client code: http://java.sun.com/developer/onlinetraining/programming/basicjava2/code/socketclient.java i made few changes in terms of naming, basic functionality should same. server app runs fine, client app throwing unknownhostexception. thought problem ip address used in both apps not being valid. i'm running on mac, , don't claim expert on ip addresses, figured might idea write code print out ip address, posted below, in case it's @ helpful. java.net.inetaddress address = java.net.inetaddress.getlocalhost(); system.out.println("ip address  :"+address.gethostaddress()); however, code returns number 463.827.201.789(not demonstrative purposes), doesn't work parameter of socket constructor i'm using. anyw...

android - How to pass and return Intent (Camera) -

i need little different usual. i have 20 buttons can take image. use same handler. depending on button clicked - pass "buttonindex" inside intent camera. value in onactivityresult know process. is possible? tried read returned intent value get's lost. yep. can use startactivityforresult (intent intent, int requestcode) requestcode returned when activity exits.

Byte order mark removal in xml files using Java IO -

the byte order mark first 3 bytes in xml file. how remove byte order mark xml file programmatically? want discard it. rather removing it, use special reader reacts bom (and uses proper encoding, based on read bom): copied elsewhere (see note inside) open-sourced in android-menu-navigator project: http://code.google.com/p/android-menu-navigator/source/browse/src/pl/polidea/navigator/unicodereader.java you can use reader anyway read content of xml , write elsewhere, removing bom.

javascript - jQuery: too much recursion But I need recursion for minesweeper -

i relatively new javascript. trying code web version of minesweeper. here recursive function needed, , looks work fine until browser gives "too recursion" error. problem need recursion. there other way code minesweeper? here demo: http://altynachar.com/minesweeper/ i can post php code if needed. function recursive(id){ var id = id; //determine kind of cell is: clean, bomb or adjasent bomb if($("#"+id).hasclass("adj")== true) var under = "adj"; if($("#"+id).hasclass("bomb")==true) var under = "bomb"; if($("#"+id).hasclass("clean")==true) var under = "clean"; //open cell $("#"+id).hide(); $("#under_"+id).show(); //if bomb, open whole grid , button ...

Objective C pointer use -

possible duplicates: what's preferred pointer declaration style, , why? placement of asterisk in objective-c is there difference between nsstring* foo = @"i'm string"; and nsstring *foo = @"i'm string"; i've used latter way, wasn't sure if there difference. thanks! no. there no difference @ all. it's same in c language. both pointers nsstring . some people prefer later form because makes clear variable pointer. i.e.: int* i, j; // pointer // j not pointer int *i, j; // makes clearer pointer while j not int *i, *j; // both pointers... check out c-faq entry on topic.

zipcode - What is the ultimate postal code and zip regex? -

i'm looking ultimate postal code , zip code regex. i'm looking cover (hopefully all) of world. there none. postal/zip codes around world don't follow common pattern. in countries made numbers, in others can combinations of numbers letters, can contain spaces, others dots, number of characters can vary 2 @ least six... what (theoretically) create seperate regex every country in world, not recommendable imo. still missing on validation part: zip code 12345 may exist, 12346 not, maybe 12344 doesn't exist either. how check regex? you can't.

multithreading - Java - multithreaded code does not run faster on more cores -

i running multithreaded code on 4-core machine in hopes faster on single-core machine. here's idea: got fixed number of threads (in case 1 thread per core). every thread executes runnable of form: private static int[] data; // data shared across threads public void run() { int = 0; while (i++ < 5000) { // work (int j = 0; j < 10000 / numberofthreads) { // each thread performs calculations , reads , // writes different part of data array } // wait other threads barrier.await(); } } on quadcore machine, code performs worse 4 threads 1 thread. cyclicbarrier 's overhead, have thought code should perform @ least 2 times faster. why run slower ? edit: here's busy wait implementation tried. unfortunately, makes program run slower on more cores (also being discussed in separate question here ): public void run() { // work synchronized (this) { if (atomicint.decre...

delphi - C#: How to access an unmanaged, 2-Dbinary array nested in a struct? -

problem: i'm trying access binary records created in borland delphi , stored in sql server database (as blob). q: heck syntax accessing two-d array in c#???? here's example: const max_bowlers = 8; gmax_frames = 40; ... type tframe = record balls : array[1..3] of shortint; // pins standing: balls 1, 2 , 3 pins : array[1..3] of shortint; currentball : byte; score : integer; // current score (-1= undefined) attributes : tframeattributes; ... tframes = array[1..max_bowlers, 0..gmax_frames] of tframe; tgamerec = record side : byte; bowlers : tbowlers; frames : tframes; ... soooooooo.... i've got valid "gamerec" on c#-land. i want access gamerec.frames[ibowler, iframe]. q: how define c# type "tframes = array[1..max_bowlers, 0..gmax_frames] of tframe;" can it? thank in advance .. psm i found solution: treat 2-d array own struct, containing arr...

what is the standard to declare constant variables in ANSI C? -

i teaching myself c going on c++ book , recoding problems in c. wanted know correct industry standard way of declaring variables constant in c. still use #define directive outside of main, or can use c++ style const int inside of main? const in c different const in c++. in c means object won't modified through identifier: int = 42; const int *b = &a; *b = 12; /* invalid, contents of `b` const */ = 12; /* ok, though *b changed */ also, unlike c++, const objects cannot used, instance, in switch labels: const int k = 0; switch (x) { case k: break; /* invalid use of const object */ } so ... depends on need. your options are #define : const uses preprocessor const : not const enum : limited int larger example #define const 42 const int konst = 42; enum /*unnamed*/ { fixed = 42 }; printf("%d %d %d\n", const, konst, fixed); /* &const makes no sense */ &konst; /* can used */ /* &fixed makes no sense */

sql - Very slow stored procedure -

i have hard time query optimization, i'm close point of database redesign. , stackoverflow last hope. don't think showing query enough i've linked not database script attached database backup in case don't want generate data hand here can find both script , backup the problems start when try following... exec lockbranches @count=64,@lockedby='034c0396-5c34-4dda-8ad5-7e43b373ae5a',@lockedon='2011-07-01 01:29:43.863',@unlockon='2011-07-01 01:32:43.863' the main problems occur in part: update b set b.lockedby = @lockedby, b.lockedon = @lockedon, b.unlockon = @unlockon, b.complete = 1 ( select top (@count) b.lockedby, b.lockedon, b.unlockon, b.complete objectives o inner join generations g on g.objectiveid = o.id inner join branches b on b.generationid = g.id inner join ( select sb.branchid branchid, sum(x.suitableprobes) suitableprobes spiciebranches sb inner join probes p on...

java - Background with getResourceAsStream("path") -

i having folder structure this. project/src/folder/folder/folder/xyz.java /img/background.jpg and want put background.jpg jpanel in xyz.java . background. , i've done with private imageicon createimageicon(string path, string description) { java.net.url imgurl = getclass().getresource(path); if (imgurl != null) { return new imageicon(imgurl, description); } else { system.err.println("couldn't find file: " + path); return null; } } but problem here image has in same folder xyz.java searched bit , found solved getresourceasstream("path") can't bring enough knowlege solve this. important me because want run programm *.jar file on different operating systems. my problem don't understand how getressourceasstream("path") should work different. found no tutorial fits me. seems people use different .jar files or applets. , don't know stream can do, getressourceasstream("p...

colors - What is a simple way to brighten textures mapped to a quad in OpenGL ES? -

i'm displaying 2d sprites built using multiple textures (with transparency) applied quads. have enabled color array gldrawarrays , know how use change ratio of each color , dim textures (ie. reducing colors same amount). this done using premultiplied alpha , following: glblendfunc(gl_one, gl_one_minus_src_alpha); gltexenvi(gl_texture_env, gl_texture_env_mode, gl_modulate); is there simple way brighten texture well? i tried using gl_add, causes entire quad become visible (ie. pixels transparent not anymore). thanks. this quite easy: draw quad on region want brightened, overlay quad using glblendfunc(gl10.gl_dst_color, gl10.gl_one); which effectively means take underlying color (dst, gl_one) is, , add fraction of same color (src, gl10.gl_dst_color). the fraction add specified color of quad, can tweak brightness setting overlay quad's vertex colors {0.0f, 0.0f, 0.0f} (no brightening) {1.0f, 1.0f, 1.0f} ('doubling' brightness). of course can i...

Fixing a failed integrity check in Mercurial? -

i did hg pull on repository , brought in changesets. said run hg update , did. unfortunately, when did that, failed following error message: abort: integrity check failed on 00manifest.i:173! when run hg verify , tells me there number of issues things not in manifest (with slight path obscuring): >hg verify checking changesets checking manifests crosschecking files in changesets , manifests somewhere1/file1.aspx@172: in changeset not in manifest somewhere2/file1.pdf@170: in changeset not in manifest checking files file3.csproj@172: ee005cae8058 not in manifests somewhere2/file1.pdf@171: 00371c8b9d95 not in manifests somewhere3/file1.ascx@170: 5c921d9bf620 not in manifests somewhere4/file1.ascx@172: 23acbd0efd3a not in manifests somewhere5/file1.aspx@170: ce48ed795067 not in manifests somewhere5/file2.aspx@171: 15d13df4206f not in manifests 1328 files, 174 changesets, 3182 total revisions 8 integrity errors encountered! (first damaged changeset appears 170) the s...

security - to encrypt php or make it "call home" -

i have simple php script , want protect it. i'm ruling out ioncube they'll hack anyway , it'll increase customer support. i'm hearing making script "call home". alternative or same ioncube , similar encrypting software? if viable alternative, there software or scripting can buy or learn code use technique? if calling home isn't best answer, better alternative securing php scripts. thanks pointing me in right direction. if php code being distributed, there stop removing call home code? protect code through legal means instead.

ios - Handle notifications to pause app and how to test on iPad -

i "pause" app when ipad receives notifications, push notifications other apps, local notifications alarms , on, showing small pop window. have tried event listen can not find it. i have implemented in view controller applicationwillresignactive , hope there similar kind of notifications. [[nsnotificationcenter defaultcenter] addobserver:self selector:@selector(pausemyapp:) name:uiapplicationwillresignactivenotification object:nil]; i'm sure have read somewhere can not recall. appreciate if can redirect me right documentation or give short piece of code. thanks in advance. i must seem stupid have asked question, answer same using :-) implement applicationwillresignactive. documentation can found here (like me!) has problem finding again... uiapplicationdelegate protocol reference

javascript events - How do I determine that all tabs have been loaded in Firefox? -

i writing firefox add-on , need able run code after tabs have been loaded. i tried like: window.addeventlistener("load", function(e) { gbrowser.addeventlistener("load", function(ee) { // code run after tabs have loaded // thank user installing add-on alert('thank installing add-on'); // add tab website gbrowser.selectedtab = gbrowser.addtab("http://www.mywebsite.com/"); }, true); }, false); but not work because run code each tab after loaded. want wait until of tabs have loaded. want print alert message when firefox restarts after users installs add-on. want add new tab website. how do this? i guess mean wait until session restored when browser starts up. there sessionstore-windows-restored notification sent out can listen via observer service. this: cu.import("resource://gre/modules/xpcomutils.jsm"); var observer = { queryinterface: xpcomutils.generateqi([co...

PHP vs. C CGI for small web service -

i creating small web service accessed machines, not users takes query string , makes few mysql queries. decided code in php because simple , easy write , job well. boss however, wants write cgi in c (using fastcgi) because says faster , use less memory. i'm not keen on idea few reasons: the mysql api c seems have lot more calls equivalent php , need lot more error handling. string manipulation in c complicated , messy. the code in c 3 times long equivalent code in php , looks rather messy, lots of error handling. but that's opinion. other factors need take in account? c best tool job? or php? some points this: it's easier implement web service in php rather c, because php language designed work online , c general language. c compiled , makes faster php programs, if worried optimization (your program consumes lot of resources , hardware limited) can use php "accelerators" compiles source ( for example ) access databases equal penalized in ...

Performance difference in various Hibernate Queries on VarChar MsSql columns -

i have query in hibernate believe because of varchar , nvarchar discrepancies in driver , mssql discussed here getting hibernate , sql server play nice varchar , nvarchar . understand issue not hibernate confused way hibernate deals code below . when ran queries below (using set parameter , without it), on db varchar column type column 'code' , found appending string in hql works lot faster setparameter(or criteria query should have been faster hql) . query createquery = session.createquery("from abc code='"+substring+"'"); /*query createquery = session.createquery("from abc code=:substring"); createquery.setparameter("substring","test");*/ return createquery.list(); please let me know how make difference. the execution plan computed database different between 2 queries. similar problem described in this question , , dba told me same problem can appear oracle well. ...

php - Apache Benchmark is not writing error in the log file -

apache benchmark not writing error in log file. i tried ab -n1000 -c10 http://localhost . my error log file located in /var/log/apache/error.log please help. are seeing error in ab or in apache server ? ab prints results stdout , have options csv(-e) or gnuplot(-g)

MySQL blob: how to get just a subset of the stored data -

i use mysql storage system huge number of files. read/write portion of data stored in column (data stored bytes) don't have load entire file application (because can > gb). so, in brief, have random read/write access in blob column without loading entire data memory. there functions available perform these operations? thank you. mysql treats blobs same strings (more or less) : blob values treated binary strings (byte strings). have no character set, , sorting , comparison based on numeric values of bytes in column values. so usual string functions work on blobs. in particular, can use substring grab part of of blob. that said, storing multi-gigabyte data file in relational database blob isn't best thing do. you'd better off storing file's metadata in database , leaving file in file system; file systems pretty @ managing files, relational databases @ handling structured data.

tomcat - is there any way to backup generated pdf report files from jasperserver? -

i've been running jaspperserver (deployed on tomcat 6) while now. in daily report folder have quite huge number of files. i'm wondering if there way them , delete them folder have empty daily report folder again. you download them via webservice interface of jasperserver in script , safe them somewhere. , delete them on server. or take backup of jasperserver database (which contains pdf files) , delete them afterwards. have restore download them later.. , might problem if upgraded jasperserver version. you run separate jasper server off database copy...

python - Scapy show2() packet problem -

i'm trying create scapy layers , want them adapt size on fly. use following code: class foo(packet): name = "testpacket" fields_desc = [ bytefield("length", none), bytefield("byte2", none), bytefield("byte3", none), bytefield("byte4", none), bytefield("byte5", none), bytefield("byte6", none), bytefield("byte7", none), bytefield("byte8", none), bytefield("byte9", none), bytefield("byte10", none), bytefield("byte11", none) ] def post_build(self, p, pay): if self.length none: if self.byte11 not none: x = 0xa elif self.byte10 not none: x = 0x9 elif self.byte9 not none: x = 0x8 elif self.byte8 not none: x = 0x7 elif self.byte7 not none: ...

How can I rerun a program with gdb until a segmentation fault occurs? -

my program has segmentation fault problem, faults rarely(once in 20 times or more), , debug in gdb, need manually rerun program until segmentation fault occurs (during half day of reruns once fails :( ). so questions is, there way tell gdb rerun program until segfault? put breakpoint @ exit of program triggers run command, , don't forget set pagination off . information on settings commands available in breakpoint command lists section of gdb documentation. in short: set pagination off break exit commands run end after commands line you'll see next 2 lines being entered command execute when breakpoint reached.

osx - RHO mobiles +Ruby for mac OS X 10.6.4 -

i want work in rho mobiles had done r&d , cam know ruby needed that. want install ruby , rhomobile in mac os x 10.6.4 work in rhomobiles. had got idea through link:- http://docs.rhomobile.com/rhodes/install please me , guide me this!! 1 - need download tools http://rhomobile.com/rhostudio-mac 2 - need run both script ("install gems" , "install gems on rvm"). 3 - enter version (for exemple 1.8.7 or 1.9.2) , mac account password (for exemple - 12345) 4 - wait until install (3 - 7 minutes) 5 - drag rhostudio applications folder.

More efficient switch statement in jQuery/JavaScript -

i'm working on app uses switch statement provide custom animations depending on link has been clicked trigger animation. seems lot of code want, i'm having little trouble figuring out better way it. what happens when click on link, div open reveal hidden content , other divs slide side of screen. kinda custom accordian. my switch statement looks - history paramater taken id of clicked link. divs stored in object called rpsobject . switch( history ) { case "biography" : $("#" + rpsobject.boxid[1]).myanimation(); $("#" + rpsobject.boxid[2]).myanimation({ top : 80 }); $("#" + rpsobject.boxid[3]).myanimation({ top: 160 }); $("#" + rpsobject.boxid[4]).myanimation({ top: 240 }); $("#" + rpsobject.boxid[5]).fadeincloselink(); break; case "blog" : $("#" + rpsobject.boxid[0]).myanimation(); $("#" + rpsobject.boxid[2]...

Castle Windsor filter optional installers -

is there way filter installers when using iwindsorcontainer.install( iwindsorinstaller[] )? the reason asking have optional features packaged in installers in same assembly yes, can pass in instance of type derives installerfactory selection you.

etl - Logging with scriptella -

does know how instruct scriptella log catalina log should 1 write in etl.xml enable logging? scriptella using standard ju logging mechanism. if want see log messages of scriptella in catalina.out, easiest solution append following line conf/logging.properties file of tomcat installation: scriptella.level=fine by default level.info messages printed. see using java.util.logging

Forms in Ruby on Rails -

ive started using ruby on rails project of mine , have hit interesting walls. im using scaffolding instead of moving default show page after have entered data, want instead redirect page have created. key page form , half of form made of values entered in previous form. ive guessed have keep in memory instead of allowing written database. original idea query table , find last record multiple users not advisable. can help? examples great or point me in right direction im pretty familier c++, jave etc, understand computer jargon. thanks do care if data first form stored in database before going second form? if not can set create action in controller redirect new page want. depending on how managing user session, pull information user stored in first form. example if using devise handle session, have user enter username, email , password in first form, redirect profile form has separate email option. pre-populate field show user.email , give user option create separate ema...

ruby on rails - Update Attributes After Sign In Devise -

i using devise in rails 3 app. i update attributes of user on successful sign in. i doing following way: i added following code application_controller.rb def after_sign_in_path_for(user) @user = current_user @user.status = "online" @user.save root_path end is possible have different method doing , not using method used defining after_sign_in_path ? thanks in advance! you can hooks warden. ##config/initializers/devise.rb warden::manager.after_authentication |user,auth,opts| user.update_attribute(:currently_signed_in, true) end warden::manager.before_logout |user,auth,opts| user.update_attribute(:currently_signed_in, false) end

ruby - RubyZip: archiving process indication -

i adding tons of file archive looks this: print "starting ..." zip::zipfile.open(myarchive, 'w') |zipfile| my_tons_of_files.each |file| print "adding #{file.filename} archive ... \r" # ... end print "\n saving archive" # !!! -> waiting 10-15 minutes # want show percentage of completed job end after files added archive starts compress them (about 10-15 minutes). how can indicate going on rubyzip gem (actually want show percentage current_file_number/total_files_count ). you can override zip::zipfile.commit: require 'zip' require 'zip/zipfilesystem' module zip class zipfile def commit return if ! commit_required? on_success_replace(name) { |tmpfile| zipoutputstream.open(tmpfile) { |zos| total_files = @entryset.length current_files = 1 @entryset.each |e| puts "current file: #{current_files}, total files...

django-taggit: Is there a way to produce less db queries? -

say have model: class entry(models.model): ... tags = taggablemanager() when iterate on entry.objects.all() in template, entry.tags.all produces 1 more query database. possible reduce queries number? using select_related() (i know won't work, since django-taggit uses manytomany relation, sure there should way select entries related tags in 1 hit)? from django 1.4 onward, can use prefetch_related retrieve one-to-many relations on queryset in single query. unfortunately doesn't work brilliantly django-taggit, because 'tags' property manager rather true relation, , prefetch_related can't make sense of it. instead, need follow tagged_items relation: entries = entry.objects.prefetch_related('tagged_items__tag') you need go through similar contortions in template code access prefetched tags, because entry.tags.all run query rather making use of prefetch: {% tagged_item in entry.tagged_items %} <li>{{ tagged_item.tag.name ...

symfony1 - Symfony: turn off i18n on forms -

i turn off i18n calls on forms or form widgets enhance performance. possible? for choices form widget, can turn off auto translation adding option "translate_choices" set false.

android - What's mean PermGen Space? -

in eclipse when want import android method (ondestroy(), onpause()...) got error message permgen space. what's mean this, , can make workable? this question discusses problem. tomcat, believe solution same (increase permgen heap size).

windows - Sending HTTP request in Perl -

how can send request in perl on windows? get /index.html http/1.1 host: www.example.org cookie: test=quest you can using sockets: use io::socket; $sock = new io::socket::inet ( peeraddr => 'www.example.org', peerport => '80', proto => 'tcp', ); die "could not create socket: $!\n" unless $sock; print $sock "get /index.html http/1.0\r\n"; print $sock "host: www.example.org\r\n"; print $sock "cookie: test=quest\r\n\r\n"; print while <$sock>; close($sock); but might want consider using lwp (libwww-perl) instead: use lwp::useragent; $ua = lwp::useragent->new; $req = http::request->new(get => 'http://www.example.org/index.html'); $req->header('cookie' => 'test=quest'); # send request $res = $ua->request($req); # check ou...

vim how to set good indet without syntax highlighting? -

i have mapped f8 :set syntax=off<cr> . i editing without syntax highlighting, if switch syntax off, indent rules switched off. how can have indent without syntax highlighting? if vim autoindent ok , can set autoindent after "syntax off". on other hand, if use own index function. try run following command, may help. set indentexpr=<your function> or check indent function by: set indentexpr? and reset result after "syntax off"

c# - start a Process (executable) in Resources -

ive added executable file in resources, , when tried build project, got file not found exception [the system cannot find file specified]. here code process sortprocess = new process(); byte[] connect = sample.properties.resources.connect; sortprocess.startinfo.filename = connect.tostring(); pls me. can try create own demo project, add executables in resources, start process. thank ps: im trying access executable in resources embedded resource. you need make sure file copied on build time. in visual studio, right click on exe file in solution browser , go properties. believe under "compile action" select "always copy" or that. sorry don't have vs in front of me, there under properties. edit sorry answered in kind of hurry. don't think can or should embed executables this. happening in code reading entire exe file, byte byte, string, ofcourse not result in filename. embedded resources additional content images, text files , such....

c# 4.0 - What does my WCF service expect the request data to look like? -

i've got wcf-hosted service right self-hosted , defined this: [operationcontract] [webinvoke(requestformat = webmessageformat.json, method = "put", uritemplate = "/device")] void updatedevicelevel(zdevice device); the zdevice class looks this: public class zdevice { public bool? newpowerstate { get; set; } public int nodeid {get; set;} } i have simple mac client consumes service using http post. posts {"newlevel":27,"nodeid":6} \devices url , .net magically stuffs values zdevice object me. here. now however, need add basic security mix. i've done adding new parameter , "requestwrapping" method call: [operationcontract] [webinvoke(requestformat = webmessageformat.json, bodystyle=webmessagebodystyle.wrappedrequest, method = "put", uritemplate = "/device")] void updatedevicelevel(string password, zdevice device); what i'm trying figure out syntax server expecting consuming clients...

javascript - Prevent validation when using __doPostBack -

i using __dopostback manually in javascript, triggering validation on server side. when page refreshes, has validated fields on page , displaying errors in validationsummary control. is there way prevent this? i not calling page.validate() on server. use validation groups. http://msdn.microsoft.com/en-us/library/ms227424.aspx

javascript - Getting widths of dynamic float divs -

i building dynamic dropdown navigation. in dropdown there multiple floating divs, between each 'row of items' have add horizontal divider. can't set static width because text-length of items dynamic , may not wrap. so reading each container, reading div items, want read width of items add divider can't manage it. $('.mutopnavdropdown').each(function(i, e) { var iwidth = 0; $(this).find('.mainsubnavrowitem').each(function(ii, ee) { if (iwidth > maxwidth) alert('divide!'); alert($(ee).width() +'-'+ $(ee).offsetwidth +'-'+ $(ee).clientwidth); iwidth += $(ee).width(); }); }); how read floating div no width value , dynamic content inside width ? your code works me. divs visible? if divs set display none jquery not able return width.

modelica - How can I make a string executable? -

i'm trying execute string in modelica. string saved in variable in order able change when need to. function test input string incomp="resistor.r:=2"; output string outcomp; algorithm outcomp:=incomp; end test; could please i using dymola. what need following. -read component names text file (or input them while executing function) -then change parameters of these components. code example: function test input string incomp="resistor"; //entered user, or read text file output real result; algorithm incomp.r :=2 ; /*this incorrect since wouldn't understand want enter : resistor.r := 2; */ result := incomp.r ; //in order view result end test; what trying not possible in modelica. may tools have "reflective api" allows (or perhaps built-in function takes command string , executes it) there no universal api works across tools. if want run bunch of simulations in dymola different pa...

.net - Image Cropping Control for WinForms with Selection Rectangle -

i need control allows user select rectangular area of image , apply simple "crop selection" feature. found several options none of them consistent large images - control must able show entire image (like zoom mode in picturebox). controls i've found use picturebox normal sizemode, limits crop selection area when picturebox exceeds container bounds.

python - How to delete an object and all related objects with all imageFields insite them (photo gallery) -

i have photo gallery album model (just title , date , stuff) , photo model foriegn key album , 3 imagefields in (regular, mid , thumb). when user delete album need delete photos reletaed album (from server) db records point album , album itself... couldn't find , actualy found many answers 1 oposite other. can 1 please clarify point, how beeing done in real world? thank much, erez here possible answer question figured out: getting list of albums in string, in case separated commas you need import shutil, then: @login_required def remove_albums(request): if request.is_ajax(): if request.method == 'post': #if ajax call delete ok list of albums delete albums_list = request.request['albums_list'].rsplit(',') album in albums_list: obj_album = album.objects.get(id=int(album)) #getting directory images need deleted dir_path = media_root + '...

python - Is it possible to include a library like lxml without installing it? -

i need perform xml parsing using machine may not have permission install libraries in. possible include python library lxml source? have tried using virtualenv ? should let use lxml without "installing" it.

asp.net mvc - RenderPartial not working -

i have simple partial view returns (renders) list of synonyms of given word. i'd use partial view inside view , use @html.renderpartial("synonymfinder", new { word = "something" }) inside view. error: cs1502: best overloaded method match 'system.web.webpages.webpageexecutingbase.write(system.web.webpages.helperresult)' has invalid arguments this simplest scenario. removed parameters , used @html.renderpartial("synonymfinder") , still same problem. what's wrong? in mvc 3 should use: @html.partial("synonymfinder", new viewdatadictionary { { word = "something" } }) note 2nd parameter of type viewdatadictionary . if don't pass explicitly that, helper use overload takes object 2nd parameter , uses model instead of route values.

Python command to get last part file -

i have .dat file like: step1 a1 b1 a2 b2 a3 b3 step2 a4 b4 a5 b5 . . . stepn bn bm each step has 2 column (a , b). need scrip, looks last step , gives me "an" , "am" thank help! something efficient, works long files (uses no memory): with open("data.dat") f: # file automatically closed line in f: # goes through line (no need store them) pass step, an, bn, am, bm = line.split() # splits last line read (on spaces) if need convert numerical values, int(an) or float(an) work.

objective c - MFMailComposeViewController rotation -

details - - ios - 4.2, xcode - 3.2.5, device - ipad 2, platform - openframeworks i'm using mfmailcomposeviewcontroller email screengrab attachment. it's working fine i'm having issues rotation. my mfmailcomposeviewcontroller added viewcontroller panel resides @ top of screen each orientation. result, mfmailcomposeviewcontroller appears in correct orientation perfect. problem appears when cancel button pressed. options appear if orientation portrait. image taken when viewed in landscape. http://augmatic.co.uk/store/ipad_email_rotation.jpg here code: uiimage* screengrab = app->visualsmanager->getscreengrab(); mfmailcomposeviewcontroller *picker = [[mfmailcomposeviewcontroller alloc] init]; picker.mailcomposedelegate = self; picker.modalpresentationstyle = uimodalpresentationfullscreen; [picker setsubject:@"check out image!"]; nsarray *torecipients = [nsarray arraywithobject:@"test@email.com"]; [picker settorecipients:torecipients]; n...

objective c - Get String From Array to call method -

i'm trying string in call array. have no luck. it's being passed class. mainclass.h #import first @class first; @interface mainclass : uiviewcontroller{ nsmutablearray *listarray; } /////////////////// mainclass.m first *first = [[first alloc] init]; listarray = [[nsmutablearray alloc]init]; [listarray addobject:@"first"]; [listarray addobject:@"second"]; int aslot = 0; int suma; float level = 5, insample = 10; nsstring *slota =[listarray objectatindex:aslot]; suma = [slota out:insample andlevels:level]; ///////// first.h -(float)out:(float)insample andlevels:(float)level; first.m -(float)out:(float)insample andlevels:(float)level{ float outsample = insample + 10 * level; return outsample; } i want slota (the class) equal string array "first" or "second", can call method. i have table when select first, sends samples , other parameters class processing returns mainclass. ...

linq - Most elegant way to process first IEnumerable item differently -

what elegant way process first ienumerable item differently others, without having test on each iteration? with test on each iteration, this: // "first item done" flag bool firstdone = false; // items ienumerable<something> foreach (var item in items) { if (!firstdone) { // once processdifferently(item); firstdone = true; continue; } processnormally(item); } if this: processdifferently(items.first()); processnormally(items.skip(1)); // calls `items.getenumerator` again it invoke getenumerator twice, avoid (for linq-to-sql cases, example). how it, if need several times around code? if needed in several places, i'd extract method: public void process<t>(ienumerable<t> source, action<t> firstaction, action<t> remainderaction) { // todo: argument validation using (var iterator = source.getenumerator()) { ...

javascript - Using getSelected in MooTools -

i'm new js , mootools , i've been having funny error using getselected() mootools 1.3.2. i've looked @ other posts have similar code , haven't been successful. i'm using getselected try , value of option , reason, browser isn't calling it. here's html <select id="id_method" name="method"> <option selected="selected" value="">---------</option> <option value="au">auction (best price wins)</option> <option value="fi">fixed price</option> <option value="fr">free item/donation</option> <option value="mu">multiple items , prices</option> <option value="no">no price displayed</option> <option value="tr">trade</option> </select> here's js window.addevent('domready', function() { ... $('id_method').addeven...

css - how to align text and image with in anchor tag -

this sample code in trying position text below image in anchor. have problems if there more elements in html , browser minimized image , text going miss aligned output-'text' , image , text below image should align'center' , should stay aligned if browser minimized. <head> <style type="text/css"> .cimg { width:100%; text-align:center; } .cimga { display:block; margin-top:5%; } .cimgimg { position:absolute; top:10px; bottom:0px; right:48% } </style> </head> <html> <body> <div class="cimg">text</duiv> <div class="cimg"> <a > imagetag/call </a> </div> </body> </html> your widths, paddings, , margins need in pixels.

Alternative to jQuery livequery plugin? -

i need check when element alive, i'm doing: $('#obj').livequery(function() { ... }); how can live method or way? this old question, record, here 5 cents: an alternative livequery use publish/subscribe approach example implementation jquery tiny pub/sub: really, really, tiny pub/sub implementation jquery. i use it, example, in way: // inform of dom change (mostly through ajax) $.publish("/table/loaded"); // re-execute plugin $.subscribe("/table/loaded", function(e, data) { $("#my_id input[name='date']").datepicker(); }); +info : understanding publish/subscribe pattern greater javascript scalability

php - How to link images with records from the database? -

my site having profiles, each profile has few images. users upload images themselves. need link images disk , profiles in mysql table. tell me best way realize functionality more flexibility? ps i'm using codeigniter 2 + mysql. as using codeigniter. assume using file uploading class. after successful completion of upload, can use $this->upload->data() which returns array contains data related upload. example array array ( [file_name] => mypic.jpg [file_type] => image/jpeg [file_path] => /path/to/your/upload/ [full_path] => /path/to/your/upload/jpg.jpg [raw_name] => mypic [orig_name] => mypic.jpg [client_name] => mypic.jpg [file_ext] => .jpg [file_size] => 22.2 [is_image] => 1 [image_width] => 800 [image_height] => 600 [image_type] => jpeg [image_size_str] => width="800" height="200" ) its better stor...

c# - Exception in GUI thread causing vshost.exe to crash -

i think visual studio 2008 (.net 3.5) corrupted. if start new windows forms project in new solution, add code double[] x = new double[2]; x[3] = -1.0; to form_load handler (or button handler), , try debug program, crashes immediately, not throwing exception, crashing. if put same code in form constructor or in main, exception gets thrown normal. any ideas might going on? don't worry, vs fine. the form load handler (ultimately) invoked windows message loop, exception handling little different. see here more details.