Posts

Showing posts from May, 2013

math - How can I solve an equation with two variables where x is maximum? -

lets have equation - x^2+y^2=100 - there's more 1 solution. want make mathematica 8 give me solution (where natural numbers involved) x maximized (i.e x=10, y=0) i'm pretty new mathematica - , got confused whats going on... without diophantine explicit requierment: maximize[{x , x^2 + y^2 == 100}, {x, y}] (* -> {10, {x -> 10, y -> 0}} *) edit as can see, result 2 elements list. first element ( 10 ) value x (the function maximization performed). second element {x -> 10, y -> 0} , corresponding assignment rules variables @ max point. note here maximizing x , value 10 repeated in both elements, not case, want maximize general function of variables, , not vars themselves. in particular case, have 2 straightforward ways assign max value of x n : using first element of list: n = first@maximize[{x , x^2 + y^2 == 100}, {x, y}] or more general, using appropriate rule: n = x /. last@maximize[{x, x^2 + y^2 == 100}, {x, y}]

Finding all records containing a given subfield in mongodb -

in mongodb, can find records in collection in database db contain particular field using following query var doc = db.collection_name.find({field_name:{$exists:true}}) now consider following document: { "somefield":"someval", "metadata": {"id":"someval", "client_url":"http://www.something.com" } } what query getting records having id field in metadata ? please help. thank you you can use dot notation reference sub-document fields var doc = db.collection_name.find({"metadata.id":{$exists:true}})

vbscript - How do you rename a file URL to a variable in VB script? -

i'm making program in microsoft excel using bunch of vb script macros. 1 of macros gets data "from web" , retrieves table sheet in excel. when "from web", copied , pasted url html file have on desktop. location of program going change frequently, need able have cell in excel can specify url, macro reference. here code below: sub importswipedatawithtitlesbeta() ' ' importswipedatawithtitlesbeta macro ' ' keyboard shortcut: ctrl+shift+k ' sheets("import swipe data").select cells.select selection.delete shift:=xlup range("a3").select activesheet.querytables.add(connection:= _ "url;file:///c:/users/sean/desktop/attendance program adc/acs%20onsite%20se%20complete.htm", _ destination:=range("$a$3:$c$3")) .name = "acs%20onsite%20se%20complete_8" .fieldnames = true .rownumbers = false .filladjacentformulas = false .preserveformatting = true .refreshonfileopen

asp.net mvc 3 - MVC data annotations and templates -

in mvc scaffold code understand template being used , can define own templates. also, data annotations on object sent view being taken account. but modelitem? @foreach (var item in model) { <tr> <td> @html.displayfor(modelitem => item.referencenum) </td> modelitem unuses background variable. displayfor expects method receives single parameter. implementation of method is, de-facto, right side of lambda expression: item.[something] . happens item.[something] totally ignores modelitem . replacing modelitem item would, of course, result in compilation error, because item belongs model , , it's not object created when calling anonymous method { item.[something] } . that's why modelitem can practically name doesn't exist in symbols table (i.e. compiler doesn't have definition for).

Starting an apk on boot in Android -

is there way start android application on boot? perhaps adding init.rc script? if "android application", mean user interface, make home screen. if "android application", mean have small hunk of code want run around time of boot, set broadcastlistener boot_completed broadcast. you manipulate init.rc if doing things creating custom firmware.

logging - Where are SQL Server connection attempts logged? -

does sql server has external log file or internal table attempted connections, or kind of info put somewhere in windows event log? you can enable connection logging. sql server 2008, can enable login auditing. in sql server management studio, open sql server properties > security > login auditing select "both failed , successful logins". make sure restart sql server service. once you've done that, connection attempts should logged sql's error log . physical logs location can determined here .

c# - Expression.DebugInfo How Do I Tag Expressions? -

