Posts

Showing posts from March, 2015

java - Programmatically invoke the JSP parser -

i invoke jsp parser programmatically. means want able, in java, 'run' jsp page , output, without sending client (i want save output file). don't want 'forward' request jsp page. want able on several jsp pages in row. what best way of doing this? i have found question , balusc doesn't answer question directly. in case wondering, need because want 'precompile' jsps using on other platforms java servlet container. edit what need not .class file, html output. indeed, static once generated have custom jsp tags , want leverage jsp parser expand them. i'm not sure understand point of this. jsps parsed , precompiled .class files. they're java servlets @ point. need servlet engine execute them. if intent capture generated http response "precompiled" response, suggest there's no dynamic content , response same every time send particular request. if that's case, you've got static html. if i'm corre

java - Benefits of using Springs Transaction management vs using hibernate -

i've been trying learn spring , hibernate, , i've used lot of examples around net put nice application. however, realized spring supports transaction management. in spring app made whatever calls wanted to, directly hibernate. there reason/benefit why people use spring's transaction management/db stuff? the real advantages are: lightweight declarative syntax. compare: public void saveemployee(employee e) { session s = sf.getcurrentsession(); s.gettransaction().begin(); s.save(e); s.gettransaction().commit(); } and @transactional public void saveemployee(employee e) { sf.getcurrentsession().save(e); } flexible transaction propagation. imagine need execute saveemployee() method part of complex transaction. manual transaction management, need change method since transaction management hard-coded. spring, transaction propagation works smoothly: @transactional public void hireemployee(employee e) { dao.saveemployee(e);

tsql - "Partitioned" sorting in a SQL query -

