Posts

Showing posts from January, 2014

python - deleting rows in numpy array -

i have array might this: anovainputmatrixvaluesarray = [[ 0.96488889, 0.73641667, 0.67521429, 0.592875, 0.53172222], [ 0.78008333, 0.5938125, 0.481, 0.39883333, 0.]] notice 1 of rows has 0 value @ end. want delete row contains zero, while keeping row contains non-zero values in cells. but array have different numbers of rows every time populated, , zeros located in different rows each time. i number of non-zero elements in each row following line of code: numnonzeroelementsinrows = (anovainputmatrixvaluesarray != 0).sum(1) for array above, numnonzeroelementsinrows contains: [5 4] the 5 indicates possible values in row 0 nonzero, while 4 indicates 1 of possible values in row 1 zero. therefore, trying use following lines of code find , delete rows contain 0 values. for q in range(len(numnonzeroelementsinrows)): if numnonzeroelementsinrows[q] < numnonzeroelementsinrows.max(): p.delete(anovainputmatrixvaluesarray, q, axis=0) but reason, code not...

geospatial - Shorten this code that determines distance between two lat/longs in C#? -

public static double distance(latlong from, latlong to) { double lat1 = from.latitude * (math.pi / 180.0); double lat2 = to.latitude * (math.pi / 180.0); return math.acos((math.sin(lat1) * math.sin(lat2)) + (math.cos(lat1) * math.cos(lat2) * math.cos((math.pi / 180.0) * (to.longitude - from.longitude)))) * 3958.760; } can shorten code stretch? i'm wondering ... that's standard spherical law of cosines formula. won't simpler that. @ best, clean code little: public static double distance(latlong from, latlong to) { double deg = math.pi / 180.0; // 1 degree in radians double lat1 = from.latitude * deg; double lat2 = to.latitude * deg; double dlng = (to.longitude - from.longitude) * deg; double r = 3958.760; return math.acos(math.sin(lat1) * math.sin(lat2) + math.cos(lat1) * math.cos(lat2) * math.cos(dlng)) * r; }

c# - Order of operators in IF statement -

i when necessary prevent null pointer exception : // example #1 if (cats != null && cats.count > 0) { // } in #1, i've assumed cats != null needs first, because order of operations evaluate left right. however, unlike example #1, want if object null or if count zero, therefore i'm using logical or instead of and: // example #2 if (table == null || table.rows == null || table.rows.count <= 0) { // } does order of logical comparisons matter? or can reverse order , same results, such in example #3? // example #3 if (table.rows.count <= 0 || table.rows == null || table == null) { // } (btw, realize can rewrite #2 below, think it's messy, , i'm still curious or operators) // example #4 if (!(table != null && table.rows != null && table.rows.count > 0)) { // } yes, short-circuiting happens in both cases, difference being && stops if lhs false (because overall expression must false) while || ...

javascript - How can one add drop shadows to Raphael.js objects? -

i find out how add blurry edged drop shadows raphael.js objects/paths. far know not possible library there work around? adding link raphael.blur in separate answer, per op's request. http://github.com/dmitrybaranovskiy/raphael/blob/master/plugins/raphael.blur.js updated code sample: var shadow = canvas.path(p); shadow.attr({stroke: "none", fill: "#555", translation: "4,4"}); shadow.blur(4); var shape = canvas.path(p); note in dmitry's comments mentions there no webkit support. uses <filter> element , fegaussianblur filter effect. webkit has implemented fegaussianblur effect, filters unstable , disabled in safari (it may work in chrome 5 - should work in chrome 6).

WPF - Image control inside Listbox -

i displaying images inside list box. binding source of image control using object through datacontext of listbox. problem: want display no image (image) if url does't have image. possible in xaml code. code: <listbox cliptobounds="false" x:name="lbbestsellerimage" width="auto" itemssource="{binding}" itemspanel="{dynamicresource iptlistbox}" itemcontainerstyle="{dynamicresource listboxitemstyle}" /> <style x:key="listboxitemstyle" targettype="{x:type listboxitem}"> <setter property="background" value="transparent"/> <setter property="padding" value="2,0,0,0"/> <setter property="template"> <setter.value> <controltemplate targettype="{x:type listboxitem}"> <grid width="150"> ...

android - programmatically sizing views -

