Posts

Showing posts from June, 2011

c# - Inheritance and Linq-to-Entities -

i have following models: public class person { long id; string name; } public class student : person { string studentid; } public class bus { long id; public icollection<person> riders {set; get;} } public class schoolbus : bus { long schoolbusnumber; } i have following code: schoolbus schoolbus = new schoolbus(); schoolbus.riders = new list<person> { new student { name = "jim" }, new student { name = "jane } } var query = rider in schoolbus.riders select new { (rider student).studentid; } students , person set separate tables , i'm using dbcontext. i know why not work, possible solutions me return right studentid using person collection? try this: var studentids = rider.oftype<student>().select(x => x.studentid);

objective c - Xcode 4 UIButton segue push to Table View Controller -

Image
right have uibutton setup in storyboard pushes table view controller. working expected. trying have uibutton load xml file when pressed , still move onto table view controller. how can this? have code xml pieces, it's question of code go , how add .h , .m files new viewcontroller subclass uiviewcontroller . how link files uibutton i've created in storyboard? drag button connection new view , select custom segue instead of push or modal. change new custom segue's class "mysegueclass1" or ever you'd call it. create new objective-c class same name assigned custom segue. inside mysegueclass1.m file add following code, , add ever additional actions want -(void)perform -(void)perform{ uiviewcontroller *dst = [self destinationviewcontroller]; uiviewcontroller *src = [self sourceviewcontroller]; [dst viewwillappear:no]; [dst viewdidappear:no]; [src.view addsubview:dst.view]; cgrect original = dst.view.frame;

oop - Parametrized module loading in Node.js -

i working on first node.js project , have come oop problem not sure how solve in node.js. i have module a: module.exports = a; function a() { } a.prototype.method = function() { return "a";}; //other methods... and couple other modules (lets b , c) implement same "interface" a. now, have module x: module.exports = x; function x(impl) { //choose a, b, or c based on value of impl } so question is, how implement x in order able do: var x = require("x"); var impl = new x("a"); impl.method(); //returns "a" i believe prototype , __proto__ involved? edit: trying achieve load implementation a, b or c, based on string value (env variable) through standartized interface new x() , access methods of a(b,c...) through instance of x. i think you're after: a.js (b.js , c.js similar, of course): function a() {} a.prototype.method = function() { return 'a'; }; module.exports = a; x.js: var

exception - Java, return new MyException: anti-pattern? -

in class i'm doing validation of custom data. many conditions apply. upon failure, want throw specific myexception. throwing myexception takes many common parameters, , 1 custom parameter (based upon actual failure). actual throw takes many characters write , destroys tidyness because of code duplication. have throw times. made mind create private method prepares , returns new instance of myexception , takes custom data parameter, code can cleaner. private myexception createmyexception(final customerrordata errordata) { ... info gathering, parameterizing, etc... return new myexception(errordata); } ... so throwing new myexception shorter: throw createmyexception(errordata); my question is: what's correct practice prevent code duplication in case? may overmistifying exceptions. an exception factory - never seen before @ least sounds proper design. i worry - seem put quite lot effort on designing exception throwing framework : adding parameters, states

java - How can we tell which class gives the exception -

i getting java.util.concurrentmodificationexception need figure out class gives me exception. code has numerous classes , packages , difficult figure out error comes. exception shows problem of arraylist . doesn't catch exeption when use exception handling in suspected areas. any way out? if you're using modern ide, eclipse example, can run application in debug mode , set breakpoint on exception. effect: application stop each time exception thrown (in entire jvm) , stack trace. that makes quite easy identify caller (and actual thread, if concurrency issue) playn.java.javagrouplayer.paint(javagrouplayer.java:96) that's bad guy. it's paint method javagrouplayer class. has loop iterates through array list , @ 1 point detects, list has been modified. do use threads in swing application? in case, double check not modify layout.

Google Maps API v3 MouseEvent return position of marker not mouse -

i have implemented map markers , listeners on markers. ... google.maps.event.addlistener(marker,'rightclick',function(event) {showrightclick(event, map, marker);}); ... // show right click menu function showrightclick(event, map, marker) { var point = map.getcanvasprojection().fromlatlngtocontainerpixel(event.latlng); var scriptinterface = getheader(); var screenx = point.x + window.screenleft; var screeny = point.y + window.screentop; scriptinterface.rightclick(marker.name, marker.objectid, marker.dimobjectid, screenx, screeny); } but, when listener triggers, event latitude , longitude of marker , not mouse. so, right click menu trying show appears @ bottom of marker , not mouse position. does know if bug or expected behaviour? although documentation says mouseevent event's latlng "the latitude/longitude below cursor when event occurred," location of marker in version 2. the behaviour may expected s

scala - Compiler complains about class that extends DelayedInit not defining delayedInit method -

i have class i'm trying make extend delayedinit : class foo extends delayedinit { // expensive initialisation code } however when try run sbt compile error: foo needs abstract, since method delayedinit in trait delayedinit of type (x: => unit)unit not defined my understanding extending delayedinit trait initialisation code should automatically wrapped in closure , run in delayedinit method after initialisation complete. i've had stab @ googling , can't seem find example of usage. missing? how delayedinit works , sample usage delayedinit trait provides ability control @ point initialisation code within class or object (but not trait) run. any initialisation code within classes or objects (but not traits) inherited delayedinit passed compiler during initialisation delayedinit method , it's when want run it. delayedinit method called automatically part of initialisation , running code passed parameter straight away within method stil

javascript - jQuery - RegEx working bizarrely -

i new regexp. here problem. have input value. apply regexp "rule" input value. rule starts input value , not case sensitive. lets take example. reference string paris (75018) , input value pari . in scenario working fine. if input value paris (7 not working. in case "system" telling me no match , don't it. matching! hope can help. thank in advance replies. cheers. marc. http://jsfiddle.net/ju8va/ my html: <input id="btn" type="submit" />​ my js: $('#btn').click(function() { var loc = "paris"; //input value... var locregexp = new regexp("^" + loc, "i"); // var test = "paris (75018)"; //reference value if (test.match(locregexp)) { alert('matches'); } else { alert('does not match'); } });​ the problem ( has special meaning in regular expressions. literally, have escape \( . see here: h

Database ERD Diagrams and graph planarity -

i wondering, erd diagram planar? have basic understand of database entity relationships, have been unable think of situation make erd diagram non-planar. could please explain me whether or not erd diagram planar? if not, situation make non-planar? if yes, please provide small proof of why planar? i have searched on internet , nobody seems have concrete answer this. thank you. could please explain me whether or not erd diagram planar? i think it's matter of generating graph in manner displays graph in simple readable form. having algorithm strives achieve planar layout can organize complex erd diagram comes closer achieving goal. use visual paradigm generate erd diagrams; don't think it's case diagrams come out planar pretty close of time. exception occurs one-to-one, many-to-one, , one-to-many class relationships. if yes, please provide small proof of why planar? if graph not planar, want draw few crossings possible, because crossings dec

How to parse JSON in Android -

where can find step-by-step instructions on how parse json feed in android? i'm android beginner wanting learn. android has tools need parse json built-in. example follows, no need gson or that. get json: defaulthttpclient httpclient = new defaulthttpclient(new basichttpparams()); httppost httppost = new httppost(http://somejsonurl/jsonwebservice); // depends on web service httppost.setheader("content-type", "application/json"); inputstream inputstream = null; string result = null; try { httpresponse response = httpclient.execute(httppost); httpentity entity = response.getentity(); inputstream = entity.getcontent(); // json utf-8 default bufferedreader reader = new bufferedreader(new inputstreamreader(inputstream, "utf-8"), 8); stringbuilder sb = new stringbuilder(); string line = null; while ((line = reader.readline()) != null) { sb.append(line + "\n"); } re

Building python pylab/matplotlib exe using pyinstaller -

the following code runs fine , displays simple pie chart when run interpreted python py program. a month ago, used pyinstaller create stand-alone exe , worked great. recently, decided rebuild exe. pyinstaller build completes without errors, generated exe nothing when run. when run it, ends without errors , without displaying pie chart. has changed since month ago, can't figure out what. i've tried uninstalling python , modules , reinstalling, made no difference. from pylab import * matplotlib import pyplot plt figure(1, figsize=(6,6)) ax = axes([0.1, 0.1, 0.8, 0.8]) labels = 'frogs', 'hogs', 'dogs', 'logs' fracs = [15, 30, 45, 10] explode=(0, 0.05, 0, 0) pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', startangle=90) title('pie chart example', bbox={'facecolor':'0.8', 'pad':5}) show() this pyinstaller command using build exe. command works other pyqt gui bu

jpa - Eclipse RCP, Spring, Hibernate Class Loading Issue -

i’m developing rcp based app uses data access layer implemented using spring data jpa backed hibernate. annotated domain classes in 1 jar/bundle, spring repositories , spring config instantiate datasource, entity manager, , transaction manager in bundle.these jars used other non-rcp apps across project.i have of hibernate 3.6.8 jars , dependencies either wrapped , exposed through own plugins or osgi bundles (jta, antlr, commons collections, etc) in target platform. i’m using eclipse gemini blueprint manage bundle spring contexts within rcp app. when dal bundle spring context being initialized gemini extender, hibernate related classdefnotfound exceptions, either on org.hibernate.ejb.hibernatepersistence or javax.persistence.spi.persistenceprovider. i’ve tried putting of hibernate jars , dependencies in single plugin exports javax , hibernate packages. i’ve tried setting eclipse buddy policies in manifests of plugins have control over, etc. i haven’t been able find solution clas

jquery - Preventing parent page reloading when exiting modal -

i have form has popup when button pressed on page. if filled in form, have not submitted posting yet , press popup button, when go exit modal form had filled in goes blank. looking prevent this. dont want have post when click popup button, want smoothly exit modal when go parent page unsubmitted filled in data still there. code using have worry have onclick event this: onclick="location.href=parent.location" that easiest solution found exit modal has 1 problem stated above. thanks. so, after not getting answers decided make note saying "esc exit". works fine. makes sense if able must able same on button click.

Mysql - Replicate only a few tables from a database -

using mysql replication mysqlbinlogs between master , slave databases, possible replicate few key tables instead of entire database? i ideally not generate mysqlbinlogs unneeded tables if not possible, use slave limited tables , set master-slave result in limited mysqlbinlogs? binlog generated tables. use blackhole storage engine on mysql instance filter binlog. here guide: http://jroller.com/dschneller/entry/mysql_replication_using_blackhole_engine

Flip an Android Canvas -

is there easy way flip canvas in android? cant seem find allows me flip vertically 0 on y-axis bottom of phone screen instead of top. it's ok if solution isn't fast because i'm not doing computationally intense canvas. thanks in advance. try canvas.scale(1, -1, width / 2, height / 2) see canvas.scale documentation. first 2 parameters amount scale by.

memory - How can I get an OutOfMemoryException in .Net? -

in memory hungry app i'm developing i'm facing outofmemoryexceptions. expected never have kind of exceptions virtual memory. why if needed more ram available os not using hd ram? you can outofmemoryexception in many different ways. in 32-bit windows, process can use 2gb of virtual address space (i believe it's 1tb in 64-bit applications). keep in mind not ram, different, hence "virtual". forget ram. ram make things quicker. windows memory manager decides if memory program using in ram or disk. when have lots of programs open, less memory loaded physical ram , more on disk. performance terrible, won't have oom exception. the common way oom exception in .net, try allocate large enough amount of data (something byte array) there not enough contiguous pages of memory available map it, suspect problem lies. means it's possible out of memory exception, if you're requesting new object increase virtual address space amount on 2gb. &

python - How do I extract images from html files in a directory? -

this followup question: how parse every html file in directory images? essentially, have directory of html files each of contain images save separately in same directory. after making suggested changes program, still getting error: image: theme/pfeil_grau.gif traceback (most recent call last): file "c:\users\gokalraina\desktop\modfile.py", line 25, in <module> im = image.open(image) file "c:\python27\lib\site-packages\pil\image.py", line 1956, in open prefix = fp.read(16) typeerror: 'nonetype' object not callable this revised code (thanks nightcracker) using. import os, os.path import image beautifulsoup import beautifulsoup bs path = 'c:\users\gokalraina\desktop\derm images' root, dirs, files in os.walk(path): f in files: soup = bs(open(os.path.join(root, f)).read()) image in soup.findall("img"): print "image: %(src)s" % image im = image.open(image) im.save

javascript - Collections in Spine.js -

i need support collections in spine.js. know spine.js doesn't support @ moment - not sure if ever will. has added feature or know best way go implementing it? this feature built in. collections class methods on model. recommended way add few methods model. if need different class related collection (because used ir ot something) can create new 1 inherits original model , add classmethods there. sample: (check console output) http://jsfiddle.net/spobo/vbtkc/ i have moved published class method post model , have worked without need of postcollection class. choice :)

c# - Initializing member in Getter or Constructor -

is there difference between these 2 approaches ? in approach using getter initialize datatable public datatable res { { if (res == null) { res = getdatatable(); } return res ; } private set; } vs. in approach using constructor initialize datatable public class xyz { public datatable res{ get; private set;} //constructor public xyz() { res= getdatatable(); } } this variable used on asp.net page fill dropdown list. perform better ? edit:- this used in web application data not change. bind table dropdown list in page_load event. the question whether given instance of class xyz need , use datatable . if not, you'd want lazy-initialize (using getter), avoid doing work front nothing. if need it, next question whether there potentially substantive delay between instantiation of class , call res property. if so, loading data upon instantiation mean data bi

r - Random variates from fMultivar doesn't match density function -

i trying use fmultivar package plot histogram of t distribution , show corresponding density function matches histogram. the problem histogram doesn't seem match density function. below minimal example. library(fmultivar) n = 50000 qtile = seq(-5,5,by=0.05) xtt = rmvst(n,dim=1,df=3) hist(xtt,300,xlim=c(-5,5),probability=true) lines(qtile,dmvst(qtile,dim=1,df=3),col='red') xn = rmvsnorm(n,dim=1) hist(xn,300,xlim=c(-5,5),probability=true) lines(qtile,dmvsnorm(qtile,dim=1),col='red') xt = rt(n,df=3) hist(xt,300,xlim=c(-5,5),probability=true) lines(qtile,dt(qtile,df=3),col='red') as clear, xtt doesn't match density function. xn , xt does. am doing wrong here? i unconvinced, @ least regarding whether random draws giving different distribution. histograms same , have looked @ qqplot of 'xt' , 'xtt' on couple of runs , seem line satisfactorily. comparing density lines histograms suggest density estimates might off ,

php - Magento - render phtml template file from layout update xml -

i'm putting first magento theme. wee. this site have large number of static pages, , i'm trying determine best method of getting content system in maintainable way. ideally, process can managed team member limited experience in magento (this key point). aside these 2 main methods of including static "page" content: 1 - save page-content cms static block, added category page 2 - save page-content cms page it seems should able render phtml template file (with page-content real markup) combination of layout update xml directives (in cms page / category page), or widget type of include. assuming file structure looks this: /my_theme /default /varient /template /cms /template /category1 /category2 - page_content.phtml i've tried planting file cms page via number of variations on: <reference name=&qu

javascript - tabs and page reloading -

how make page seem it's tabbed when reloading page? ie. avoid flicker when re-rendering page? it seems that's twitter tabbed view of "followers, following, etc" https://twitter.com/#!/google/following the page reloads on each tab - looks center content changing - rest of page doesn't 'flicker' though reloads. edit: i don't think doing ajax - entire page reloaded, though end result seems ajax. it's not reloading whole page, retrieving new content ajax placed in area , displaying it... it's dynamic ajax content http://www.dynamicdrive.com/dynamicindex17/ajaxcontent.htm

java - Compile/ Catch an exception -

i having lot of trouble code. code compiled , ran suppose before tried put in code catch exception. no longer compile. suppose catch exception , produce error message if user inputs negative number. import java.awt.event.actionevent; //next group of lines import various java classes import java.awt.event.actionlistener; import javax.swing.jbutton; import javax.swing.jframe; import javax.swing.jlabel; import javax.swing.jcheckbox; import javax.swing.jpanel; import javax.swing.jtextfield; import java.awt.gridlayout; import java.text.*; import java.io.ioexception; public class squareroot extends jframe { public static void main(string[] args) { //creates window jframe frame = new jframe(); frame.setsize(450, 300); frame.settitle("find square root"); frame.setdefaultcloseoperation(jframe.exit_on_close); jlabel numberlbl = new jlabel("enter number:"); final jtextfield numberfield = new jtextfield(10);

sql server - XMLize Stored procedure? -

i want write stored procedure xml(?) in comments. /* <description>valid people</description> */ create procedure validpeople select /*<field><name>birthday<name> <minvalue>1950-01-01</minvalue> <maxvalue>2012-01-01</maxvalue> <sql><![cdata[*/ case when not birthday between '1950-01-01' , '2012-01-01' birthday end birthday, --]]></sql></field> .... -- <tablesource> .... -- </tablesource> so can generate report of validation rules comments end users. or let end user modify rules , let machine regenerate stored procedure/comments. is there tool purpose? consider using extended properties to document stored procedures (and possibly other objects, tables, columns, indexes, etc.). there tools available can build database documentation (much api docs known java or .net) based on information. also, information stored "real&quo

installing apache mod_ssl with latest openssl version (/usr/local/openssl) -

i need update apache 2.2.21 installation use latest openssl version. somehow keeps using 0.9.8k. (according server-status). i followed guide , compiled apache custom ssl path: http://hulan.info/item/compile-apache-with-ssl-php-5-and-mysql-on-linux it still says: server version: apache/2.2.21 (unix) mod_ssl/2.2.21 openssl/0.9.8k dav/2 server built: mar 8 2012 10:17:02 can me? how can let mod_ssl use latest openssl version?

nio - why netty can not make a distinction between socket close and socket half close -

i got interest problem, when close (oio) socket outputstream half close manner, netty server detect event , trigger channelclose method in handler, in client side, socket open , connected, complete close socket in client, time, netty server no reflect. doesn't strange? nobody can tell difference. shutdown output sends fin. close sends fin, unless has been sent, i.e. shutdown. fin appears @ receiver eos (eof) condition. server got fin shutdown, saw eos, closed socket, client got fin, saw eos, closed socket, , sent ... nothing server, because fin had been sent.

ruby - How to switch base_uri with httparty -

i trying pass parameter login method , want switch base uri based on parameter. like so: class managementdb include httparty def self.login(game_name) case game_name when "game1" self.base_uri = "http://game1" when "game2" self.base_uri = "http://game2" when "game3" self.base_uri = "http://game3" end response = self.get("/login") if response.success? @authtoken = response["authtoken"] else # raises net/http response raised raise response.response end end ... base uri not set when call method, how work? in httparty, base_uri class method sets internal options hash. dynamically change within custom class method login can call method (not assigning if variable). for example, changing code above, should set base_uri expect: ... case game_name when "

ios - Creating new AVPlayer while in background does not work? -

i'm playing music avplayer . @ time nstimer fires , i'dlike fade on track. start fading out avplayer , create new avplayer instance play next song. when on foreground works expected. when app on background. playing track fades out new avplayer instance not start playing. not possible create new avplayer instance on background? or how can make play? or there way overlap 2 tracks? i playback avqeueupalyer , can't let tracks overlap. suggestions? -- edit -- if not clear, able play background audio long want. creating new avplayer instance in background not work. the correct way wanted seems avmutablecomposition. don't need multiple avplayers , few other benefits. more details: summarized in blogpost: http://www.postblog.me/2012/03/playing-multiple-overlapping-audio-tracks-in-background/

dns - Does CNAME work at all for AppHarbor? -

i've created new application , use custom url. appharbor started charging custom hostnames , rather not have pay until i'm ready go live. does know if cname work? i've tried setting 1 , 404 error. as mentioned on appharbor support request , appharbor must know custom hostname correctly route application requests based on host header. once hostname configured on appharbor, cname dns configuration work fine.

c# - Clear scrollsaver.min.js information -

i had problem dynamically created labels (with scrollbars) not keeping scroll position when page refreshed. proposed solution works well, scrollsaver.min.js script. however, reset variables when asp.net session started , script seems keep values. there way clear cookie generated script on session_start? if want remove cookies, it's easy , straightforward. if know names of specific cookies, can use request.cookies.remove("cookiename") remove cookie. inside firefox, can view cookies "pageinfo->security->view cookies" option.

python - Save plot to image file instead of displaying it using Matplotlib -

i writing quick-and-dirty script generate plots on fly. using code below (from matplotlib documentation) starting point: from pylab import figure, axes, pie, title, show # make square figure , axes figure(1, figsize=(6, 6)) ax = axes([0.1, 0.1, 0.8, 0.8]) labels = 'frogs', 'hogs', 'dogs', 'logs' fracs = [15, 30, 45, 10] explode = (0, 0.05, 0, 0) pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=true) title('raining hogs , dogs', bbox={'facecolor': '0.8', 'pad': 5}) show() # actually, don't show, save foo.png i don't want display plot on gui, instead, want save plot file (say foo.png), that, example, can used in batch scripts. how do that? while question has been answered, i'd add useful tips when using savefig . file format can specified extension: savefig('foo.png') savefig('foo.pdf') will give rasterized or vectorized output respectively, b

mysql - Sql statement return with zero result -

i trying choose row where 1) list.ispublic = 1 2) userlist.userid='aaa' , userlist.listid=list.listid i need 1)+2) there row statement can not row, there problem? list table: listid listname creator isremindsub isremindunsub ispublic createdate lastmodified reminder 1 test2 aaa 0 0 1 2012-03-09 null null user_list table (no row): userid listid userrights my test version select * list l inner join user_list ul on ul.listid = l.listid l.ispublic = 1 , ul.userid = '09185346d' this result when there 2 list in user_list has aaa , , 1 list public in list, cause double retrieve of 1 public list in list if in php ? listid listname creator isremindsub isremindunsub ispublic createdate lastmodified reminder userid listid userrights 1 test2 aaa 0 0 1 2012-03-09 null