the following sql query displays products sold sorted cost , number of orders have sorted in partitioned manner. namely, products cost of under $100 should go first , else > $100 should follow it. adding having ts.totalsold < 100 query accomplish first partition, filter out other products. operation should atomic, query can executed once. note: cost query has partitioned calculated max of 2 cost columns, makes things bit more complicated (the proposed solutions of case when won't work highestcost not column) select ps.productname, ts.totalsold, ((ps.cost1 + ps.cost2 + abs(ps.cost1-ps.cost2)) / 2) highestcost products ps cross apply (select (select count(orderid) orders os os.productid=ps.productid) totalsold) ts order highestcost asc, ts.totalsold edit : modified query include calculated cost query has partitioned. edited select * ( select ps.productname, ts.totalsold, ((ps.cost1 + ps.cost2 + abs(p

c# - Deserializing from JSON (ScriptObject) to Managed Object -

i'm attempting deserialize json returned javascript via silverlight. basically on client side returning json , in c# handler, getting via scriptobject... i tried convertto method on scriptobject , still not anything. how able convert scriptobject c# object list of objects? somecallback(scriptobject result) { // convert managed object var objects = result.convertto<list<someobjectclass>>(); // can't property it.. // count correct... messagebox.show("count: " + objects.count); // shows correct count of items } silverlight contains no api take scriptobject , serialise json string. silverlight supports json serialisation via system.runtime.serialization.json.datacontractjsonserializer class found in system.servicemodel.web dll. you need javascript base json serialiser convert value trying pass scriptobject pass json string parameter instead of scriptobject . believe popular tool job jquery. now looks expecting

python - How do I get redmine's activity log to show repository changes automatically? -

i wrote little python script accept bitbucket post callbacks of repository changes , update local copy. works fine, noticed redmine's activity log doesn't show changes until click on repository tab. is there way trigger activity log update programatically? misunderstood question in irc, can find answer question in redmine faq

Android accessing parent class values after starting an intent? -

i'm starting intent in activity class ttwifi.java follows intent = new intent(this, socketclient.class); startactivity(i); now how access variables of ttwifi.class socketclient.class ? i believe there way send values between them. new android, guess fundamental stuff :) appreciate if can me out in this... through following code can share values activities intent i=new intent(fitnessgraph.this,nami.class).putextra("<stringname>"," string value"); use above code in parent activity , using below line can retrieve value in child activity.write line in child activity string s= getintent().getstringextra("<stringname>");

c# - How do I assign an event handler to an event in C++/CLI? -

how add "events" "event"/delegate? syntax? same in c++/cli , in c#? in c# , += operator: someobj.someevent += new eventhandler(blah_someevent); ... private void blah_someevent(object sender, eventargs e) { } more-than-a-year-later-edit it has been long time since posted answer , noticed me maybe wrong. don't know why op marked answer right 1 (maybe op looking rather c++-cli syntax? knows now) . anyway, in c++-cli be: someobj->someevent+= gcnew eventhandler(this, &blah_someevent);

java - retrieve jsf bean in axis2 web service as server request -

i using eclipse axis2 create web service client wsdl. my impl method is: public output[] startprocess(message[] messages){ myapplicationbean managementbean = (myapplicationbean) facescontext.getcurrentinstance().getexternalcontext().getapplicationmap().get("myapp"); ... } however when execute: http://localhost:8080/myproject/services/portstartprocessservice method startprocess i see in tomcat debug reaches method, facescontext.getcurrentinstance() returns null. my web.xml (part of it) <servlet-mapping> <servlet-name>faces servlet</servlet-name> <url-pattern>*.jsf</url-pattern> <url-pattern>/services/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>axisservlet</servlet-name> <url-pattern>/servlet/axisservlet</url-pattern> </servlet-mapping> how can use jsf beans (like application scope) in web services call? i know no

ruby on rails - Safe Erb plugin Implementation Issue -

i trying implement safe erb plugin in rails 2.0.2 app. using version project specific purposes along ruby 1.8.7. i have referred following tutorials: http://www.railslodge.com/plugins/430-safe-erb http://agilewebdevelopment.com/plugins/safe_erb i make sense of above url's newbie rails , rails related plugins. found above tutorials generic. i couldn't relate plugin's use great extent in terms of real world sense above tutorials. please enlighten me on usage on day day real world....? i have implemented books appl has author, title , publishing date. facing issues implementing taint feature of plugin in second tutorial, need call tainted? method objects class. have done in create method of books_controller.rb. code create method looks this: def create @book = book.new(params[:book]) @book.publishing_date = params[:publishing_date] respond_to |format| if @book.save flash[:notice] = 'book created.' format.htm

c# capture microphone -

can tell me how capture microphone , send on ip? there example of how capture , put buffer in order send on udp socket computer , listen song? i'm working in c#. thx. apprecciate if there can give me example:) you can find open source projects inspired from: http://www.voip-info.org/wiki/view/open+source+voip+software if want stream audio via udp maybe don't need full implementation of sip stack if want make skype-clone do.

ios simulator - How to determine on which iPhone my App is running? -

i looked around find, how can know on iphone app running (iphone 3g, iphone3gs, iphone 4) additional things depending on device. preferred method this: size_t size; sysctlbyname("hw.machine", null, &size, null, 0); char *name = (char *)malloc(size); sysctlbyname("hw.machine", name, &size, null, 0); nsstring *machine = [nsstring stringwithcstring:name]; free(name); if([machine compare:@"iphone3,1"]==nsorderedsame){ //iphone 4 }else if([machine compare:@"i386"]==nsorderedsame){ //simulator }else{ //iphone 3gs, 3g... } nslog(@"device %@", machine); this worked fine far, updated x-code , simulator. possible run simulator iphone 4, iphone3gs or iphone3g. how can detected @ runtime? solutions or workarounds far? edit: solution here http://iphonedevelopment.blogspot.com/2009/05/device-detection.html of course isn't working anymore, since simulator can iphone4! never coded iphone, googled , found th

c++ - Why do I get an error trying to call a template member function with an explicit type parameter? -

i don't it, seems me call f unambiguous, fails compile expected primary-expression before ‘int’ . if comment out line call f , compiles fine. template<typename t> struct { template<typename s> void f() { } }; template<typename t> struct b : a<t> { void g() { this->f<int>(); } }; this due obscure provision of standard in if have template tries access template function in object type depends on template argument, have use template keyword in weird way: this->template f<int>(); this similar weirdness typename comes dependent types, except applied functions. in particular, if leave out template keyword, there's parsing ambiguity between this->f<int>() (what intended), and ((this->f) < int) > () which makes no sense (hence error). use of keyword template here disambiguates , forces compiler recognize it's looking @ valid call templated member function rather gar

picturebox - Display WPF Image in backgroundworker -

i using wpf 3.5. i have while loop in backgroundworker_dowork event, continuously stream images dslr. initially, streamed image displayed in picturebox <grid> <windowsformshost verticalalignment="top" background="transparent" height="500"> <wf:picturebox x:name="picliveview" /> </windowsformshost> </grid> here code behind: while (!liveviewexit) { try { if (picimage != null) lock (mylock) { this.picliveview.image = (image)picimage.clone(); } } catch { } } this works fine. however, when try change picturebox wpf image control, have error when assigned bitmapimage wpf image control: {"the calling thread cannot access object because different thread owns it."} memorystream

How to convert Ruby's SHA512.hexdigest to C#? -

i'm re-writing rails web app in c#. i'm stuck ruby's hash function: # generates 128 character hash def password.hash(password,salt) digest::sha512.hexdigest("#{password}:#{salt}") end the following c# function gives different result: private static string hash(string password, string salt) { return bitconverter.tostring(new sha512cryptoserviceprovider().computehash(encoding.utf8.getbytes(password + ":" + salt))).replace("-", "").tolower(); } what doing wrong? thank you never mind. results are same. if ever need convert ruby's hashing c#, digest::sha512.hexdigest(some_string) does same bitconverter.tostring(new sha512cryptoserviceprovider().computehash(encoding.utf8.getbytes(somestring))).replace("-", "").tolower(); c# lot more verbose, main thing works! :)

regex - Verifying the format of a text file? -

i have application downloads .txt file via ftp, , calls sql insert file data database. want check whether file in correct format before trying insert. the file should consist of number of rows, each following format: (4 letter code) (tab) (3 or 4 letter code) (tab) (date dd-mmm-yy) (tab) (variable length text description) (tab) (1 letter code) is there way check whether every line in file follows pattern, , warn me if doesn't? sounds typical use case regular expressions . create regex pattern , match against each line in file. if aren't familiar regex, maybe you'll find this link helpfull in addition links above. the pattern looking propably this: ^\w{4}\t\w{3,4}\t\d{2}\-\d{3}\-\d{2}\t.*\t\w$ it match text these (imagine _ tab): test_foo_12-feb-11_this text_x test_fbar_01-jan-15_bla bka bla_o but not: test123_foo_12-feb-11_this text you this: dim pattern = "^\w{4}\t\w{3,4}\t\d{2}\-\d{3}\-\d{2}\t.*\t\w$" each line in text

c# - Logging a lot of operations efficiently -

we want go deeper on logging @ work , planning log virtually every important thing happening in our system, such audit operations performed on db tables , other business operations happening in system , in services thereof, generate thousands of records every couple of hours. the logging system should - of course- easy use , configure, , able queried real-time. my questions are: 1) can "the audit operations on db" part handled sql-server itself? have own logging mechanism? 2) how , can log other business operations? first framework comes mind log4net, i'm still not sure log them don't want overfill db time. using whole different db logging purposes, or producing text files out of db periodically , zipping them, etc. way? how enormous systems handle kind of elaborated logging processes? log4net has whole bunch of appenders can configure in app.config , change without need rebuild anything, can have database appenders, smtpappenders, rolling fil