so know expression.debuginfo used for, , have debug expression created, how tag other expressions debug info? here's i'm trying basic test: using system; using system.collections.generic; using system.linq; using system.text; using system.linq.expressions; using system.reflection; namespace expressiondebugtest { class program { static void main(string[] args) { var asm = appdomain.currentdomain.definedynamicassembly(new assemblyname("foo"), system.reflection.emit.assemblybuilderaccess.runandsave); var mod = asm.definedynamicmodule("mymod", true); var type = mod.definetype("baz", typeattributes.public); var meth = type.definemethod("go", methodattributes.public | methodattributes.static); var sdi = expression.symboldocument("testdebug.txt"); var di = expression.debuginfo(sdi, 2, 2, 2, 12); var exp = express

CSS inside xml response in jquery ui autocomplete -

is there way give different css class part of label inside xml response? in other words label value label: $( "name", ).text() + ", " + ( $.trim( $( "countryname", ).text() ) || "(unknown country)" ) + ", " + $( "countrycode", ).text() i wish give different css class $( "countrycode", ).text() since wish font have smaller others (name , countryname) is there way? success: function( xmlresponse ) { var data = $( "geoname", xmlresponse ).map(function() { return { value: $( "name", ).text() , label: $( "name", ).text() + ", " + ( $.trim( $( "countryname", ).text() ) || "(unknown country)" ) + ", " + $( "countrycode", ).text() , id: $( "geonameid", ).text() }; }).get(); wrap in span , give span class. since using xml, may consider using more meaningful tag , styling (unless xhtml).

Wrapper C++ in C++/CLI clr:safe for C# COM Interop -

is there way make wrapper clr:safe project in c++ unmanaged? my little story started way, "boy, have project 'c# com interop' 1 have use 'c++ library' , must result in 'one' (dll com)." ok, after few days searching, realized possible use c++ library in 2 ways: adding in resources , calling pinvoke or creating wrapper c++/cli. pinvoke can not have 1 dll(right?). opted second option "wrapper c++/cli". seemed easy @ beginning, recompile library visual studio 2005 2010, create clr project (with keypair.snk , re-signed) added library. works! \0/ use ilmerge, ohhhoo this? clr:safe? why? ok, try recompile c++/cli clr:safe erros appears... how can fix this? thanks in advanced, ilmerge isn't right tool this. instead, compile c# .netmodule, , pass c++/cli linker along c++/cli object files.

bash restart sub-process using trap SIGCHLD? -

i've seen monitoring programs either in scripts check process status using 'ps' or 'service status(on linux)' periodically, or in c/c++ forks , wait on process... i wonder if possible use bash trap , restart sub-process when sigcld received? i have tested basic suite on redhat linux following idea (and didn't work...) #!/bin/bash set -o monitor # can explain this? discussion on internet needed trap startprocess sigchld startprocess() { /path/to/another/bash/script.sh & # 1 restart while [ 1 ] sleep 60 done } startprocess what bash script being started sleep few seconds , exit now. several issues observed: when shell starts in foreground, sigchld handled once. trap reset signal handling signal()? the script , child seem immune sigint, means cannot stopped ^c since cannot closed, closed terminal. script seems hup , many zombie children left. when run in background, script caused terminal die ... anyway, not work @ all. have

rails 3: easiest way to load a large seed list (20,000 single words) into a table (using rake seed) on a Heroku app? -

on local dev machine have word list, 1 word per line, 20,000 words need load new table i'll call wordlist. and need create exact same table on several heroku apps well, dont have local file storage. the table schema id:integer , word:string i've read numerous articles using seed.rb ... don't quite see how make work word list in file on dev machine, loading list table on local dev machine , on remote heroku app instances. any ideas appreciated! i take word list , stick in csv, 1 word on each line. should take 2 minutes. use fastercsv gem iterate through csv have saved in /lib/data. can stick /db/seeds.rb. seeds.rb fastercsv.foreach("#{rails_root}/lib/data/words.csv", :headers => :first_row) |row| word.create_by_name(row[0]) end run rake db:seed , that's it. btw :headers => :first_row means skip first row if have title on top. if don't leave part out. for remote file: require 'open-uri' fastercsv.foreach(open(&q

validation - RelaxNG - *any* attribute? -

is there way define any name attribute? i'm validating code users can , apply own attributes tags , like, don't impact project. <define name="div"> <zeroormore> <attribute name="*"> <text /> </attribute> </zeroormore> <text /> </define> <anyname/> seems looking for: <define name="div"> <zeroormore> <attribute> <anyname/> </attribute> </zeroormore> <text/> </define>

Order data frame by two columns in R -

i'm trying reorder rows of data frame 2 factors. first factor i'm happy default ordering. second factor i'd impose own custom order rows. here's dummy data: dat <- data.frame(apple=rep(letters[1:10], 3), orange=c(rep("agg", 10), rep("org", 10), rep("fut", 10)), pear=rnorm(30, 10), grape=rnorm(30, 10)) i'd order "apple" in specific way: appleordered <- c("e", "d", "j", "a", "f", "g", "i", "b", "h", "c") i've tried this: dat <- dat[with(dat, order(orange, rep(appleordered, 3))), ] but seems put "apple" random order. suggestions? thanks. reordering factor levels: dat[with(dat, order(orange, as.integer(factor(apple, appleordered)))), ]

c# - Firefox browser does not reload the update CSS/JS files -

i'm having problem in firefox browser, because everytime update css or js files, need clear cache of firefox browser updated files. i'm using xsp2 server because developed webapp using c# , asp.net in ubuntu. is there way automatically reload updated css/js files in firefox browser , implemented in server-side or in webapps? please advise. many thanks. you mess cache of headers, easiest thing append updated elements querystring when want them change... i know doesn't sound solution, when begin minifying , combining js , css files performance reasons, of solutions change url these resources when change anyway...

Django cropper - getting additional resized images from cropped image -

i have problem getting additional resized images croped image. using django-cropper 0.1. model cropped image have part of code this: class cropped(models.model): def __unicode__(self): return u'%s-%sx%s' % (self.original, self.w, self.h) def upload_image(self, filename): return '%s/crop-%s' % (settings.root, filename) def save(self, *args, **kwargs): #force_insert=false, force_update=false, using=none): source = self.original.image.path target = self.upload_image(os.path.basename(source)) image.open(source).crop([ self.x, # left self.y, # top self.x + self.w, # right self.y + self.h # bottom ]).save(django_settings.media_root + os.sep + target) self.image = target super(cropped, self).save(*args, **kwargs) but want have additional resized images cropped image change code little , looks that: cla

php - OPP nomenclature question: object->function($param) -

in oop, call when do: $o = new classinstance(); $o->somefunction($p); for example, i'm passing parameter p function somefunction. easy. but how articulate calling of function in class object, classinstance? you're not passing function somefunction object classinstance.... say: "call somefunction function in classinstance object?" thanks. "call method somefunction object $o (which instance of class classinstance ), passing $p argument.". rephrasing clarity: $instance = new classname(); $instance->somemethod($p); "call method somemethod object $instance (which instance of class classname ), passing $p parameter (or argument)".

jquery - Is it possible to export Silverlight canvas to HTML with scripts -

in 1 of our application have implement item drag/drop functionality on page , later export page html along jquery , css. i use silverlight application development give greater user experience. add item drag , drop facility 1 item container another. but final thing want implement is, once ready our drag , drop on canvas/page export canvas/page pure html along jquery , css. so question is: possible export canvas html? if yes please provide sample code. if understand question correctly, want end-result of silverlight operations displayed using html without using silverlight. if correct simple option occurs me is: render canvas png on client, send server, , serve image in html. there lots of how-to's suggest googling: http://www.google.co.uk/search?sourceid=chrome&ie=utf-8&q=silverlight+how+to+export+a+canvas+to+a+bitmap&safe=active if wanting else (e.g. generating interactive html content) please clarify question.

php - PDO pass by reference notice? -

this: $stmt = $dbh->prepare("select thing table color = :color"); $stmt->bindparam(':color', $someclass->getcolor()); $stmt->execute(); yields this: runtime notice variables should passed reference though still executes. this: $stmt = $dbh->prepare("select thing table color = :color"); $tempcolor = $someclass->getcolor(); $stmt->bindparam(':color',$tempcolor); $stmt->execute(); runs without complaint. i don't understand difference? the second parameter of bindparam variable reference . since function return cannot referenced, fails strictly meet needs of bindparam parameter (php work though , issue warning here). to better idea, here's , example: code produce same results second example: $stmt = $dbh->prepare("select thing table color = :color"); $tempcolor = null; // assigned here $stmt->bindparam(':color',$tempcolor); $tempcolor = $someclass->getcolo

algorithm - Sorting a partially sorted array -

possible duplicate: interview q: sorting sorted array (elements misplaced no more k) i have partially sorted array property every element within d units of sorted position. wondering if there way sort array -- exploiting fact -- in less n log n time. off top of head... create "sliding window" of size 2d. start @ [0,2d). sort elements in window; elements 0 through d-1 guaranteed correct. slide window forward d, it's [d,3d). sort elements, guaranteeing elements d through 2d-1 correct. slide forward d, [2d,4d). sort those. , on. each sort o(d log d), , takes n/d steps end, o(n/d * d log d) = o(n log d). if d constant, that's o(n). [edit] you make point in comment; did not prove each iteration preserves property every element within d units of proper position. so... lemma: if array property every element within d units of proper position, , sort contiguous subsequence within create array a', every element in a' wi

rest - how can I use active Record queries with salesforce as the data-store? -

Image
i connecting salesforce.com data-store , accessing rest api's. currently, query, have use soql, query language. how can use activerecord type 'where' queries instead? you don't have use soql retrieve records via salesforce.com rest api, if retrieving id of record. this, can use following syntax: /vxx.x/sobjects/sobjectname/id/ to retrieve records meet specific clause other id, don't believe there alternative soql @ point directly in rest api. however, if using ruby, there ruby toolkit salesforce support using active record style syntax. open source project , can find out more here: http://quintonwall.com/wp-content/uploads/2011/02/rubytoolkit-gettingstarted.pdf here couple of examples above document: there toolkits other languages, not sure of support active record style record access.

Android: Using focus mode FOCUS_MODE_EDOF during image capture -

has used focus mode focus_mode_edof, provided in android cameraparameters? http://developer.android.com/reference/android/hardware/camera.parameters.html#focus_mode_edof i need know if mode used tap focus on object selected (as depicted in iphone 4 camera specs, http://www.apple.com/iphone/features/camera.html )? if yes, need implement touch listeners on preview screen determine part of preview selected? to answer question: no, not mode want use touch-to-focus. edof stands "extended depth of field", , in case, refers camera fixed focus uses optical , computational tricks create image beyond distance in focus. using fact different wavelengths of light affected differently lens, color channels can sharpened separately , combined. allows larger aperture (and better performance in low-light conditions) conventional fixed-focus lens, have focused @ hyperfocal distance focus entire scene. edof cameras common on nokia phones. because don't have moving par

php - Following a tutorial resulted in broken MAMP installation -

hooked mamp on macbook (osx) month ago , fine. followed bogus tutorial on how debug php in eclipse (didn't work), , php files open with: file:///applications/mamp/htdocs/ instead of: http://localhost:8888/ which displays code now. php files can viewed on server if append filename localhost url in browser, can tell me how configure php/mamp properly? i'm new @ stuff , tried fix on own, no dice =/ most of work reconfiguring /etc/apache2/httdp.conf. configuring apache vast topic, might better off using google find tutorial. @ least, you'll need handler eg.: # php file handlers. <ifmodule php5_module> addtype application/x-httpd-php .php addtype application/x-httpd-php-source .phps <ifmodule dir_module> directoryindex index.html index.php </ifmodule> </ifmodule>

Silverlight 4 : Resize Dynamic Rectangles Using Thumb -

xaml <canvas x:name="cvsburstimage" mouseleftbuttondown="cvsburstimage_mouseleftbuttondown" style="{staticresource burstcanvasstyle}"> <viewbox x:name="vbburstimage" style="{staticresource viewboxcanvasstyle}"> <image x:name="imgburstimage" source="../assets/images/default_burst_image.png" imagefailed="imgburstimage_imagefailed"/> </viewbox> </canvas> i facing strange problem need draw rectangles on canvas , make them resizable as moveable (place them anywhere in canvas). i have achieved via mouse events of canvas; private void canvas_mouseleftbuttondown(object sender,mousebuttoneventargs e) {} private void canvas_mousemove(object sender, mouseeventargs e) {} private void canvas_mouseleftbuttonup(object sender, mousebuttoneventargs e) {} explanation; on mouseleftbuttondown, start capturing mouse cordinates ,

Having problem while parsing XML document in blackberry -

i trying to parse data 1 url, it's not displaying parse data on screen: public class xml_parsing_sample extends uiapplication { //creating member variable mainscreen mainscreen _screen= new mainscreen(); //string variables store values of xml document string _node,_element; connection _connectionthread; public xml_parsing_sample() { // todo auto-generated constructor stub _screen.settitle("xml parsing");//setting title _screen.add(new richtextfield("requesting.....")); _screen.add(new separatorfield()); //_screen.add(new richtextfield("xml data")); pushscreen(_screen); // creating screen "system.out.println("1111111111111");" //creating connection thread run in background _connectionthread = new connection(); "system.out.println("222222222222222");" _connectionthread.start();//starting thread operation "system.out.println("after conn

linux - How to decrease the size of generated binaries? -

i know there option "-os" "optimize size", has little affect, or increase size on occasion :( strip (or "-s" option) removes debug symbol table, works fine; can decrease small propotion of size. is there other way go furthur? apart obvious ( -os -s ), aligning functions smallest possible value not crash (i don't know arm alignment requirements) might squeeze out few bytes per function. -os should disable aligning functions, might still default value 4 or 8. if aligning e.g. 1 possible arm, might save bytes. -ffast-math (or less abrasive -fno-math-errno ) not set errno , avoid checks, reduces code size. if, people, don't read errno anyway, that's option. properly using __restrict (or restrict ) , const removes redundant loads, making code both faster , smaller (and more correct). marking pure functions such eleminates function calls. enabling lto may help, , if not available, compiling source files binary in 1 go (

android - dynamic layout with two buttons problem -

how can set buttons in linearlayout dynamically? want android mobiles different display sizes can use app. code <linearlayout android:id="@+id/linear_layout_main2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <button android:id="@+id/bt1" android:text="go" style="@style/button_font" android:clickable="false" android:background="@drawable/box1" android:layout_marginleft="6px" /> <button android:id="@+id/bt2" android:text="on" style="@style/button_font" android:clickable="false" android:background="@drawable/box1" android:layout_marginleft="6px" /> </linearlayout> style-code <style name="button_font" parent="@android:style/textappearance.medium"> <item name="android:layout_wi

deployment - Jenkins - Promoting a build to different environments -

i hoping guidance on best way promote build through environments. we have 3 environments, dev, staging, prod. the dev jenkins build running in continuous integration set-up, code checked in subversion, jenkins run new build (clean, compile, test, deploy). the tricky bit when comes staging , prod. the idea able manually promote successful dev build staging. staging build check out dev's svn revision number, build, test, deploy staging , create branch in svn. lastly release manager manually promote staging build prod. prod build check out branch previous staging build, deploy prod , tag branch release. i have tried use combination of promotion builds plugin , paramterized trigger plugin no luck. subversion revision number doesn't seem passed between dev build staging build. does have guidance on process promote build through multiple environments? in scenario, why need go , label branch in svn? don't use svn, w/ tfs, when hudson/jenkins gets co

Facebook IFrames on Mobile? -

wondered whether possible facebook business iframe page appear on mobile versions of facebook? if not possible has heard whether feature introduced in future? if mean page tabs displayed on mobile site / native apps, answer sorry, no, that's not supported.

Share URL on Google+ -

is possible share url on google+ it´s possible facebook or twitter? via hyperlink specific url? http://plus.google.com/share?url=http://example.org/ ... i don´t want use +1 button because need style hyperlink selfmade icon. thanks lot. yes, possible. click on post options list (it's small circle in upper right part of post) , you'll see option says 'link post'. click it!

java - http post request for android -

i want send post request in java android. i use code : httpclient httpclient = new defaulthttpclient(); httppost httppost = new httppost("myurl"); try { // add data list<namevaluepair> namevaluepairs = new arraylist<namevaluepair>(2); namevaluepairs.add(new basicnamevaluepair("artist", "amy macdonald")); namevaluepairs.add(new basicnamevaluepair("title", "don't tell me it's over")); namevaluepairs.add(new basicnamevaluepair("album", "don't tell me it's over")); httppost.setentity(new urlencodedformentity(namevaluepairs)); // execute http post request httpresponse response = httpclient.execute(httppost); } catch (clientprotocolexception e) { // todo auto-generated catch block } catch (ioexception e) { // todo auto-generated catch block } the problem when use : httpresponse

javascript - getElementByTagName question -

i know if want find group of elements, getelementsbytagname method , returns nodelist. if looking tag name "body" , why need add [0] after ("body") element? there 1 body tag in html document. var body = document.getelementsbytagname("body")[0]; body.classname = "unreadable"; why cant write code without index[0] this var body = document.getelementsbytagname("body"); body.classname = "unreadable"; if write code class unreadable not added body tag ...why? because document.getelementsbytagname allways returns nodelist. if want find easier way retrieve body can use document.body

actionscript 3 - 3d shapes in flex -

i drawing 3 circles in flex application, using actionscript. these circles pure 2d images, not looking good. how can make 3d using shadows or shades inside shape. cheers,pk if want 3d-ish effects, should usage of bevelfilter. have found links show how can use filter: http://www.republicofcode.com/tutorials/flash/as3filters/ http://wonderfl.net/c/6axw http://www.flashactionscripttutorials.com/?p=projects&actionscript-functie=applyfilter if want genuine 3d-objects, should use 3d-library (i recommend away3d).

localization - display German special characters correctly in Delphi 2007 -

i need display german special characters correctly in delphi 2007 characters "ü" appear "?" in label components any advise thanks unexpected question mark ( ? ) shows when text goes trough code page conversion fails. since delphi 2007 not unicode enabled, label's caption ansistring . text you're putting in there goes trough @ least 1 code page conversion fails, , you'll have figure out conversion takes place , why it's failing. common causes code page conversions: the text label comes dfm (you wrote in object inspector). machine , test machine both use different "default code pages non-unicode applications". should never see while testing on machine. the text label came database, , either database has wrong code page or test machine has wrong code page: when delphi helpfully tries convert code page, fails. the character set property of label's font wrong. here's bit of code put ü character in label

python - Django recive array ajax problem -

i'm sending array via post reqest django server if use dev server, see <querydict: {u'arr[]': [u'1', u'2']}> if send apache+mod_wsgi sever, see <querydict: {u'arr[]': [u'2']}> olny last item, ideas? upd: dev sever on local pc, if apache+mod_wsgi on local pc fine, if on remote - last item my solution: serialize array json2 json.stringify(my_array) and deserialize import json json.loads(str)

iphone - How To Get App Version Number From User? -

i want log app version number when user sends feedback, in email. how can number? nsdictionary* infodict = [[nsbundle mainbundle] infodictionary]; nsstring* versionnum = [infodict objectforkey:@"cfbundleversion"]; nsstring *appname = [infodict objectforkey:@"cfbundledisplayname"]; nsstring *text = [nsstring stringwithformat:@"%@ %@",appname,versionnum]; you can send both appname , version number using code.

c# - save xml to xmlfile -

xelement xml2 = new xelement("topmenus", b in dc.topmenuu() select new xelement("topmenu", new xelement("id", b.id), new xelement("title", b.title), new xelement("parent_fk", b.parent_fk), new xelement("pageurl", b.pageurl))); xml2.save(server.mappath(".") + "\\xml\\topmenu.xml");// line error results in error: the process cannot access file 'c:\inetpub\wwwroot\iranfairnew\xml\topmenu.xml' because being used process. this error while simultaneously looking @ browser ie, , mozilla can run program asp.net 3.5 how can solve problem? use process explorer check nothing using file. looks file in use

visualization - faceted browsing + chart plotting for structured data -

i'm looking web open source solution browsing structured dataset, integrated in existing web application given structured dataset (a table 50k rows), user filter data using facets , chart displayed showing filtered data. i'm thinking similar google refine using facets , scatter plot facet. wonder if there more modular google refine in order integrated web application. know of library or framework or lightweight solution? google refine have python library http://pypi.python.org/pypi/refine-client might worth check out.

php - MYSQL database design to Serialize or not -

we have existing application runs on php , mysql. in process of adding fine grained user authorization, users access resources. there few thousand users , approx 100 resources (although both expected grow). my db design like: users: id, name, email resources: id, resource option 1 so, if approached typical db normalisation in mind, have following table well. guess follow structure of users being denied permission unless there record in user_resources table. if permission subsequently removed particular resource, delete row user_resources table. *user_resources:* user_id, resources_id option 2 alternative forget user_resources table , create new column in users table (called permissions or similar) , store serialized value of users permissions in users table. each time need check user's permission, have unserialize value. which approach considered better practice, , there major pro's or con's either? option 1 way go unless have solid arguments

ruby on rails - Using Capybara matchers in a controller spec with ActionController::TestResponse -

i'm calling render_views in rspec controller spec can test content of response directly rather using separate view specs. sure enough view rendered , returned in response.body . the problem how parse content of page in expressive way. i'm trying use capybara matchers has_content , has_field etc. work fine in request specs, don't work actioncontroller::testresponse or string returned .body . where's rspec api parsing view? what's point of render_views if can't inspect them? if want spec rendered views suggest in request/acceptance/feature spec, not controller. controller specs should treated more unit specs controllers. render_views can used if want make sure view renders without problems, shouldn't go deeper in terms of speccing view.

sql - How can I get the number of rows in dynamic query's result? -

i have created 1 dynamic query , works well. execute query using: exec sp_executesql @sqlquery where @sqlquery 1 dynamic query. my question how can return number of rows present after execution of query? hope question clear. thanks in advance:) you can use @@rowcount return last query effected row count. exec sp_executesql @sqlquery declare @rowcount int set @rowcount = @@rowcount select @rowcount numofrows

iphone - iOS Interface Builder - How to reset image to default size? -

i using images in both uiimageviews , uibuttons. i've been re-sizing them bit , don't remember original sizes were. there easy way within interface builder "reset" image whatever it's default size is? yes use apple(command)+equal key image view or button selected.

database - Difference SHOW INDEX, SHOW INDEXES and SHOW KEYS in MySQL -

what's difference between show index, show indexes , show keys command in mysql? if any. same results. mysql doc they synonyms.

function - subquery within alter table in db2 -

i want run subquery within alter table command in db2. alter table user alter column userid set generated identity (start 2646) the above query works fine. want give start value query below. alter table user alter column userid set generated identity (start (select max(userid) user)) i tried achieve using functions , stored procedures. problem table name should specified in both. want alter table query 40 tables. create function findmax (tablename varchar(64), columnname varchar(255)) returns integer return select max(columnname) tablename i have done before using sql scripts , doing multiple passes against database. you can same if using findmax function if have sql this: select 'findmax( ' || tabname || ' , ' || colname || ')' syscat.columns identity = 'y

How to identify which 3rd party flash object called a Javascript function? -

i have page multiple flash objects written third party , can't changed. call js function don't seem pass identifying parameters. there way determine inside function flash object called it? this may not cross-browser compatible, , in end may find "flash" calling function, rather specific movie, way can think of: function myfunction() { if (myfunction.caller) { console.log("this function's caller " + myfunction.caller); } else { console.log("this function called directly"); } /* rest of function */ } this should run in firefox , log console.

java - Grails framework method addTo throws exception on multiple invoke -

i want add subscriptions user class, invoking "addto" method, here code: if (params.jobs == "on") { user.addtosubscriptions(category.findwhere(id: 1l)) } else { user.removefromsubscriptions(category.findwhere(id: 1l)) } the "params" come checkboxes, user can subscribe category setting checkboxes. code above invoked when form submitted. doesn't work when user changes more 1 categories, think of same code above different params.x, this if (params.offers == "on") { category cat = category.get(2) if (!user.subscriptions.contains(cat)) user.addtosubscriptions(category.findwhere(id: 2l))//needs long variable } else { user.removefromsubscriptions(category.findwhere(id: 2l)) } what happens category wich first in code gets added , removed, other throw following exception: org.hibernate.exception.genericjdbcexception: not execute jdbc batch update edit: line in wich ex

ruby on rails - How to implement one vote per user per comment? -

i have comment controller has method vote_up , vote_down how vote_up works. my comment model has description , count field. def vote_up @comment = comment.find(params[:comment_id]) @comment.count += 1 if @comment.save flash[:notice] = "thank voting" respond_to |format| format.html { redirect_to show_question_path(@comment.question) } format.js end else flash[:notice] = "error voting please try again" redirect_to show_question_path(@comment.question) end end this allows multiple vote , downs. how design user can vote once per comment somehow keep track if voted or down, have ability change vote if want too. you this. prohibits identical votes allows changing vote opposite (it's thumbs up/thumbs down system). def vote(value, user) # goes model #find vote instance given user or create new 1 vote = votes.where(:user_id => user).first || votes.build(:user_id => user

web services - Perl web API using Data::Dumper -

we've developed open web api using apache , mod_perl, can pass text created data::dumper make requests. our data looks this: $var1 = { 'ourfield' => 'ourvalue' }; currently, noticed we're using eval data perl hash server side: my $var1; eval $our_dumper_string; #$var1 filled hash value the problem this, is major security issue. can pass malicious perl code in there , run server side... it there better way safely take data::dumper string , turn hash? yes. use json::xs , use json rather data::dumper format. more compatible other web apis

c# - Fixing maximum length quota on XmlDictionaryReaderQuotas for WCF 4.0 REST -

wcf 4.0 rest projects return 400 bad request errors if post body greater 8192 characters in length. default value of xmldictionaryreaderquotas.maxstringcontentlength property. xmldictionaryreader class used in deserialization process, json messages. i've seen many examples of how solve wcf custom bindings , endpoints, no solution wcf 4.0 rest projects, uses simplified configuration. the normal web.config file contains section looks this: <system.servicemodel> <servicehostingenvironment aspnetcompatibilityenabled="true"/> <standardendpoints> <webhttpendpoint> <standardendpoint name="" helpenabled="true" automaticformatselectionenabled="true" /> </webhttpendpoint> </standardendpoints> </system.servicemodel> first, message size needs increased. that, add maxreceivedmessagesize standardendpoint. <standardendpoint name=""

c++ - What is the rationale for renaming monotonic_clock to steady_clock in <chrono>? -

why did committee rename monotonic_clock steady_clock? vendors providing monotonic_clock backwards compatibility expect monotonic_clock linger while. it seems bit deprecate in c++0x. ;) edit: committe has right , responsibility rename components best can before release done in case. i don't see big benefit of rename. n3128 proposal did , includes rationale: the implementation of timeout definition depends on steady clock, 1 cannot adjusted. monotonic clock not sufficient. while 1 implicit in standard, below make 1 explicit. given steady clock, monotonic clock seems of marginal utility, , replace monotonic clock steady clock. monotonic_clock wasn't deprecated. removed prior standardization. draft standard subject change right until voted fdis. , 1 of changes. living on draft (the bleeding edge) great, 1 must accept risks of doing so.

dictionary - Modifying a Python dict while iterating over it -

let's have python dictionary d , , we're iterating on so: for k,v in d.iteritems(): del d[f(k)] # remove item d[g(k)] = v # add new item ( f , g black-box transformations.) in other words, try add/remove items d while iterating on using iteritems . is defined? provide references support answer? (it's pretty obvious how fix if it's broken, isn't angle after.) it explicitly mentioned on python doc page (for python 2.7 ) that using iteritems() while adding or deleting entries in dictionary may raise runtimeerror or fail iterate on entries. similarly python 3 . the same holds iter(d) , d.iterkeys() , d.itervalues() , , i'll go far saying for k, v in d.items(): (i can't remember for does, not surprised if implementation called iter(d) ).

php - Using ./configure a 2nd time in Linux: Do I need to re-input previous options? -

i compiling php , postgresql myself. have got things working fine. there 25 options added (using method http://vladgh.com/blog/install-nginx-and-php-php-fpm-mysql-and-apc ) php compile. if want add option php (e.g. pdo) need re-enter 25 , enter line enabling pg_pdo, or previous options stored , need enter 1 new option? getting @ here ./configure method, not installing postgres. don't understand how ./configure works or if stores it's previous values , can added to. also, if upgrading postgresql, there need recompile php if not changing options. i hope clear. have been searching day , can't seem make headway. don't know enough make process linux. running ubuntu 10.04lts server. yes, need reenter them. ./configure command generate new set of makefile options, overwriting previous one. luckily, previous ./configure command should still in console's history can press arrow key find it. assuming shell bash on ubuntu, can ctrl r , start typing

ruby - In case of high nibble first zero should be added first -

i using ruby 1.9.2 , found. > ['a'].pack('h') => "\xa0" since h takes high nibble first , since input a 1 nibble additional nibble should padded @ front. means above code should same as > ['0a'].pack('h') but seems missing something. cares explain. since answer of first case \xa0 clear 0 being padded right. when dealing high nibble first a should same 0a . if pack half byte, 1 nibble, that's you'll get. need specify how long input string in nibbles: 'x'.unpack('h') # => ["8"] 'x'.unpack('h2') # => ["85"] 'x'.unpack('h') # => ["5"] 'x'.unpack('h2') # => ["58"] to pack opposite of unpack , don't omit length argument.

c++ - QStringList remove spaces from strings -

what best way trimming strings in string list? try use replaceinstrings: qstringlist somelist; // ... // // add strings // ... // somelist.replaceinstrings(qregexp("^\s*"),""); but spaces not removed. as answer told, need escape backslash. want change expression match 1 or more spaces , not 0 or more spaces, try using: qregexp("^\\s+")

ruby - How to truncate data in a hash so that the resulting JSON isn't longer than n bytes? -

i have hash looks this: { :a => "some string", :b => "another string", :c => "yet string" } i wan't call to_json on eventually, resulting json-string cannot longer n bytes. if string big, first :c should truncated first. if that's not enough, :b should truncated. :a . strings can contain multi-byte characters german umlauts , ruby version 1.8.7. (the umlauts first take 2 bytes, json 5 bytes long.) what wrote loop converts hash to_json , checks length. if less or equal n it's returned, otherwise concat values of :a + :b + :c , shorten half. if new hash big(small), shorten(extend) 1/4th, 1/8th, 1/16th of original string. length of hash.as_json == n . it feels hackish , although tests check out i'm not sure that's stable. does have suggestion how solve properly? how about: # encoding:utf-8 require 'rubygems' require 'json' def constrained_json(limit, a, b, c) output, size, hash

optimization - Using LLVM as a Matlab backend -

would make sense use llvm (with full-fledged jit , optimizers) run interpreted language code matlab? what concrete parts of execution enhanced, using abstract compiler-optimizer instead of matlab's current modus operandi? (i understand has simple llvm-like optimizer, don't believe powerful llvm itself) the reason thought of because using runtime information typical matlab calculation has (size of arguments etc.) think full-fledged optimizer increase execution speed in simple scenarios matlab program needs take special measures ensure optimal performance (like explicit preallocation of variables etc.) i understand there no support of @ all, i'm wondering impact of such interpreter be.

Maintain local variable value between calls in vb.net -

public function methodone(byval s string) string dim sb new stringbuilder() sb.append(s) sb.append(methodtwo()) return sb.tostring() end function public function methodtwo() string dim integer = 0 index integer = 0 5 = index next return i.tostring() end function i want retain value of i, once goes methodone, loses value. tried making static integer = 0 , did not work. sorry misread that. how creating property called count, , update whenever methodtwo called. can use property count in methodtwo instead of i. public function methodone(byval s string) string dim sb new stringbuilder() sb.append(s) sb.append(methodtwo()) return sb.tostring() end function public property count integer 'count 0 when initialized public function methodtwo() string 'dim integer = 0 index integer = 0 5 count = count + index next return count.tostring() end function

Eclipse Remote debugging with Linux through CYGWIN isn't working -

i use windows xp cygwin run web-logic server located in machine. have whole setup in 1 machine. but couldn't make remote debugger work eclipse. here debug command in startwsl.sh export debug_opts = -xdebug -xrunjdwp:transport=dt_socket,address=1044,server=y,suspend=y but couldn't debug eclipse, connection times out. do miss need when using cygwin? appreciated!!! debug_opts not recognized env variable in startweblogic.sh standard script. may want use java_options variable instead.

actionscript 2 - How do I get 2 Flash banners to wait until both are loaded? -

i have 2 flash banner ads, built in cs5.5, using as2, placed on page , appear interact each other when played @ same time. similar this: http://www.youtube.com/watch?v=x8yg6cl3ngy the problem might not load @ same time. how can each banner check other has finished loading before playing? i had read localconnection way this, haven't been able find explains well. first hit on google has code examples - @ least try , post if stuck - http://test.adform.com/testpage/banner-specifications/rich-media-instructions/synchronized-banners/

objective c - NSMutableDictionary - "Incorrect decrement of the reference count of an object..." -

i have property in header file as @property (nonatomic,retain) nsmutabledictionary* e; and in viewdidload: method allocated like self.e = [[nsmutabledictionary alloc] initwithcontentsofurl:myurl]; . the xcode static analyser triggered, , says 'potential leak of object...' obviously. when release object ( [self.e release] in dealloc) error persists, saying there "incorrect decrement of reference count", , object not owned caller (my viewcontroller). the 'incorrect decrement...' error goes away when replace [self.e release] [e release] . former error potential leak still there. problem? this statement: self.e = [[nsmutabledictionary alloc] initwithcontentsofurl:myurl]; is over-retaining object. both alloc-init , property retain object. in terms of ownership, own object returned alloc-init , sending retain message in property accessor claim ownership of again, results in object being over-retained. you can use convenience const

c# - Displaying XML schema elements in treeview in order of appearance in XML -

i need display xsd files in treeview. found 1 solution here !, displays nodes in file in order appear. need display them in order appear in xml file, , nested under elements nested under in xml file: <?xml version="1.0" encoding="ibm437"?> <xs:schema xmlns:xs="http://www.w3.org/2001/xmlschema"> <xs:element name="cat" type="xs:string"/> <xs:element name="dog" type="xs:string"/> <xs:element name="pets"> <xs:complextype> <xs:choice minoccurs="0" maxoccurs="unbounded"> <xs:element ref="cat"/> <xs:element ref="dog"/> </xs:choice> </xs:complextype> </xs:element> </xs:schema> would displayed this: -pets -dogs -cats how undentify root node? think once got can recurse each type in root elemet find name. looking @ xsd spe

php - how can I do some code before I build the form in Drupal 7 (kinda preprocess)? -

i'd ask how can code before build form in drupal 7? before defining form i'd perform code(i want build object), how can it? the code want perform: if (isset($_get["team"])){$team = $_get["team"];} else {$team=1; }; $myteam = new team($team); i define form: function teamform_nameform() { $form['editteam']['team_city'] = array( '#title' => t('team city'), '#type' => 'textfield', '#description' => t(''), '#required' => true, '#default_value' =>**$myteam->returncity()**, '#size' => 30, ); $form['editteam']['submitcontentchanges'] = array( '#type' => 'submit', '#value' => t('save changes'), '#submit' => array('teamform_editteam_submitcontentchanges'), ); } i tried use following hook, doesn't work. (i

Adding arp bindings into ARP table Linux -

im trying add arp binding arp table in linux, arp table looks this: ip address hw type flags hw address mask device 192.168.3.12 0x1 0x6 00:0c:29:89:c5:cc * eth1 192.168.3.100 0x1 0x6 00:0c:29:89:c5:c8 * eth1 192.168.43.2 0x1 0x2 00:50:56:e1:65:76 * eth0 192.168.3.111 0x1 0x6 00:11:22:33:44:55 * eth1 192.168.43.139 0x1 0x6 00:0c:29:89:c5:cc * eth0 this im trying do, following error: arp -s 192.168.43.138 00:00:22:33:33:33 siocsarp: invalid argument any other ip addresses working fine, 1 resulting in error ideas wrong here? (it not problem of mac address probably, ive tried many other addresses) try specify interface -i , if not work trying add mac entry own ip address.

php - Omit all result if one row is equal to a certain value -

i want select row (that appears multiple times) table if column 'wrong' never reads "yes".that means if row exists 100 times , only 1 time wrong=yes, no display rows in result. *and if possible no variables , while loops please. if can't done, go ahead , post solution variable. here example of table structure: table 1 user--wrong--othercolumns bob data bob data bob data bob data bob data bob yes data bob data bob data jon data result should be: jon (because 1 time wrong equal yes user bob) this code ofcourse doesn't omit bobs. 1 omitted: select user table1 wrong <> 'yes' select * table1 t1 not exists (select 1 table1 t2 t1.user = t2.user , wrong = 'yes');

symfony1 - dynamically embedding forms -

i trying add embedding forms dynamically using single table in schema. what mean is, in sfguarduserprofile table, have numerous fields determine user is, i.e. practice_id, nurse_id, patient_id so, in mind, trying dynamically add nurses practices. i have practice form, extends sfguarduseradminform , extends sfguarduser , can username, password etc stored in sfguarduser table. within practiceform embedding practiceprofileform , displays fields need sfguarduserprofile table. hope following... this works fine , see fields both tables. now, bit unsure how do: embedding nurses. particularly unsure how this, practices , nurses saved in same table. practiceform class practiceform extends sfguarduseradminform { public function configure() { $form = new practiceprofileform($this->getobject()->getprofile()); $this->embedform('profile', $form); } } i have nurseform, again extends sfguarduser , embeds nurseprofileform, extends sf

ruby on rails - NameError: undefined local variable or method `logger' -

when run 'script/server' works fine, when run unit tests ( rake test:units ), error below, , not sure how solve this. error nameerror: undefined local variable or method `logger' #<giveawayeligiblemembertest:0x10477dff8> /users/kamilski81/sites/pe/vitality_mall/vendor/rails/actionpack/lib/action_controller/test_process.rb:471:in `method_missing' /users/kamilski81/sites/pe/vitality_mall/lib/update_giveaway_eligible_members.rb:17:in `is_valid_checksum?' /users/kamilski81/sites/pe/vitality_mall/test/unit/giveaway_eligible_member_test.rb:26:in `test_that_checksum_is_valid' /users/kamilski81/sites/pe/vitality_mall/vendor/rails/activesupport/lib/active_support/testing/setup_and_teardown.rb:60:in `__send__' /users/kamilski81/sites/pe/vitality_mall/vendor/rails/activesupport/lib/active_support/testing/setup_and_teardown.rb:60:in `run' i tried putting: class test::unit::testcase rails_default_logger = logger.new(stdout) r

php - How do I limit an already limited query? -

how can limit query limited? the thing is, i'm dividing results pages, , in case, done limit (is there other way it...?), using limit again seems impossible. obviously, if have ideas on how can done in php instead (simple code, please), post it. use offset e.g. [limit {[offset,] row_count | row_count offset offset}] see select documentation the offset calculated doing this $offset = ($page-1) * $pagesize the select select ... yourtable limit $offset, $pagesize

c - OpenMP optimizations? -

i can't figure out why performance of function bad. have core 2 duo machine , know creating 2 trheads not issue of many threads. expected results closer pthread results. these compilation flags (purposely not doing optimization flags) gcc -fopenmp -lpthread -std=c99 matrixmul.c -o matrixmul these results sequential matrix multiply: 2.344972 pthread matrix multiply: 1.390983 openmp matrix multiply: 2.655910 cuda matrix multiply: 0.055871 pthread test passed openmp test passed cuda test passed void openmpmultiply(matrix* a, matrix* b, matrix* p) { //int i,j,k; memset(*p, 0, sizeof(matrix)); int tid, nthreads, i, j, k, chunk; #pragma omp parallel shared(a,b,p,nthreads,chunk) private(tid,i,j,k) { tid = omp_get_thread_num(); if (tid == 0) { nthreads = omp_get_num_threads(); } chunk = 20; // #pragma omp parallel private(i, j, k) #pragma omp schedule (static, chunk) for(i

.net - how to prevent user controls code behind running in async postbacks? -

i have aspx page contains dozens of custom controls issue have asp.net ajax update panel update small area of page other user controls lives in page.(user controls outside update panel , update panel has updatemode="conditional") there way of programatically prevent running code behind of custom controls, since seriosly degrade performace/page load time. have check isasyncpostback script manager prevent unnecessary calls dal. there way prevent running custom control code behind according following conditions, cannot touch custom control code behind,ascx page file etc cannot use caching any change can done aspx page , code behind referring above. cannot integrate jquery or javascript frameworks(wish could) late now. slightly off-topic, have freedom explore methods not include use of updatepanel ? known have poor performance , should used sparingly. with said, page lifecycle methods usercontrol s must fire them rendered again. updatepanel methodology is

java - Upload file in binary mode using Orion SSH2 -

does know how upload file using binary transfer mode using orion ssh (a java library, formerly ganymed ssh)? binary mode default sftp. ascii mode appeared in sftp version 4, using binary mode file transfer.

c# - Could not load assembly -

i have normal winforms app. run , calls logic in .dll (another project part of solution). error (my own exception) saying not load assembly etc etc. i've used assembly log viewer not find issue - found windows service program uses installed/deployed on account. winforms app calls service, in turn calls logic in own , different .dlls. could issue? thanks if use filedialog , open/save/write file directory other 1 contains exe/dlls, change programs working directory if not set filedialog.restoredirectory = true . 1 caused me fits while, , explain why appears intermittent.

php - Paypal IPN and mail() function -

update: (2/29/12) okay, i've run same issue again different client on different server , hosting company. again, having script mail() sends out email correctly no issues. added code similar have below , hooked paypal ipn. every time new payment comes in, ipn fires, data gets saved db mail() function doesn't work. however, ran interesting issue. did test ipn fire paypal's sandbox same script , email sent out. is issue paypals production ipn, perhaps way posts data script? any information here extremely helpful since current solution using cronjobs sloppy. end update i have paypal ipn listener configured since writes information db when new payment comes in. i'm trying setup mail() function sends me email alert of new payment. i have done before project can't life of figure out why it's not working time. i'm not getting error's in error_log , rest of script runs fine. i've tested make sure server send mail standalone mail() script.

jquery - Hide/Show Dropdowns based on previous dropdown selection with Javascript -

looking answer in jquery or mootools (mootools preferably) - have 2 'hidden' drop downs , 1 shows. once user selects choice displayed dropdown, want appropriate dropdown list show up. once make selection 2nd list, appropriate 3rd list show up. if user goes , changes choice on first drop down, other drop downs should go being hidden, , 2nd dropdown list should show. the current setup works first time user loads page - if select first drop down, appropriate list in 2nd drop down displays. if go , change it, nothing happens. i'm sure it's javascript i'm not it. looking this. here current js: var lastlist = ""; function changedropdowns(listname){ //hide last div if (lastlist) { document.getelementbyid('lastlist').style.display='none'; } //value box not nothing & object exists - change class display if (listname && document.getelementbyid(listname)){ document.getelementbyid(listname).style.display ='block';