android, how to send username and password to webservice as header fields? -

i trying create application on android phone takes username , password user, encrypt password using md5 connect url these parameters. a code connect worked fine on iphone, couldn't find in android: nsmutableurlrequest* request = [nsmutableurlrequest requestwithurl:myurl]; [request sethttpmethod:@"get"]; [request addvalue:usernamefield.text forhttpheaderfield:@"username"]; [request addvalue:md5pass2 forhttpheaderfield:@"password"]; i tried connect via httpurlconnection used post/get dataoutputstream, httpclient send parameters httpget/httppost, no success. i think need send parameters headerfield don't know how. note: compared encryption results , correct. i find apache library more straightforward when comes http. an example of follows: defaulthttpclient client = new defaulthttpclient(); httpget request = new httpget(); request.seturi(new uri("http://www.internet.com/api")); normally request use parameters,

nhibernate - Mapping object id as int idententity -

i have domain objects in fluentnhibernate have id's of type object int (reasoning further below). right have sqlite end. want map id auto-increment. far have: public class usermap : classmap<user> { public usermap() { table("users"); id(x => x.id).customtype<int>().generatedby.native(); map(x => x.email); } } public class user { public virtual object id { get; set; } public virtual string email { get; set; } } but when maps being loaded throws fluentconfigurationexception message identity type must integral (int, long, uint, ulong) user.id property (stack trace says happens when call native . again, want auto-increment integer. reasoning object id we have business requirement support several rdbms's mongodb. aware bad idea, please focus on question. mongo uses objectid (a guid-like consecutive value type) it's default id type. idea hide actual id type (because it's data-layer depen