i need programmatically adjust sizes of views in ui. want adjust height of child view height of parent view minus 60, this: child.getlayoutparams().height = parent.getmeasuredheight() - 60; child.requestlayout(); (obviously, simpler need do) this works great when done in response to, say, clicking button or like....the child view adjust size requested, , well. now need have sizing done when activity starts, , when orientation changes. preferably without seeing jump around. tried adding activity's onstart(), doesn't work, parent's height measures zero. tried using getheight() rather getmeasuredheight(), , got same incorrect behavior. where put code, or need do, programmatically size views? i encountered same problem. solution found on web using child.post() delay treatment in activity oncreate . works i'm doing, love hear better solution... child.post(new runnable() { public void run() { //resize stuff } } )...

How to show a PDF Page by Page using the Three20 Project - iPhone -

i have large local pdf. how can use three20 project showing pdf page page zooming, swiping functionalities? is there other free library available achieve functionality? i tried use apple wwdc 2010 code facing problems (i showing pdf pages instead of images). question related here, in photoscroller app (iphone wwdc-104 photos app) uiscrollview images shift right when called using presentmodalviewcontroller kindly me. why think three20 can achieve this? three20 not magical library can solve of problems in iphone os. try using normal approach, 1 of them available in this blog post .

Sessions and performance in asp.net MVC -

is true asp.net mvc doesn't use sessions [sessions varibale] , hence there it's performance better asp.net webform. if not case why speed of asp.net mvc faster asp.net webform? it's not use viewstate ,since viewstate data doesn't transmit , fro between client , server,the mvc pages load bit faster.

how to hide and show in html element dynamically -

html input element hide , show using link tag. example:yahoo mail bcc hide , show this done in javascript. for simple javascript, i.e. without using jquery can that: document.getelementbyid("idofelement").style.display = "none"; // hide document.getelementbyid("idofelement").style.display = "block"; // show here link possible values display css element.

Eval Function in C# -

how can evaluate string in c# windows application because need dynamically select object in form based on combination of 2 string give me name of needed object you can try controlcollection.find method find control name. example: myform.controls.find("foobutton", true); method returns array of control element name property set "foobutton". there no c# eval equivalent . link can find useful answers. ofc, if want find or evaluate winform controls update: think better control key directly. example: control control = this.controls["footxtbox"]; if(control==null) { messagebox.show("control not found"); } control.text = "something";

haskell - Options for pure-number module namespace? -

it seems pure-number module namespace like module 2010.foo is not allowed. one not pretty option be module v2010.foo can suggest other options? module names must start capital letter. module name must same file name, far module naming goes have 1 option: start name capital letter.

how to get an movable pin on a map view iphone or ipad? -

how movable pin on map view , user can move pin , point out specific location on map. please tell me how this thanks kumar. i think hold finger on map few seconds , pin appears.

iphone - using a viewController to open another instance of the same viewController -

i have masterviewcontroller.h.m.xib (uiviewcontroller) opening testdummy.h.m.xib (uiviewcontroller) in following way: testdummy *controller = [[testdummy alloc] initwithnibname:@"testdummy" bundle:nil]; [scrollview addsubview:controller.view]; i have 2 buttons in testdummy: (open), (close) , 1 label: (windowdepth). i'm trying create second instance testdummy open first testdummy. allow multiple testdummy (uiviewcontroller) open n depth , allow close button take them 0 depth. here's have open button. -(ibaction) btnopen_clicked{ testdummy *newcontroller = [[testdummy alloc] initwithnibname:@"testdummy" bundle:nil]; newcontroller.isnotroot = yes; newcontroller.windowdepth = self.windowdepth + 1; //do stuff... childdummy = newcontroller; // start animated transition [uiview beginanimations:@"page transition" context:nil]; [uiview setanimationduration:1.0]; [uiview setanimationtransition:uiviewanimationtransitioncurlup forview:self.view ca...

java - "Please wait until after injection has completed to use this object" error from Guice -

we have 2 singleton objects (declared via in(scopes.singleton) ) in guice each uses other in constructor. guice's way implement proxies - initializes object @ first proxy other object, , when object needed resolved. when running code several threads, following exception: java.lang.illegalstateexception: proxy used support circular references involving constructors. object we're proxying not constructed yet. please wait until after injection has completed use object. @ com.google.inject.internal.constructioncontext$delegatinginvocationhandler.invoke(constructioncontext.java:100) i assume bug in guice, because aren't doing out of ordinary. 1 workaround found initializing singletons using .aseagersingleton() , not convenient, testing example. is known issue? reported issue google guice , reproduces standalone test. any other suggestions/workaround? did try injecting provider<t> in each constructor instead of actual instances? if don't n...

asp.net - How to invoke server side function before invoking client side function -

i using update panel in application. inside update panel trying trigger html button, in turn should invoke server side function after need invoke client side function.but client side function getting invoked first server side function not getting invoked @ all. here code <asp:updatepanel id="embedcodepanel" runat="server" updatemode="conditional"> <triggers> <asp:asyncpostbacktrigger controlid="btnembedurl" eventname="onclick"/> </triggers> <contenttemplate> <label id="lbl_embedcode" class="hide">site embed code:</label> <textarea id="embedcode" class="embedcode hide"> createembedurl('<%=_redirecturl%>') </textarea> </contenttemplate> </asp:updatepanel> this button code: <input id="btnembedurl" runat="server" type=...

How are STA COM components handled when used in a WCF service hosted in IIS (7+)? -

from understand, when com component marked using sta used mta thread, calls supposed marshalled sta thread , executed dedicated thread. in case of windows client application, mean execute on ui thread (if marked sta), , callbacks com component me handled windows messages sent hidden window , processed on windows message loop. what happens though if use sta com component in wcf service hosted in iis? worker process have windows message loop on sta thread? can fire own sta thread own message loop? the com runtime looks after dispatching of calls methods on com object inside sta: right based on same os mechanism used dispatching windows messages, don't need worry making happen - com under hood. what do need worry sta com objects going live in. if instantiate apartment-threaded com objects using com interop wcf service, need careful. if thread on not sta thread, in-process com objects live in default host sta iis worker process. not want happen: com objects servi...

.net - I am getting a "duplicate association path" error in the NHibernate Criteria when accessing the same table twice -

i have createcriteria adds join same table twice different aliases: acriteria.createcriteria("color", "co").add(expression.in("co.colorid", bikush.color.select(x => x.colorid).tolist())); acriteria.createcriteria("color","fco").add(expression.in("fco.colorid",bikush.fccolor.select(x => x.colorid).tolist())); i'm getting error "duplicate association path" here sql want generate: select b.bikushid, c.[name] plaincolor, fc.[name] fancycolor bikush b inner join bikushincolor clt on clt.bikushid = b.bikushid inner join color c on clt.colorid = c.colorid inner join bikushinfccolor bifc on b.bikushid = bifc.bikushid inner join color fc on bifc.colorid =fc.colorid is there anyway around using criteriaapi of nhibernate? thanks if understand correctly, should merge thies 2 calls in one: criteria.createcriteria("color", "co") .add(expression.in("co....

java - Determine the square root of a number -

i have following lines of code homework, takes numbers. trying figure function used find square root of number. how 1 this? system.out.println("find value of c if:"); scanner kbreader=new scanner(system.in); system.out.print("a="+" "); double a=kbreader.nextdouble(); system.out.print("b=" + " "); double b=kbreader.nextdouble(); system.out.print("c=" + " " ); system.out.print((a*a)+(b*b)); what's wrong math.sqrt(double) ?

how to initialize a PHP bidimensional array -

let's manage multidimensional array (pseudo-code): array $colors * wine,red * cheese,yellow * apple, green * pear,brown what code used avoid following notation, initialize array (assuming there hard-coded list of elements=?: $colors[x][y] = 'something'; $array = array( array('wine', 'red'), array('cheese', 'yellow'), array('apple', 'green'), array('pear', 'brown') ); upd: foreach ($array $v) { echo $v[0]; // wine, cheese... echo $v[1]; // red, yellow... }

Why doesn't this event unbind using jQuery? -

i have seen similar questions can't figure out doing wrong here. dropdown shown after ajax call completes succesfully want hide when user clicks anywhere. remove event though because there no need hide if hidden. dropdown.slidedown('fast'); $(document).bind('click.test', function() { alert('click'); dropdown.slideup('fast'); $(document).unbind('click.test'); }); any thoughts??? you can call one method instead.

Embedded Google Docs PDF viewer displays login page rather than PDF -

i have web page in embed google docs viewer in iframe <iframe src="http://docs.google.com/viewer?url=url-encoded-url&embedded=true" width="750" height="960" style="border: none;"></iframe> (where url-encoded-url actual encoded url). for many/most of users, google pdf doc viewer appears , displays referenced pdf. but of users instead see google docs page login box. i've no idea why happens. has heard of happening? , more important, know why, , can done ensure pdf shown. i second zhami's comment on question. happens when (the user) has google account login has expired. login page shows them email: field filled in email asks password. if click on "change user", email field goes empty , can go iframe page , see document. i think maybe can google bug?

c# - ADO.Net Transaction Not Working -

i have following code (i'm new .net transactions) , seem executing @ all. it's called through webservice , difficult me debug: public void updatejailfiles(list<rms.namefile> names, rms.incident incident, int currentdate, int currenttime, int incidentkey) { string library = rmslibrary; idbtransaction transaction; using (idbconnection conn = connection) { conn.open(); transaction = conn.begintransaction(); try { names.foreach(namefile => { idbcommand command = conn.createcommand(); command.commandtext = "call " + library + ".sp_namefile_update(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; command.commandtype = commandtype.storedprocedure; command.commandtimeout = 0; ...

Citation for Silverlight 4 backward compatibility? -

i have strong impression silverlight 4 client runtime run silverlight 3 application well, life of me can't find definitive statement microsoft effect. can provide reference? there quite few citations. here's 1 tim heuer, silverlight pm. http://timheuer.com/blog/archive/2010/04/15/silverlight-4-breaking-changes-backward-compatibility.aspx yes, situation refer backward compatibility. means existing compiled xaps under previous versions should continue work as-is if users have later version of silverlight installed on machine. and microsoft website, in section seems doesn't apply (but does): http://msdn.microsoft.com/en-us/library/cc265156(vs.95).aspx ...each major version of silverlight plug-in. each version backward compatible previous versions. and another: http://support.microsoft.com/gp/lifean45 microsoft continue support versions of silverlight shipping updates latest version of both silverlight runtime...

How can I tell when a Delphi TDBGrid has finished populating from a database? -

i have database populating tdbgrid in delphi 2007 pro. when grid finishes populating, want automatically fill list box based on data processed grid. can manually watching , waiting grid fill dataset , calling next procedure. there event allow calling next procedure when grid finishes populating automatically? thanks. if you're using tdataset descendant, can use afteropen event: "afteropen called after dataset establishes access data , dataset put dsbrowse state." edit (code sample comments duilio's answer ): in below, 'cds' 'tclientdataset'. 'tdbgrid' attached data set means of 'tdatasource', grid's functionality not in way effected code below, or listbox's functionality grid's matter.. procedure tform1.cdsafteropen(dataset: tdataset); var sl: tstringlist; begin sl := tstringlist.create; try sl.sorted := true; sl.duplicates := dupignore; dataset.disablecontrols; try data...

objective c - Paging Horizontally with vertical scroll on each page! -

in app use page control , uiscrollview page horizontally, i'd able enable vertical scrolling on each page. know can nest uiscrollviews in order achieve this, there 1 problem in project. each of pages uses view controller consisting of view, background image (different image each page). background image should not move while scrolling , down. now want ability have buttons, regular rect buttons, create in interface builder (since want able design , update positions easily) , can scrolled vertically. so should this: you see screen page-control on bottom, above image buttons on it. when scroll sideways, go page, again image (another one) , different buttons. whenever scroll vertically on page, buttons should scrollable (so can have lot of buttons on 1 page), image should maintain it's position. so figured, add scroll view on top of view background image. works fine since have buttons hovering on background image , have separate nib file each page including buttons. wh...

Rails MultiSite App + nginx config -

i'm trying deploy multisite rails app different views , public folders each site. let's have www.foo.com , www.bar.com. inside rails_root directory have [sites] directory 2 folders inside [foo] , [bar] each folder consists of [public] , [views] folder. my nginx configuration has that: server { listen 80; server_name www.foo.com; root rails_root/sites/bar/public; passenger_enabled on; rails_env development; } server { listen 80; server_name www.bar.com; root rails_root/sites/bar/public; passenger_enabled on; rails_env development; } my problem nginx can't find rails_root expects usual hierarchy public folder rails_root/public. solution this? when referer rails_root don't mean variable use instead of writing specific path .../.../

Android OpenGL only renders half the screen -

Image
i have follow example of opengl application , don't know why thing happening... i have glsurfaceview it's corresponding renderer drawing triangle. but, instead of getting whole view on screen, have upper half, , it's duplicated can see on picture. i'm using nexus 1 the xml: <?xml version="1.0" encoding="utf-8"?> <com.forgottenprojects.geoturista.drawinglayer xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/drawing" android:layout_width="fill_parent" android:layout_height="fill_parent" /> the activity has in manifest: android:theme="@android:style/theme.notitlebar.fullscreen" the drawinglayer class: public class drawinglayer extends glsurfaceview { private trianglerenderer renderer; private context context; public drawinglayer(context context, attributeset attrs) { super(context, attrs); init(context); } public drawin...

ajax - Why isn't Firefox submitting my form twice? -

html/js here: http://pastebin.com/jrtfeatw php here: http://pastebin.com/ecrhcwmy based on ajax f1's tutorial here: www.ajaxf1.com/tutorial/ajax-file-upload-tutorial.html anyway, problem. in chrome, works fine. however, in firefox, upload first file no problem, , begin uploading second one. i've traced in firebug , calls form.submit() on correct form, , form has correct fields in it, reason form never gets submitted. is because i'm submitting same form twice? , if so, there workaround knows of? cheers! i have no explanation this, however, setting source of iframe about:blank between each image upload fixed issue.

Ruby use case for nil, equivalent to Python None or JavaScript undefined -

how ruby's nil manifest in code? example, in python might use none default argument when refers argument, in ruby can refer other arguments in arg list (see this question ). in js, undefined pops more because can't specify default arguments @ all. can give example of how rubynone pops , how it's dealt with? i'm not looking example using nil . preferably real code snippet had use nil reason or other. ruby's nil , python's none pretty equivalent (they represent absence of value), people coming python may find surprising behaviors. first, ruby returns nil in situations python raises exception: accessing arrays , hashes: [1, 2, 3][999] # nil. [].fetch(0) raises indexerror {"a" => 1, "b" => 2}["nonexistent"] # nil. {}.fetch("nonexistent") raises indexerror instance instance variables: class myclass def hello @thisdoesnotexist end end myclass.new.hello #=> nil the second remarkab...

Can I specify the default SQL Server with two named instances installed? -

i have sql 2005 express installed. installed sql server 2008 r2 , running both instances successfully. named: computername\sqlexpress (2005) computername\install2 (2008) i trying figure out how specify 2008 instance default server. have tried: data source=.\local; ... data source=.; ... data source=localhost; ... data source=(local); ... data source=127.0.0.1; ... each time there connection error stating... test connection failed because of error in initializing provider. network-related or instance-specific error occurred while establishing connection sql server. server not found or not accessible. verify instance name correct , sql server configured allow remote connections. (provider: named pipes provider, error: 40 - not open connection sql server) i have other developers working on same project , have sql server 2008 r2 installed , able use data source=(local); ... connect without issues. is there way me define 2008 instance default or local instan...

php - Connect with Facebook buttons - how does the pop-up window work? -

does know how facebook connect buttons generate pop-up window use sign in? i think there's code this.. <a href="#" onclick="mywindow=window.open('http://www.yahoo.com','mywindow','toolbar=no,location=no,directories=no,status=no, menubar=no,scrollbars=no,resizable=no,width=600,height=300'); return false;">click here</a> but haven't found similar in documentation. the facebook api uses called fbml (facebook markup language). tag based markup written inline other html on website, , processed javascript library. connect script is: <script src="http://connect.facebook.net/en_us/all.js"></script> if use script , provide following tag: <fb:login-button></fb:login-button> then javascript render button. more details can found here: http://developers.facebook.com/docs/authentication/ the button automatically generate popup window when click it, don't have worry c...

c++ - Functions / Methods in Objective C! -

i need functions in objective c? in c++ can make function this: int testfunction(int zahl) { int loop; loop = zahl * 10; return loop; } this function multiply zahl 10 , returns result. in c++, can call function whenever want with: testfunction(5); and returns 50. i dont understand how can make such functions testfunction in objective c? have with -(void)testfunction{}? thankx lot help!! greez franhu just use int testfunction(int zahl) { return zahl * 10; } you need other notation (see user467105's answer) if want declare member functions.

javascript - how to get the last character of a string? -

how last character of string: "linto.yahoo.com." the last character of string "." how can find this? an elegant , short alternative, string.prototype.slice method. just by: str.slice(-1); a negative start index slices string length+index , length , being index -1 , last character extracted: "abc".slice(-1); // "c";

php - How can i install imagick so that it can work in XAMPP? -

hello m using ubuntu 10.04 , want use(install) imagick in xampp.i have installed imagick synaptic package manager when m trying use in xampp,its not working , giving error like"no class imagick found". when open phpinfo(),i didnt find imagick there. pls suggest me how can install imagick can work xampp??? try installing php5-imagick . package containing php bindings imagemagick.

wpf - When does the defered execution occur? -

i've got situation want fetch data database, , assign tooltips of each row in listview control in wpf. (i'm using c# 4.0.) since i've not done sort of thing before, i've started smaller, simpler app ideas down before attempt use them in main wpf app. one of concerns amount of data potentially come down. reason thought use linq sql, uses deferred execution. thought , not pull down data until user passes mouse on relevant row. this, i'm going use separate function assign values tooltip, database, passed upon parameters need pass relevant stored procedures. i'm doing 2 queries using linq sql, using 2 different stored procedures, , assigning results 2 different datagrids. even though know linq sql use deferred execution, i'm beginning wonder if of code i'm writing may defeat whole intent of using linq sql. example, in testing in simpler app, choosing several different values see how works. 1 selection of values brought no data back, there no ...

automation - Writing web forms filler/submitter with QT C++ -

i'm scratching head on how accomplish following task: need write simple web forms filler/submitter qt c++, following: 1) loads page url 2) fills in form fields 3) submits form sounds easy, i'm web developer , can't find way how make qt accomplish task, managed load url qwebview object using webkit, have no idea next, how fill in fields , submit forms. hints, tutorials, videos? appreciate this. qwebelement class work, reading through class documentation gave me full idea on how accomplish task. eveyrone suggestions.

Ruby on Rails CSV putting &quot;&quot; instead of actual quotes -

i attempting generate csv file. fine except blank fields, i'm not quite sure have &quot;&quot; instead of actual quotes. i've provided code i'm using generate file , output. <% headers = ["username", "name", "e-mail", "phone number"] %> <%= csv.generate_line headers %> <% @users_before_paginate.each |user| %> <% row = [ "#{user.username}".html_safe ] %> <% row << "#{user.profile.first_name} #{user.profile.last_name}".html_safe unless user.profile.blank? %> <% row << "#{user.email}".html_safe unless user.profile.nil? %> <% row << "#{user.profile.phone}".html_safe unless user.profile.nil? %> <%= csv.generate_line row %> <% end %> output username,name,e-mail,phone number admin,localshopper ,shoplocally1@gmail.com,&quot;&quot; brian,oliveri design ,brian@oliveridesign.com,727-537-9617 ...

java - Why can't I access package-private fields in the android.widget package? -

i'm attempting override android view class tweak functionality slightly. need modify field not have setter method. i've placed subclass in package called android.widget . why can't access of package-private member fields? notice compiler says "cannot resolved," rather not being accessible. have how android.jar built? those methods not part of android sdk , therefore unavailable directly sdk application. if building firmware, can access them directly. presumably, subclass @ them via reflection, though bear in mind such fields (or other non-sdk stuff) subject change in given android release.

TV guide listing API -

does know provider offering tv listings (through api or download) channel , cable providers? or there independent company collecting/providing such data? api/rest/soap interface great. the mythtv folks have gathered resources various countries here . if you're in or canada, recommend schedule direct service. these services based on xmltv data format/toolset.

jquery - find position of <li> -

i trying find position of test3 in jquery can lead me down right path please. i need jquery display 5 <ul id="numeric" class="sortable boxier" style="margin-right: 1em;"> <li>test7</li> <li>test2</li> <li>test6</li> <li>test5</li> <li>test3</li> <li>test8</li> </ul> thank you $('li:contains(test3)').index() note uses 0-based indexing, display 4. can add 1 if want start count @ 1.

json - Twitter record size -

sorry maybe stupid question;) i trying model records if modeled twitter. interesting me how big or small are? normal can bigger 512 bytes per record? and methods know optimization records within json documents? mean especial json;) maybe links? thanks;) to analyze worst case: if store data in utf8, it's conceivable having 3-byte characters means 480 bytes. a utf8 may 4 bytes (4*160=640). i'm not sure edge-case worth protecting against.

comparison - High-level differences between node.js and ZeroMQ? -

excuse ignorance, high-level overview of (something like) node.js versus zeromq? node.js javascript vm based on v8 -- built full programming environment asynchronous io zeromq library doing variety of things -- message queueing on arbitrary protocols. compatible amqp (message protocol) , not have have broker (central routing server). basically totally different :-) there half functional binding of zeromq node http://github.com/justintulloss/zeromq.node - , more functional 1 amqp in general ry built - http://github.com/ry/node-amqp

sql server - SQL - Insert query Inside another Insert with updated Identity seed -

i have 2 tables t1 , t2 t1 has 10 unique records primary key (identity seed) t2 has multiple entires foreign key each record in t1 t1 has 2 columns : primarykey - data t2 has 2 columns : primarykey - foeignkey (this fk primary key of t1) i need write query select records t1 , insert new entries i.e. t1 ,with same data,and since pk on t1 identity seed auto generate new id, new id generated need join t2 , insert new related records new identity. i know duplicate data , not concern, 1 time transaction query need not efficient, no cursors please, best if can achieved using select , inserts without doing loops using external variables ! !! update : if there entry in t1 not suggest in table t2 there has corresponding entry/entries. p.s. im using sql server 2005 assuming primary key on t2 identity, use: -- populate t1 insert t1 select data t1 -- populate t2 t1 values insert t2 select primary_key t1 x exists(select null t2 y j...

spreadsheet - How do I use this Google Apps Script? -

http://code.google.com/googleapps/appsscript/class_range.html#getformula is there script can install or need write own? after that? yes, need write google-apps-script calls method, want use it. in spreadsheet go tools->scripts->scripts editor , write code there. of course, getformula method returns string representation of formula in given cell. can moving cursor on cell. don't need write script that.

ios - How to manipulate texture content on the fly? -

i have ipad app working on , 1 possible feature contemplating allow user touch image , deform it. basically image painting , when user drags fingers across image, image deform , pixels touched "dragged" along image. sorry if hard understand, bottom line want edit content of texture on fly user interacts it. is there effective technique this? trying grasp of need done , how heavy operation be. right thing can think of search through content of texture based on touched , copy pixel data , kind of blend on existing pixel data finger moves. reloading texture glteximage2d periodically effect. there @ least 2 fundamentally different approaches: 1. update pixels (i assume mean in question) the effective technique change pixels in texture called render-to-texture , can done in opengl/opengl es via fbos . on desktop opengl can use pixel buffer objects ( pbos ) manipulate pixel data directly on gpu (but opengl es not support yet). on unextended opengl can chan...

html - How to show required field with jqtouch in iphone view? -

Image
i've started designing pages particularly iphone browser (safari). don't know if jqtouch best or not, started working on it. till learned initialization of jqtouch, , implemented touch events (tap, swipe). now planning create user interface , forms. take on demo (best viewed in webkit ). now coming question, best way show required field in iphone view? you can post suggestions on ui creation iphone.. question belongs html, not related objective c! to start off, don't think there convention indicating required form field in iphone. so, developers. depends on how implement form fields. there few different ways this. example, text input field placeholder attribute drill down form, e.g. settings key-value fields, e.g. contacts for first option, may have more space put in more informative wording, such suggested vikas: "username (required)". for latter two, might follow desktop convention adding asterisk in front/back of label, e.g....

java - Allowing parent to process mouse event if event was not consumed by child -

Image
i have frame: here happens: when i'm on pinkish panel, scroll pane works fine. when put mouse on darker gray jtextarea scroll pane not event. in general question how can make sure parent of component receives event if component didn't handle specific event, if component has listener , enabled? perhaps specific example do. you can see calculator, calculator drawn on scalable image panel, , can zoom in , out ctrl + wheel event, when don't press ctrl, scroll pane receive event , scroll view port. (i think sums it) adam. while not entirely "neat", answer in question might adapted want do. instead of mouse_event_mask you'd use awtevent.mouse_wheel_event_mask , , pass event scrollpane when control key state appropriate. (with luck post "real" mechanism forward event parent component).

Problem in chatbox made in jquery -

i have made chatbox in jquery , want add functionality see "xyz typing" have written code setinterval("typing()", 1000); function typing() { var name1= $("#name").val(); var n=$('#message').val().length(); if(n>1) $('#shout').prepend(name1+'is typing'); } but not working. someoen pls help... you shouldn't use "typing()" . invoke eval() internally. instead, use typing . if have made chatbox, want send server via ajax person has typed something.

ajax - MVC2 JQuery Syntax not working -

i trying following : <script src="scripts/microsoftajax.js" type="text/javascript"></script> <script src="scripts/microsoftmvcajax.js" type="text/javascript"></script> <script src="scripts/jquery-1.4.1.min-vsdoc.js" type="text/javascript"></script> <%=html.dropdownlist("ddlpostage", new selectlist(model.postageoptions ienumerable, "id", "text", model.selectedpostageid)) %> <script language="javascript"> $('#ddlpostage').change(function() { alert('okay go'); }); </script> but getting runtime error @ jquery systax. "microsoft jscript runtime error: object expected". as far concerned path-to-jquery okay because form validation using <% html.enableclientvalidation(); %> worked fine in 1 of previous pages , jquery file sits beside other js files default vs2008. what doin...

Serving Java Applets from a Queue? -

i'm looking elegant way create queue serving batch compiled applets. have hacked sql , php script handle chokes under mild loads. there existing system can handle taking list in sql , serve applets in descending order each time requested. i'm trying handle server side well. the trick getting file001, file002 ++ ect. served each time web page loaded. i'm batch creating applets has modified background , i'm trying serve never been used applet waiting in queue load each time page requested. is there applet server can tweak or needs built? no, have never heard of "batch compile applet server". could maybe explain in more detail why feel necessary? why don't use same class , pass parameters it? that said, can compilation on demand quite e.g. ant , / or cruisecontrol. put pre-compiled applets directory. php frontend needs keep track of applet delivered last, , fetch next 1 next time. still, sounds rather complicated me; maybe explain mot...

vba - Error when reading registry with Visual Basic 6 running on Win7 -

i have inherited vb6 application friend of family member, wants have enhancements done it. haven’t developed in vb more 3 years (i’m developing in ms dynamics ax). i’ve upgraded hardware , running win7. last time worked app (about year , half ago) on winxp platform, , worked fine. when run app (through code) on win7, error when trying read registry. yes, running vb administrator. the code read registry is: public function sreadregistry(byval hkeyroot long, _ byval ssubkey string, _ byval svaluename string) string dim r long dim sdata string * 255 dim ldatasize long dim stempval string dim readvalue string ldatasize = 255 'get value requested ldatasize = 255 r = vregreadstring(hkeyroot, ssubkey, svaluename, sdata, ldatasize) if r stempval = "" else stempval = left$(sdata, ldatasize - 1) end if sreadregistry = stempval end function the “vregreadstring “ declared within module; , declar...

Why can't I install ruby 1.9.2 on Ubuntu via apt-get? -

apt-get install ruby installs ruby 1.8.7 when install ruby 1.9.2 sources via ./configure make install, ruby not installed (ruby -v gives nothing). so how can install ruby 1.9.2 on ubuntu? i use rvm ruby version manager on ubuntu-10.04.1-desktop. ruby-1.9.2 , ruby 1.8.7 no problem.

c++ - Pros and cons of 'inline' -

first of all, state facts know 'inline', don't bother restate them. an inline function special kind of function definition must available in every translation unit in function used. it hint compiler (which free ignore) omit function call, , expand body instead of call. the pro know of (2.) may make code faster. the con know if (1.) increases coupling bad. now let's consider templates. if have template library, need provide definitions of function templates in every translation unit, right? let's forget controversial 'export' while, since doesn't solve problem anyway. so, come conclusion there no reason not make template function inline because con of inline know of there priori. please correct me if wrong. in advance. the pro know of (2.) may make code faster. may being operative word. inlined functions may make code paths faster, yes. but inlined function puts additional pressure on instruction cache on modern cpus. i...

android - Instant signal strength -

i need find way measure current signal strength of android phone, without need register phonestatelistener god knows when returns actual asu. something like: int signal = getphonesignal(); any plz? thanks! if have closer on android sources see after registering phonestatelistener have instant notification: public void listen(phonestatelistener listener, int events) { string pkgfordebug = mcontext != null ? mcontext.getpackagename() : "<unknown>"; try { boolean notifynow = (getitelephony() != null); mregistry.listen(pkgfordebug, listener.callback, events, notifynow); } catch (remoteexception ex) { // system process dead } } so can create own timer , on timer update register new listener , after receiving instant update remove passing same listener object , set events argument listen_none . of course can't call best practice alternative can see calculate signal strength...

actionscript 3 - Finding out when Recursion involving Asynchronous operation finishes -

i have recursive call includes asyn operation (file copy) .. want find out when recursive call finishes (along asyn operations). private function copyinto(directorytocopy:file, locationcopyingto:file):void { var directory:array = directorytocopy.getdirectorylisting(); //get list of files in dir each (var f:file in directory) { if (f.isdirectory) copyinto(f, locationcopyingto.resolvepath(f.name)); else { f.copytoasyn(locationcopyingto.resolvepath(f.name), true); f.addeventlistener(event.complete, onfilecopied); } } } function onfilecopied(event){ alert(event.target); // [object file] } basically needed copy folder structure drive,and folder being copied contains files 100-200mb , take time copy,which blanks out ui , flash player. , after files copied, want further things(hopefully without blocking ...

cakephp invalidate element array -

i using cakephp. have form element array. ex:- <textarea name="data[user][0][description]> <textarea name="data[user][1][description]> from controller, need invalidate (manually) array field if empty , need show errors respective field. correct syntax invalidating field if element array ? know, following work single element . how element array ? $this->user->invalidate("description"); unfortunately cannot invalidate field function. but invalidate() does? function invalidate($field, $value = true) { if (!is_array($this->validationerrors)) { $this->validationerrors = array(); } $this->validationerrors[$field] = $value; } it set validationerrors of model. so, can following in controller (but appeal move validation in model): $this->user->validationerrors[1]['description'] = 'your error message'; the following code invalidate second description in lis...

c# - Unable to logout from ASP.NET MVC application using FormsAuthentication.SignOut() -

i trying implement logout functionality in asp.net mvc. i use forms authentication project. this logout code: formsauthentication.signout(); response.cookies.clear(); formsauthenticationticket ticket = new formsauthenticationticket( 1, formsauthentication.formscookiename, datetime.today.addyears(-1), datetime.today.addyears(-2), true, string.empty); response.cookies[formsauthentication.formscookiename].value = formsauthentication.encrypt(ticket); response.cookies[formsauthentication.formscookiename].expires = datetime.today.addyears(-2); return redirect("logon"); this code redirects user login screen. however, if call action method specifying name in address bar (or select previous link address bar dropdown), still able reach secure pages without logging in. could me solve issue? that's strange... make 1 single call to: formsauthentication.signout(); , works... publi...

Can't specify Cobertura datafile location for server running under Ant? -

i have ant build script instruments jar files, starts servers using jars files , runs integration test suite of junit tests against them. i want capture cobertura.ser file each server in separate file. the servers need have working directory set can pick config files. it's requirement of system classpath must not used pick these files. setting net.sourceforge.cobertura.datafile system property allows datafile set, , works ok, until "dir" property set on ant java task. once dir set, server starts correctly, test suite runs ok, when server shuts down no data file written. here's fragment of build.xml: <parallel> <daemons> <java fork="true" dir="src\main\resources\conf\my.server" classname="my.server"> <sysproperty key="net.sourceforge.cobertura.datafile" file="target\cobertura.ser" /> <classpath> ... </classpath>...

Entity Framework; Object-Oriented delete -

i'm building out stock management system @ moment, using entity framework 4. a little background, entities go bit (only showing needed info) product --> productlocations warehouselocation --> has many productlocations each productlocation has quantity what i'm trying have when call product.takefromlocation(wl warehouselocation, qty integer), deletes productlocation if quantity falls zero. however... product entity, productlocation, , meant persistance ignorant. i'm using poco ef templates, couple of modifications produces ientities interface, , generates fakeentities using in-memory versions testing. means entities not know entity framework, , don't inherit or implement interfaces, c ontext.deleteobject() out of bounds. anyone encountered similar scenario , got ideas on how round this? i kind of thought if savechanges() on context partial method, extend check 0-quantities - it's going saves, bit of drag on 90%+ of operations aren't d...

android - Making specific color in bitmap transparent -

i have android application display image on image, such second image's white colour transparent. this, have used 2 imageview s, original image overlaid bitmap1 , image made transparent bitmap2 . when run this, exceptions @ setpixel method. here's code: bitmap bitmap2 = null; int width = imviewoverlay.getwidth(); int height = imviewoverlay.getheight(); for(int x = 0; x < width; x++) { for(int y = 0; y < height; y++) { if(bitmap1.getpixel(x, y) == color.white) { bitmap2.setpixel(x, y, color.transparent); } else { bitmap2.setpixel(x, y, bitmap1.getpixel(x, y)); } } } imviewoverlay imageview of overlay image. idea might going wrong in above code? the obvious error you're not creating bitmap2 - unless you've not posted code of course. you declare , set null , don't else until try call bitmap2.setpixel .

Erlang : JSON List to JSON List -

i have list of json objects (received nosql db) , want remove or rename keys. , want return data list of json objects once again. this stackoverflow post provides sense of how use mochijson2. , i'm thinking use list comprehension go through list of json objects. the part stuck how remove key each json object (or proplist if mochijson2 used) within list comprehension. can use delete function of proplists. unsuccessful when trying within list comprehension. here bit code context : a = <<"[{\"id\": \"0129\", \"name\": \"joe\", \"photo\": \"joe.jpg\" }, {\"id\": \"0759\", \"name\": \"jane\", \"photo\": \"jane.jpg\" }, {\"id\": \"0929\", \"name\": \"john\", \"photo\": \"john.jpg\" }]">>. struct = mochijson2:decode(a). {struct, jsondata} = struct, {struct, id} = prop...

How to make Asynchronous nonblocking thread FACEBOOK in Android -

i trying make facebook asynchronous non blocking thread in android. due our ui run separate thread unable can 1 tell me how that. , if possible pleade give me 1 example. thanks......... i don't know facebook access ui component other thread- public class dictionary extends activity{ handler mhandler; public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); handler mhandler = new handler(); searchthread thread = new searchthread(); thread.setparent(this); thread.sethandler(mhandler); } public void notifyitemchanged(arraylist<listitem> litems){ //write code relating ui here } private class searchthread extends thread{ private handler handler; dictionary parent; public void setparent(dictionary parent) { this.parent = parent; } public void sethandler(handler handler) { this.handler = handler; } @override ...

php - parse an rss feed and update/insert/delete rows -

i'm trying parse multiple rss feeds , if change, update records in mysql table. currently, have script inserts items of rss feeds (just post in url in form , submit). inserts following table: title, rss_url, description, price, discount, total this works well. the next part script updates rows if change in rss, changes if price or discount update. works great what i'm looking is: if item in rss feed removed, script needs detect , delete row or insert flag table been deleted... my code quite long winded: $result = mysql_query("select * easy_contents"); while($row = mysql_fetch_array($result)) { $articles = array(); $easy_url = $row['rss_url']; $rawfeed = file_get_contents($easy_url); $xml = new simplexmlelement($rawfeed); $channel = array(); $channel['title'] = $xml->channel->title; $channel['link'] = $xml->channel->link; $channel['description'] = $xml->channel->description; foreach ($...

vb.net - Is there a one liner to verify XML string structure? -

i have string: dim strxmltags string = "<tags><test>1</test></tags>" and want verify opening tags have closing tag in proper place. if put previous string through, it'd work. however, if put: dim strxmltags string = "<tags><test>1</test>" then want give me error. there xml structure checker or of sorts? or should try , load xml document , if errors then, know. thanks. the easiest way indeed try loading xml document, , see if crashes or not.

java - JPA - using annotations in a model -

my application runs on jpa/hibernate, spring , wicket. i'm trying convert our orm xml files jpa annotations. annotated model looks this: @entity @table(name = "app_user") public class user extends baseobject { private long id; private string firstname; private string lastname; private string email; @id @generatedvalue(strategy = generationtype.sequence) @column(name = "id") public long getid() { return id; } public void setid(long id) { this.id = id; } @column(name="first_name") public string getfirstname() { return firstname; } public void setfirstname(string firstname) { this.firstname = firstname; } @column(name="last_name") public string getlastname() { return lastname; } public void setlastname(string lastname) { this.lastname = lastname; } @column(name="email") public string g...

xml - Transforming XSLT text element with "one space character" yields empty content -

i've got incoming xml i'm transforming (with xslt in asp using msxsm6): <cell> <data xmlns="http://www.w3.org/tr/rec-html40"> <font>text1</font> <font> </font> <font>text2</font> <data> </cell> if template <font> is: <xsl:template match="font"> <xsl:copy/> </xsl:template> the transform seems kill off space character in 2nd element in source, output xml emitted below, 2nd element becomes empty 1 no content: <font>text1</font> <font/> <font>text2</font> i trialed-and-errored on <xsl:preserve-space elements="font"/>' didn't seem help. ideas? stackoverflow! first, stylesheet fragment sample wrong. need rule this: <xsl:template match="html:data//node()|html:data//*/@*" xmlns:html="http://www.w3.org/tr/rec-html40"...

sql server 2008 - sqlcmd syntax error at line -

i used sql server 2008 script wizard create script recreate database , components on remote server sql server 2005. executing sqlcmd since on 8gigs large ran until gave following error: sqlcmd syntax error @ line 40875 @ ')' i cannot open script file check since large , checked sql server management studio , tables created except 1 , none of triggers, functions etc created. need recreate script each of these not transferred , why there syntax errors if sql creates script itself? ignore question...i mean scripting need curious why wizard generates errors.

dynamic - Binding to the change event in dynamically created dropdown list using jQuery -

i creating number of dropdown lists dynamically using jquery. able trigger event when selected dropdown list item changes. browsing on here , elsewhere see it's not possible bind change event of dropdown lists using live() wondering alternatives? know it's possible bind click event since occurs before dropdown list selection can change it's no use me tracking if selected item has changed. this relevant part of code. alert triggers when of dropdown lists clicked on of course prefer if alert triggered when selected item changed. $(document).ready(function() { // stuff omitted. addeventhandlers(); } function addeventhandlers() { // stuff omitted. $('#divreview select').live("click", function(){ alert('this change event occur instead.'); }); } use change event instead of click , this: $('#divreview select').live("change", function(){ there bug in ie before jquery 1.4.2 release. bef...

asp.net mvc 2 - Ajax.BeginForm + Updating entire page in IE9 -

i'm using mvc2 , have telerik popup window in i'm doing search , wanting display search results in second tab. i have search form in first tab, on post, perform search , have partialview containing telerik grid. works in chrome, when give go in ie9, shows search results on brand new page. ajax.beginform("search", "datasearch", new ajaxoptions { updatetargetid = "pnlsearchresults", onsuccess = "showsearchresults", httpmethod = "post", insertionmode = insertionmode.replace, loadingelementid = "searchingprogess" })) the div, pnlsearchresults contained in second tab , outside of form. i believe had elements being inside form. moved loading div outside form, reloaded , appears working fine now.

oracle10g - appropriate mapping to java type for oracle sequence -

probably real beginner question, cannot find answer on web. have oracle db, table primary key number(16) , filled sequence, max value 999999999999999999999999999 . what java type should use hold sequence value ? long, biginteger or bigdecimal? thank in advance long should has maximum value of 2^63 - 1