qt - Calling Innovator Contest 2011-Use of NokiaQtSDK for Developing VOIP and APS Apps -

i want develop application calling innovator contest 2011. seems application developed using 4.6.3 (nokiaqtsdk) accepted. i have questions needs help can develop application uses voip , aps plugins ? is acceptable contest , since these plug ins more platform specific ? can ignore built in nokiaqtsdk , use 4.6.3 sources s60 develop app ? does calling innovator contest 2011 have separate forum discussion? i don't stops reading competition's rules. once that, adopt simple rule: whatever not expressly prohibited considered allowed. yes, can use platform specific apis want , can develop sdk long know doing , working application submit ovi store. make sure of made qt, since indeed requirement.

java - Eclipse Strange Errors -

my eclipse galileo installation has started giving me problems of sudden. yesterday unable start tomct6 server , today unable create dynamic web project. i following error selected wizard not started. plug-in "org.eclipse.jst.servlet.ui" unable instantiate class "org.eclipse.jst.servlet.ui.project.facet.webprojectwizard". java.lang.nullpointerexception my eclipse shared colleagues, issue ? installed m2 sonatype plug in maven 2. have updated eclipse recently? quick googling seems mixing galileo updates helios in modules causing error message. suggest download eclipse helios , point current workspace.

.net - Why don't the EF caching providers update VIEW results? -

i have large application using entity framework , cool ef4 caching providers. 99% of time works it, have few sql server views inported try speed joins , when save object using entity framework, contents of cached view not updated? right, should have invalidate view results somwhow or bug?

Passing search param through php script -

i want create php script send search param gas buddy and return resultant web page. how can start process? you have use curl extension.

Python - Noob Question - What does it mean "Giving one of the optional arguments"? -

what do? giving 1 of optional arguments: ask_ok('ok overwrite file?', 2) def ask_ok(prompt, retries=4, complaint='yes or no, please!'): while true: ok = input(prompt) if ok in ('y', 'ye', 'yes'): return true if ok in ('n', 'no', 'nop', 'nope'): return false retries = retries - 1 if retries < 0: raise ioerror('refusenik user') print(complaint) see tutorial: http://docs.python.org/py3k/tutorial/controlflow.html#default-argument-values sets retries 2 , leaves complaint on default value 'yes or no, please!'. order of optional arguments in first line of function definition important.

entity framework mark as modified code first 5 -