delphi - How to make a TScrollbox out from TCustomControl? -

i have created component has paint override on canvas , set limit on minimum width , height. scrollbar should appear @ side when width or height less limit scrollbox , can scroll also. i choose tcustomcontrol cause paint , less flicker when double buffered. any idea or better solution? tscrollbox , tcustomcontrol both descend twincontrol . tscrollbox , tscrollingwincontrol add scroll bars, whereas tcustomcontrol adds canvas. want, can either add canvas tscrollingwincontrol , or can add scroll bars tcustomcontrol . compare definitions of 2 classes (in forms.pas , controls.pas , respectively), , should clear one's features easier duplicate in descendant. tcustomcontrol adds 3 simple methods, implemented in 40 lines of code. write tscrollingwincontrol descendant , copy methods , properties tcustomcontrol it.

How to use wkhtmltoimage together with rails template without getting Double render error -

i trying use wkhtmltoimage respond png instead of html, this png picture version of same html, respond png, need construct html src feed imgkit , , want use rails template html.. when following , double render error... how solve this? respond_to |format| format.html { } format.png { generated_html = render :action => "datatable.png.erb" # ready generate png image html mime::type.register "image/png", :png imgkit.configure |config| config.default_options = { :quality => 1 } config.default_format = :png end kit = imgkit.new( generated_html ) send_data( kit.to_png, :type => "image/png", :disposition => 'inline') } end render and/or redirect called multiple times in action. please note may call render or redirect, , @ once per action. note neither r

jquery - Expand/Collapse Content on a Webpage [ also load content on click ] -

i'm making site has different panoramas on 1 page made pano2vr gardengnomesoftware.com/pano2vr.php the problem want hide each panorama in expandable section. user can scroll down , open 1 want. i've been trying different expand/collapse codes, such one http://www.adipalaz.com/experiments/jquery/expand.html and this http://webcloud.se/code/jquery-collapse/ (the reason i've chose these have smooth opening animations, graphic changes show if open or closed , can have more 1 open @ time [non-accordion style]) however first issue panoramas don't load if in collapsed section. (if use 2nd script has cookies , remembers if section open, if open section panorama in , refresh page load in) also don't want them (the panoramas/content inside expandable sections)to load in when open page, each 1 can 5mb+, need way of loading content in section when expand it. (unfortunately panoramas both flash , html5 autoload) this code use load panorama on page: <

c++ - linux bind don't create socket -

i having weird problem. trying create unix socket in directory not create 1 want. have cut down code below example. #include <iostream> #include <string> #include <cstdlib> #include <string.h> #include <sys/un.h> #include <sys/socket.h> #include <errno.h> #include <limits.h> int main(int argc, char *argv[]) { std::string socketname(argv[1]); socketname += "my_socket"; int fd; int result; struct sockaddr_un addr; fd = socket(af_unix, sock_stream, 0); if (fd == -1) { std::cerr << "socket returned " << errno << ": " << strerror(errno) << std::endl; exit(1); } memset(&addr, 0, sizeof(struct sockaddr_un)); addr.sun_family = af_unix; strncpy(addr.sun_path, socketname.c_str(), sizeof(addr.sun_path) - 1); result = bind(fd, (struct sockaddr *) &addr, sizeof(struct sockaddr_un)); if (result =

performance - Can retrieve attributes of elements in a hash in Ruby, but not the elements themselves -

i'm having huge problems retrieving elements hash node_hash in code below. hash contains nodes of phylogenetic tree, built data available here . each node has unique id, key of hash. when try access element of hash e.g., node_hash[10] , ruby spins wheels , cannot retrieve it. however, if node_hash[10].name name returned. know proper relationships being set because can node_hash[1].children.each |child| puts child.name end and expected output of root viruses viroids unclassified sequences other sequences cellular organisms but waits after printing that. here full code. class node attr_accessor :name, :kind, :children, :parent def initialize(name=nil, kind=nil, children=nil, parent=nil) @name = name @kind = kind @parent = parent if children @children = children else @children = [] end end def add_child(child) @children << child end end node_hash = {} file.open("taxdump/names.dmp", "r")

Dynamic Database Driven CSS -

here problem, have site building. including admin page manage on fly, have no issue pretty straight forward php, mysql etc. have in head can use database store css , dynamically call add new setting different classes, id's etc. table this: settings id--class--div--setting where class body, header, footer, etc. , div , setting follows: .header { $div:$setting; } in script echoing style tag , including inside of head tags. my code worth below: $header_query = mysql_query("select style, setting styles class='header'"); $header_result = mysql_fetch_array($header_query); echo "<style type='text/css'>"; echo ".header {"; foreach($header_result $hstyle => $hsetting){ echo $hstyle.":".$hssetting.";"; } echo "}"; echo "</style>"; i figgured enough echo each setting particular class , right in part. instead of echoing out desired code echo(depending on mysql

php - How to trim a new line character from JSON encoded string? -

i developing android application communicates php server via json. in application, encoding key json send server. after encoding,when debug key in logcat, showing new line character @ end of value: the logcat showing me that: {"accesskey":"123456789\n"} because of this,php server won't accept json values. is there method or suggestions remove new line character? have googled this, can't find satisfactory solution. if fix on server php should trim response values using trim now in java method on string object. string.trim(); this should strip out \n or other trailing whitespace

Want to animate characters in android -

i working on sms application , want use animated characters read sms. new android can please let me know how it. in advance i can give brief outline scope of question broad: the simplest way use frame anmation animated characters . each frame wll contain diiferent character animation play frame-by-frame. read sms aloud.. use tts(test speech) feature of android. finally, register broadcast receiver listen incoming sms.

ocaml - Ocamlopt and missing crt2.o file -

having installed ocaml on windows 7, 64 bit (self-installer), tried create simple exe file ocamlopt helloworld.ml -o helloworld as required used native-code compiler (ocamlopt) visual c++ (i have visual studio 10 installed) , microsoft assembler masm version 8 (mingw installed); have set path variables ocaml (c:\programfiles\ocaml\bin), mingw (c:\programfiles\mingw\bin) , masm (c:\masm32\bin). however, despite best efforts , searching cannot around error message **fatal error, cannot find file "crt2.o" file "caml_startup", line 1, characters 0-1: error: error during linking. except when place helloworld.ml file in lib folder of mingw, crt2.o file located. appreciate answer may straightforward, stuck. appreciated. i guess mingw needs way find library files - when compiled source - path lib hardcoded in binaries, if not - search in way (environment variables). try building either mingw (or msys) shell provide correct environment or set lib env var

c++ - Is there a way to find out the compiler options that were used when a .so library was compiled on Linux? -

i need know how library have has been compiled, i.e. compiler options used? specifically, whether compiled optimization or not, , few other options. is there way extract information on linux, x86_64 platform? i don't believe it's possible automatically detect compiler options; @ least not in portable way. what instead change build scripts (e.g. makefile) automatically append define optimization argument (the -d flag).

android - how to set the height of a listview when the activity is initialized -

my purpose set height of listview when activity initialized. height of listview less screen, , after intialized want height of listview , make height plus integer,then set listvview's height new number. but when use listview.getmeasuredheight() or listview.getlayoutparams().height in oncreate or onstart or onresume .the answer zero. how can right answer? i new android, help. that seems weird. anyway, can place listview in viewgroup lik linearlayour, relativelayout , set listview height fill_parent. , set height of viewgroup outside.

java - Else If and Do while does not work as intended -

edit: recent happenings of me compiling program know not compile lead me believe simultaneously having issue compiler. no doubt due running in wine on mac opposed native application. thank responses. test out responses , make changes when have fixed said error compiler or have moved computers 1 working one. i relatively new programming , website please bear me. getting error 2 of if statements , 1 do/while unable resolve. the entire program works intended 2 blocks below. problem when enter character 'y', works intended , ("results =" + arrays.tostring(row)) prints expected to. proceeds continue through original loop , start program again. however, when enter other character, (i.e not 'y' or 'n') code not print "input must either 'y' or 'n'" , waits input. when 'n' entered, not follow out of loop wanted, continues loop , not proceed else if had thought would. indefinitely, not accepting other input 'y'

plone - Multiple calls to a portlet method in Renderer class -

i'm creating portlet based on base portlet. in renderer class, i've defined method : def mymethod(self): """ """ logger.info("hou yeah") .... in portlet's template call view/mymethod in root site, add portlet. when go http://www.example.com/ see hou yeah 1 time. great. when go http://www.example.com/folder1 see hou yeah twice. uh ? when go http://www.example.com/folder1/folder2/folder3 see hou yeah 4 time. ? etc... is normal behavior ? is there way fix ? thanks. it normal behaviour, think. you've find transaction right one. others deleted zope transactions handling.

replication - How to selectively replicate private and shared portions of a CouchDB database? -

we're looking using couchdb/couchcocoa replicate data our mobile app. our system has large number of users. part of database private each user -- example tasks. these i've been able replicate without problem using filtered replication . here's catch... database includes shared information of pertains given user. how selectively replicate shared information? example user's task might reference specific shared documents. there way make sure documents included in replication without including all shared documents? from documentation seems adding doc_ids replication (or adding replication doc ids) might 1 solution. has 1 tried this? there other solutions? edit: given number of users seems impractical tag each shared document users sharing perhaps that's way this? final solution depends on documents structure, see 2 use-cases: as keep within single database, have fields set recognize, document shared or document private, right? example:

javascript - Eco templates: Combine multiple templates from the command-line? -

i'm trying use eco client-side templating. have multiple .eco templates i'd combine 1 js file - know can combine js files after generated that's lot of repeated boilerplate. there better way this? look stitch sam stephenson (author of eco). bundles javascript, coffeescript , eco templates single file, , gives simple require on client side. compiles eco templates functions, they're fast on client.

Windows Phone 7: reference page controls in thread-safe way -

here trying do. in wp7 app, loading page has 2 stackpanels. stackpanel1 "collapsed" , stackpanel2 "visible". on load of page, kicking off httpwebrequest , processing begingetresponse asynchronously. @ point want swap visibility of 2 stackpanels. however, since begingetresponse run asynchronously, no longer in ui thread , cannot manipulate these stackpanel controls. if try reference them, of course, "an object reference required non-static field, method, or property 'blah.stackpanel1'" this makes sense , why. here things have tried: delegates, way sliced it, needed static reference controls. fail. i tried create static reference page class , use reference controls in begingetresponse. compiled, got unauthorizedaccessexception 'invalid cross-thread access.' @ run-time when tried reference controls. searching , searching , searching. using deployment.current.dispatcher.begininvoke run on ui thread. how can statically re

security - Locking a Java application to a particular PC -

i want devise way prevent piracy of app or @ least make more difficult. app installed in standalone pc , want make difficult person copy installation, or clone hard drive, , deploy on second pc. using mac address best way? using wmi mother board id? you can generate machine id based on mac address of network card, or based on pc name (weaker protection), , make algorithm translate machine id activation key. so can activate program based on unique identifier based on pc. however there no easy way calculate unique machine id in java ... if run application on windows can read other hardware values wmi , , mix(for example mix hd serial + mb serial + cpu serial + mac address) them 1 key should enforce better protection. keep in mind if put protection system in application should @ least obfuscate bytecode, because java bytecode decompilable , 1 programmer decompile application able discover , use algoritm integrated validation code ...

java - Why does reversing a loop make it slower? -

i have following code circular shift of bits in array: private static void method1(byte[] bytes) { byte previousbyte = bytes[0]; bytes[0] = (byte) (((bytes[0] & 0xff) >> 1) | ((bytes[bytes.length - 1] & 0xff) << 7)); (int = 1; < bytes.length; i++) { byte tmp = bytes[i]; bytes[i] = (byte) (((bytes[i] & 0xff) >> 1) | ((previousbyte & 0xff) << 7)); previousbyte = tmp; } } then thought it's easier , more readable go backwards this: private static void method2(byte[] bytes) { byte lastbyte = bytes[bytes.length-1]; (int = bytes.length-1; > 0; i--) { bytes[i] = (byte) (((bytes[i] & 0xff) >> 1) | ((bytes[i-1] & 0xff) << 7)); } bytes[0] = (byte) (((bytes[0] & 0xff) >> 1) | ((lastbyte & 0xff) << 7)); } but noticed second 1 (method2) slower first 1 (method1)! noticed difference because i'm calling method thousands of times. did test

mysql - Adding to database from PHP inserts NULL -

the missing _ typo on stackoverflow, testing. i'm trying insert value database using following 2 files: add record: <form action="addvenue.php" method="post" /> <p>venue name: <input type="text" name="venue_name" /></p> <p>venue capacity: <input type="text" name="venue_capacity" /></p> <input type="submit" value="submit" /> </form> addvenue.php <?php require("dbconnection.php"); // connect database // select database $db= 'database'; mysql_select_db($db) or die("could not select database"); $venue_name = $_post['venue_name']; $venue_capacity = $_post['venue_capacity']; $sql = "insert venues (venue_name) values ('$venue_name')"; $sql = "insert venues (venue_capacity) values ('$venue_capacity')"; if (!mysql_query($sql)) { die('error: 

php, login script -

i new in php , trying write registration script. problem when try sign in , can't see user`s menu. maybe problem sessions , cookies can't find it. here part of code: config.php <?php ob_start(); $con = mysql_connect("localhost","root","123"); if (!$con) { die('could not connect: ' . mysql_error()); } mysql_select_db("9gag", $con); $logged = mysql_query("select * users id='$_cookie[id]' , password = '$_cookie[password]'"); $logged = mysql_fetch_array($logged); ?> login.php <?php ob_start(); include("config.php"); if (!$logged[username]) { if (!$_post[login]) { echo("<center><form method=\"post\"> <table> <tr> <td align=\"right\"> user: <input type=\"text\" size=\"15\" maxlength=\"25\" name=\"