marking property modified should done this: using (var context = new unicornscontext()) { var unicorn = context.unicorns.find(1); var nameismodified1 = context.entry(unicorn).property(u => u.name).ismodified; // use string property name var nameismodified2 = context.entry(unicorn).property("name").ismodified; } code sample here in code unicornscontext extends dbcontext . i don't have entry method context. whats's wrong?

c# - jsonresult does not come back? -

trying display success message controller? [httppost] public jsonresult succesmsg() { return json(new { success = true }); } jquery: $("#but").click(function () { $.ajax({ url: "/home/succesmsg", type: 'post', data: "", success: function (result) { if (resultjson['success'] == true) { alert('success'); } else { alert('no'); } }, error: function (err) { alert('error') } }); }); add datatype: "json" $.ajax call or use shorthand: $.getjson . also check controller handles response returns in state http 200 (ok). for debugging, add complete: function(){alert('complete');} see if request completes or not. debugging tools (

c++ - Convert char array to unsigned char* -

is there way convert char[] unsigned char* ? char buf[50] = "this test"; unsigned char* conbuf = // should add here although may not technically 100% legal work reinterpret_cast<unsigned char*>(buf) . the reason not 100% technically legal due section 5.2.10 expr.reinterpret.cast bullet 7. a pointer object can explicitly converted pointer object of different type. original type yields original pointer value, result of such pointer conversion unspecified. which take mean *reinterpret_cast<unsigned char*>(buf) = 'a' unspecified *reinterpret_cast<char*>(reinterpret_cast<unsigned char*>(buf)) = 'a' ok.

python - Overcoming the size entry size limit for appengine search? -

i trying use searchable model blog entries , worked fine on development platform when try add entry in cloud error: traceback (most recent call last): file "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/init.py", line 517, in call handler.post(*groups) file "/base/data/home/apps/smart-fast/1.348228399174418277/admin.py", line 76, in post article.put() file "/base/python_runtime/python_lib/versions/1/google/appengine/ext/db/init.py", line 895, in put return datastore.put(self._entity, config=config) file "/base/python_runtime/python_lib/versions/1/google/appengine/api/datastore.py", line 404, in put return _getconnection().async_put(config, entities, extra_hook).get_result() file "/base/python_runtime/python_lib/versions/1/google/appengine/datastore/datastore_rpc.py", line 601, in get_result self.check_success() file "/base/python_runtime/python_lib/versions/1/google/appengine/datas

plsql - Exporting rows in Oracle -

i need export number of rows (from different tables- ie, related information entity - eg: customer) db in oracle. how this? using windows os. please help. thank all, pradeep while connected database 1 create database link database 2 (if have rights - there no assumptions on this) , insert tables selecting link e.g. this create database link foo connect <user> identified <password> using '<connect string>'; select * table1@foo; further information: a database link connection between 2 physical database servers allows client access them 1 logical database. see dabtabase links @ oracle database administrator's guide.

VB.NET: How to overload Dictionary.Item(TKey) -

i created own dictionary class, based on .net dictionary. now want overload item() method. works fine following code: public overloads property item(byval key tkey) tvalue return nothing end set(byval value tvalue) mybase.item(key) = value end set end property when use dictionary.item(key) access value nothing. when use dictionary(key) syntax value , not nothing. how can correctly overload dictionary.item(key) , dictionary(key)? thank torben the property must marked default enable indexer syntax. public overloads default property item(byval key tkey) tvalue return nothing end set(byval value tvalue) mybase.item(key) = value end set end property

java - Query with JOIN FETCH performance problem -

i have problem hibernate query performance can't figure out. in code snippet below need select entities @ least 1 mapping , filtered mapping. i'm using fetch join load filtered mappings. in case have performance problems query. hibernate says warning log : org.hibernate.hql.ast.querytranslatorimpl - firstresult/maxresults specified collection fetch; applying in memory! when omit fetch join , left join query nice fast. in result have mappings loaded entity not acceptable state me. there way boost query performance? there lot rows in mapping table. hql query : select distinct e entity join fetch e.mappings mapping e.deleted = 0 , e.mappings not empty , e = mapping.e , mapping.approval in (:approvals) entities : @entity @table(name="entity") class entity { ... @onetomany(mappedby="entity", cascade=cascadetype.remove, fetch=fetchtype.lazy) @orderby("created") private list<mapping> mappings = new arra

android emulator does not work properly -

i know android emulator slow, , read lot here in stackoverflow. problem when run emulator, instead of going android home screen shows me screen button, 1 likes 'lock' , other looks 'speaker'. , sometime (like moment writing question), screen shows 'android' text , nothing happens. when says 'android', it's booting. wait. can take few minutes. when it's lock , speaker, it's lock screen. slide lock right go home screen.

c++ - How read Linux or Mac created file in Windows via C FILE*? -

as know in windows eol crlf , in linux lf , cr in mac. ( more_info ) i want write program reads linux , mac win files line line in windows. open file use fopen in "rt" mode, don't know how read lines. fgets reads until crlf , lf under windows want work eol=cr files also. so solution? in advance. to open in "t" mode, file must conform platform running on. otherwise have open in binary mode, , sort difference out yourself. the c library helps write program works same on different platforms, not support "cross reading" files.

actionscript 3 - Flash AS3 - removeChild() used to completely delete object? -

i'm creating asteroids game , in main class i'm having trouble handling bullets ship fires. all of bullets of "bullet" class , stored in array called "bullets" in main class. when bullets exit screen, removebullet(bulletid) in main class called. private function removebullet(id:int) { removechild(bullets[id]); bullets.splice(id); } in bullet class have enterframe listener traces "stillhere". bullet added main stage using addchild, "stillhere" starts popping in output panel. my problem after call removebullet, "stillhere" keeps popping in output panel, tells me object tried delete still sticking around somewhere in memory. what can rid of completely? because in actionscript have no direct control on when objects removed. the real problem have event listeners still firing. can solve calling removeeventlistener when deleted. however a better approach have 1 enter_frame listener

javascript: generate 2 random but distinct numbers from range -

quick question: what best way implementing line of python code (generates 2 random distinct numbers given range)... random.sample(xrange(10), 2) ...in javascript? thanks in advance! martin here attempt using splice: var = [1,2,3,4,5,6,7,8,9,10];var sample = []; sample.push(a.splice(math.random()*a.length,1)); sample.push(a.splice(math.random()*a.length,1)); wrapped in function: function sample_range(range, n) { var sample = []; for(var i=0; i<n; i++) { sample.push(range.splice(math.random()*range.length,1)); } return sample; } var sample = sample_range([1,2,3,4,5,6,7,8,9,10], 2); we stick function array.prototype have dot notation syntax: array.prototype.sample_range = function(n) { var sample = []; for(var i=0;i<n;i++) { sample.push(this.splice(math.random()*this.length,1)); } return sample; }; var sample = [1,2,3,4,5,6,7,8,9,10].sample_range(2);

One XCode project, two target, two apps (iPhone/iPad) not universal app -

Image
we have xcode project first build universal app, , on road changed our mind on having 2 app in same binary, created 2 targets. the first 1 called: appname , iphone: base sdk 4.2 , deployment target 3.1.3. targeted device iphone. the second called: appnamehd , ipad: base sdk 3.2 , targeted device ipad. it's been few weeks building each of platform , able deploy on both ipad , iphone. now ready submit app store , i'm worried potential rejection of code. want submit ipad app now, i've looked around there in itunesconnect site can specify targeted device, , project structured first universal app. i'm wondering how determine on device test binary. more informations architecture: using default generated info.plist file both targets. should have separate info.plist each of target? differences should present between 2 .plist files. here attached actual info.plist file using. thanks in advance. first of all, there's no reason why base sdk ipad tar

android - Activity having static reference -

i'm working on exiting android code written else , has several memory issues. 1 issue i'm not able understand this. in main activity class has static method called getreference(). method returns reference variable called mthis . now, in oncreate method class myactivity extends activity { private static myactivity mthis; public myactivity getreference(){ return mthis; } public oncreate(bundle savedinstancestate){ mthis = this; } ... } now in content provider or class extending dialog class, uses static method reference context. i'm pretty sure not correct , 1 of reason memory leak. there way current context without passing context object in every class. there application context don't think has method current context. i can remove method , pass reference context object these classes. there other way fix this. i'm pretty sure not correct , 1 of reason memory leak. yes. but there way

Using Toggle with jQuery / ajax -

what i'm trying toggle. onclick event set in html. external div loaded onclick opens (appended). when click link again it's appended again. wrong. want close. open , close. keeping onclick event in html. how???? here's code... (function($){ $.am_get_item = function (item_id, size_id){ $.ajax({ url: "/order/item/" + item_id + "/" + size_id, success: function(data){ $(".item_form").hide(); $(data).find("#show_item").appendto("#form_" + item_id); $("#form_" + item_id).slidedown("slow"); $("input#form1").keyup(function () {var value = $(this).val();$("div#ok").text(value);}).keyup(); }}); } })(jquery);

Datepicker in jquery mobile is duplicate when is added in a second page -

i'm needing datepicker use in mobile app. i'm using jquery ui datepicker in app. datepicker show twice (duplicate) when put in second page. when put datepicker in first page, shown ok. this example, if run can see datepicker duplicate in second page. <!doctype html> <html> <head> <title>datepicker test</title> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a3/jquery.mobile-1.0a3.min.css"/> <link rel="stylesheet" href="http://jquerymobile.com/demos/1.0a3/experiments/ui-datepicker/jquery.ui.datepicker.mobile.css" /> <script src="http://code.jquery.com/jquery-1.5.min.js"></script> <script src="http://jquerymobile.com/demos/1.0a3/experiments/ui-datepicker/jquery.ui.datepicker.js"></script> <script src="http://jquerymobile.com/demos/1.0a3/experiments/ui-datepicker/jquery.ui.datepicker.mobile.js"

ruby on rails - What's an appropriate way to override the view of a gem? -

i thought overkill unpack entire gem application. there way override single view provides? this gem spree_easy_contact allows add contact form spree application. want tamper 1 of views alternative. if gem namespaced, can namespace view in local application. example, if gem namespaced best_gem_ever, app structure this: app - assets - controllers - helpers - mailers - models - views - - best_gem_ever - - - wonderful_controller - - - - index.html.erb at job, purposefully use technique allow clients overwrite front-end views while still pulling administrative views gem. works well. one caveat, if create asset files store in local assets folder, reason asset pipeline doesn't pick them up. have explicitly added config.assets.precompile list. hope helps!

Android theme not being set -

i have theme refuses applied activities - none of styles applied. if don't supply layout_width / layout_height attributes <button> gets runtime error, showing button class isn't being applied. /res/values/themes.xml : <?xml version="1.0" encoding="utf-8"?> <resources> <style name="theme" parent="android:style/theme.black"> <item name="android:windownotitle">true</item> <item name="android:buttonstyle">@style/button</item> <item name="android:windowbackground">@color/page_background_light</item> <item name="android:textappearance">@style/textappearance</item> </style> </resources> /res/values/styles.xml : <?xml version="1.0" encoding="utf-8"?> <resources> <style name="textappearance" parent="@android:style/text

slice - Python : Why use "list[:]" when "list" refers to same thing? -

consider list >>> l=[1,2,3] . what benefit of using >>> l[:] when >>> l prints same thing former does? thanks. it creates (shallow) copy. >>> l = [1,2,3] >>> m = l[:] >>> n = l >>> l.append(4) >>> m [1, 2, 3] >>> n [1, 2, 3, 4] >>> n l true >>> m l false

python - subprocess.Popen and buffered process output -

from inside python code, want run binary program gets parameters stdin. using subprocess module, should straightforward: import subprocess command = [ 'my_program' ] p = subprocess.popen( command, \ stdin = subprocess.pipe, stdout = subprocess.pipe, \ env={ "gfortran_unbuffered_all": "1"} ) p.stdin.write ( stdin_stuff ) while true: o = p.stdout.readline() if p.poll() != none: break # stdout now, launches program, python script hangs there. understand may due gfortran (which use compile my_program buffering stdout stream. gfortran allows 1 use gfortran_unbuffered_all environmental variable, have done, using flush() intrinsic in fortran code, still no luck: python code still hangs. you should have better luck using popen.communicate() send strings process' stdin rather manually writing it. stdoutdata, stderrdata = p.communicate(stdin_stuff)

How to separate string into parts in PHP -

right have: $path2 = $file_list1; $dir_handle2 = @opendir($path2) or die("unable open $path2"); while ($file2 = readdir($dir_handle2)) { if($file2 == "." || $file2 == ".." || $file2 == "index.php" ) continue; echo ''.$file2.'<br />'; } closedir($dir_handle2); echo '<br />'; when $file2 returned, last 4 characters in string end in number plus file extension .txt, this: file_name_here1.txt some_other-file10.txt so question is, how can separate $file2 returns string in 2 parts, $file_name , $call_number this?: echo 'file: '.$file_name.' call: '.call_number.'<br />'; returns: file: file_name_here call: 1 file: some_other-file call: 10 instead of this: echo ''.$file2.'<br />'; returns: file_name_here1.txt some_other-file10.txt thanks.... i'm big advocate of regex decided go different here. check out: $file = 'fi

c# - Using a combination of two fields as key in a dictionary -

i need store c# dict can store members based on intptr , enum (castable int if helps). in other words, if same match of intptr , enum (named sp_playlist_type) need able same result out, (that's important). i've figured i'd make struct containing two, , override gethashcode(), i'd need hashing-algorithm doesn't create duplicates 2 numbers, , generates same result every time same 2 numbers present. i think based on way tuple's gethashcode , equality alredy created, have: dictionary<tuple<intptr, yourenum>, yourresulttype> provided on .net 4.0 of course.

python - Removing duplicated lines from a txt file -

i processing large text files (~20mb) containing data delimited line. data entries duplicated , want remove these duplications keep 1 copy. also, make problem more complicated, entries repeated bit of info appended. in case need keep entry containing info , delete older versions. e.g. need go this: bob 123 1db jim 456 3db ax dave 789 1db bob 123 1db jim 456 3db ax dave 789 1db bob 123 1db bits this: jim 456 3db ax dave 789 1db bob 123 1db bits nb. final order doesn't matter. what efficient way this? i can use awk, python or standard linux command line tool. thanks. how following (in python): prev = none line in sorted(open('file')): line = line.strip() if prev not none , not line.startswith(prev): print prev prev = line if prev not none: print prev if find memory usage issue, can sort pre-processing step using unix sort (which disk-based ) , change script doesn't read entire file memory.

Android ACTION_SEND Intent and Google Analytics - how do I know what they picked? -

we using google analytics track features of our application being used , how, question apply situation want know user did after calling action_send intent. basically, want use functionality allow users share content (email, twitter, facebook, etc.) works wonderfully using stock android intent functionality, allowing user pick preferred email client, twitter app, ect. intent sharingintent = new intent(intent.action_send); //text seems necessary facebook , twitter sharingintent.settype("text/plain"); sharingintent.putextra(intent.extra_text, "whatever want share"); startactivity(intent.createchooser(sharingintent,"share using")); however, can't find way know user did upon return intent. looked using startactivityforresult instead, seems return whether or not completed or canceled sharing (and seems inconsistently implemented across different applications) - doesn't give me information on did. at

.net - Remove row from DataGridView -

in order initialize vouchersdgv data grid view i'm using following dgv.allowusertodeleterows = true = 1 dgv.rowcount - 1 dgv.rows.remove(dgv.rows(i - 1)) dgv.refresh() next but when i'm runing first time take error of {"uncommitted new row cannot deleted."} system.invalidoperationexception if continue , run code , write new row in data grid , try initialize again (now have 2 rows, 1 has data , other empty) take error {"uncommitted new row cannot deleted."} system.invalidoperationexception i can't solve it, please there assist me on that? if not dgv.rows(i).isnewrow dgv.rows.removeat(i) end if add condition loop. alternatively, use dgv.rejectchanges() reset row status original.

What is the diskspace free and used in android? -

a code/simple function return available , used diskspace in main android device. is making df command , parsing best way? other methods can used? many in advance i managed fix make nice class. // phone storage public static long phone_storage_free(){ file path = environment.getdatadirectory(); statfs stat = new statfs(path.getpath()); long free_memory = stat.getavailableblocks() * stat.getblocksize(); //return value in bytes return free_memory; } public static long phone_storage_used(){ file path = environment.getdatadirectory(); statfs stat = new statfs(path.getpath()); long free_memory = (stat.getblockcount() - stat.getavailableblocks()) * stat.getblocksize(); //return value in bytes return free_memory; } public static long phone_storage_total(){ file path = environment.getdatadirectory(); statfs stat = new statfs(path.getpath()); long free_memory = stat.getblockcount() * stat.getblocksize(); //return value in bytes

java - how to embed spring mvc application with jetty -

i have working spring mvc application(doing wanted when deployed jboss) , i'm looking way how start application jar. i've though of when starting jar, first kind of web server should started in order able run application. and i've tried tons of combinations jetty(lost 2 days already), , failed every 1 of them, suggestions https://stackoverflow.com/tags/embedded-jetty/hot my main weakness don't have thorough understanding of servlets, contexts , on. terms see on regular basis while browsing google search, maybe found solution didn't understand it. has done similar? , yes i've asked similar question tomcat : maven tomcat plugin yes, i've done sort of several times, , it's straight forward if know how bits work. since you've explained don't know how bits work, that's going bit harder :) they're not hard learn, , easiest way learn doing - you're heading down right path. the accepted answer here: executable war fi

python - Getting progress message from a subprocess -

i want start program needs several minutes complete. during time want read progress message of program (which printed on stdout). problem cannot find way read out output during run. the function found read out output of program popen.communicate() , method waits until process finishes. impossible progress , make visible user in special formatted way. is possible way? when run process subprocess.popen script see output of program on screen. possible hide it? (ubuntu 10.10, normal terminal) simplest call popen keyword argument stdout=subprocess.pipe . p = subprocess.popen(["ls"], stdout=subprocess.pipe) while true: line = p.stdout.readline() if not line: break print line to see in action, here 2 sample scripts. make them both in same directory , run python superprint.py printandwait.py: import time import sys print 10 sys.stdout.flush() time.sleep(10) print 20 sys.stdout.flush() superprint.py: import subprocess import sys p

Embedding PHP include statements within a string that gets echoed -

i've been trying clean site defining site structure php string variables , echoing variables out. condenses of site structure down 5 lines article in between echo statements. page looks this: <?php include('modules/moddefault.php'); //link site structure set variables $title = "example page"; // define page title. inserted embedded title statement. echo "$modtop"; // declaration, head, title etc. echo "$precontent"; // pre-content structure ?> <h1>web content goes here</h1> <p>article content nice , uncluttered.</p> <?php echo "$postcontent"; // post-content structure ?> i'm wondering how can embed css includes inside of php string variable. php includes don't register because php has processed page. include statements being printed scree

ruby - ActionMailer 3 without Rails -

i'm writing small ruby program pull records database , send html email daily. i'm attempting use actionmailer 3.0.3 this, i'm running in issues. searching i've done far on using actionmailer outside of rails applies versions prior version 3. point me in right direction of find resources on how this? here's far on mailer file: # lib/bug_mailer.rb require 'action_mailer' actionmailer::base.delivery_method = :file class bugmailer < actionmailer::base def daily_email mail( :to => "example@mail.com", :from => "example@mail.com", :subject => "testing mail" ) end end bugmailer.daily_email.deliver i'm stuck on put views. every attempt i've made tell actionmailer templates has failed. i guess should ask if there's different way go accomplishing program. basically, i'm doing scratch @ point. makes rails awesome it's convention, trying use

SketchFlow / Using (Selected) TabItem in TabControl to Trigger State -

context: new sketchflow / silverlight project. expression blend 4 (ultimate) i have below code. have tabcontrol 2 tabitem's. have 2 "callout" (big bubble things) quick visual on state change. i created visualstategroup , added states under it. when manually invoke these navigate window (after run project), states work expected. callout1 , callout2 flip flop opacities (between 100% , 10%). have basic understanding of state's , how work. however, when add trigger event tabitem, trigger looks good, not work. below stripped example, down bare bones. i tried eventname="mouseleftbuttondown" , eventname="click" no luck. i commented out objectanimationusingkeyframes tags, no luck there well. anybody see i'm missing? basically, cannot (selecting) tabitem trigger state change. thanks. -----------start xaml code <usercontrol xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://sch

c# - Why is it possible to create a new instance of a COM interface? -

i don't have background regarding com nor coclasses, don't quite understand why can use new operator interface. language/framework-agnostic view, it's confusing why compiles , runs correctly: using microsoft.office.interop.excel; public class excelprogram { static void main(string[] args) { application excel = new application(); } } inspecting application in visual studio 2010 shows me: using system.runtime.interopservices; namespace microsoft.office.interop.excel { // summary: // represents entire microsoft excel application. [guid("000208d5-0000-0000-c000-000000000046")] [coclass(typeof(applicationclass))] public interface application : _application, appevents_event { } } what going on behind scenes? this possible com interfaces, believe. marc gravell has explanation here . the short answer com interface can paired "default" implementation class, when "instantiate"

facebook c# sdk - Canvas authentication for c# asp.net and general principles -

i trying find general principles of using facebook c# sdk write canvas application. my approach follows. have master page attempt authorise on oninit page. well. first time round not authorized , second time round are. when post goes wrong. have expected authorization / cookies / session item / viewstate item hang around , authorizer item remain authorised. this appears not case. should check authorization once , stick auth token in memory? when want information / post information, pass auth token in manually? is general principle when want post / create new instance of facebookapp , pass in auth token? here code using. can general principles specific c# , asp.ne t, codeplex sdk dlls many spiggers public partial class facebook : system.web.ui.masterpage { protected facebookapp fbapp; protected canvasauthorizer authorizer; protected facebooksettings osettings = new facebooksettings(); protected override void oninit(eventargs e) { //not

Facebook - Music, Books, Interests.. are they all included in "Likes"? -

i trying retrieve list of users' interests. making calls graph api retrieve things books, music, etc. seems under "likes" includes listed under books, music, etc. exceptions, or can make 1 call retrieve likes? as can find on api documentation , "likes" retrieve "all pages user has liked". need permission user_likes. you need following request: https://graph.facebook.com/id/likes?access_token=token where id id of user , token token have received. it return array of json objects containing id, name, category , create_time fields. cheers

While using refinery ruby (Rack) application could not be started -

i installed new rails 3 application on ruby 1.9.2 first time using refinery cms. went using refinerycms install application, passenger having issues application. passenger says rack can not start gives me error: "no such middleware insert after: actiondispatch::static" i running several other rails applications on server using passenger without trouble; although none of applications using refinerycms. help appreciated project in class i'm taking , have limited time complete scope of project, awesome started. in config/environments/production.rb file have specify: config.serve_static_assets = true this enables actiondispatch::static , requirement of refinery cms.

php - Managing Joomla Website -

currently workflow this: make changes local copy of website use akeeba backup make copy of website , database delete contents of hosted server upload akeeba backup files visit website , run akeeba restore syncs database is there better way manage joomla website? problem is, have team working on 1 website doesn't work well. setting version control server won't work because pretty in joomla gets stored in database need somehow cvs work database. potentially if joomla , sqlite worked (they don't) cvs solution might work. write php script, doesn't doing difficult.

jQuery not parsing nested XML correctly -

i'm parsing data xml looks this: <departuresdata> <station> <id>29411</id> <name>kúpalisko matador</name> <distance>182</distance> <vehicle> <number>180</number> <time>10:26</time> <time>10:56</time> <target>holíčska</target> <lineid>289</lineid> <type>bus</type> </vehicle> <vehicle> <number>180</number> <time>10:17</time> <time>10:47</time> <target>cintorín petržalka</target> <lineid>288</lineid> <type>bus</type> </vehicle> </station> <station> <id>30122</id> <name>kúpalisko matador</name> <distance>201</distance> <vehicle> <number>80</number> <time>10:09</time> <time>10:

Display mysql results in one row -

mysql> select * facts; +----+---------+------------+---------+ | id | fact_id | fact_value | host_id | +----+---------+------------+---------+ | 1 | 1 | rh5 | 1 | | 2 | 1 | rh4 | 2 | | 3 | 2 | virtual | 1 | | 4 | 2 | virtual | 2 | | 5 | 3 | rack 2 | 1 | +----+---------+------------+---------+ mysql> select * hosts; +---------+-----------+ | host_id | host_name | +---------+-----------+ | 1 | bellagio | | 2 | mirage | +---------+-----------+ the query used following: mysql> select host_name,fact_value hosts left join facts b on > b.host_id=a.host_id , b.fact_id in (1,2,3); +-----------+------------+ | host_name | fact_value | +-----------+------------+ | bellagio | rh5 | | bellagio | virtual | | bellagio | rack 2 | | mirage | rh4 | | mirage | virtual | +-----------+------------+ i want results print 1 row each host, not

php - Access to array $this->session->array -

how can access array $this->session->userdata('auth') ? print_r() displays: array ( [ncli] => 0 [nomecli] => somename [nomcli1] => administrador [morcli] => company [nuser] => admin [pwdcli] => pwdadmin ) but can't use $this->session->userdata('auth')[ncli] ... put in variable: $data = $this->session->userdata('auth'); echo $data['ncli']; the reason why can't ()[] php doesn't support yet .

.net - When I set a variable to a new object, does the old value die? -

assume have variable, list(of t) , 100 elements instances of class.... if set variable new list(of t) 100 instances, old ones totally disappear, right? they...die. absolutely thing of past, right? assuming nothing else points 100 things, yes, eligible garbage collection.

swing - Button whith show counter and switch anoter frame after 60 second -

hello friends how create counter button in swing using code switch frame after 30 second not display 30 second so how ? thanks package javaapplication1; import java.awt.event.actionevent; import java.awt.event.actionlistener; import java.util.timertask; import java.util.timer; import javax.swing.jframe; import javax.swing.swingutilities; public class timerbutton extends jframe { timer timernew; javax.swing.timer timer; public timerbutton() { initcomponents(); } private timerbutton(int seconds){ initcomponents(); timernew = new timer(); timer = new javax.swing.timer(1000, new myactionlistener()); timer.setinitialdelay(0); timer.start(); timernew.schedule(new remindtask(), seconds*1000); system.out.println(timernew.tostring()); } class myactionlistener implements actionlistener { private int counter = 10; public void actionperformed(actionevent e) { coun