Posts

Showing posts from June, 2013

.net - How to truncate a file in c#? -

i writing actions done program in c# file using trace.writeln() function. file becoming large. how truncate file when grows 1mb? textwritertracelistener tracelistener = new textwritertracelistener(file.appendtext("audit.txt")); trace.listeners.add(tracelistener); trace.autoflush = true; what should added above block try play around filestream.setlength filestream filestream = new filestream(...); filestream.setlength(sizeinbytesnotchars);

How do i apply a link to a td element in rails? -

i have following: <td> <%= link_to simple_format(h(post.text)), post %> <%= time_ago_in_words(post.created_at) %> </td> in rails, how make entire td link post? if want make of text in cell clickable, this: <td> <%= link_to post %> <%= simple_format(h(post.text)) %> <%= time_ago_in_words(post.created_at) %> <% end %> </td> which wrap a tag around both of text bits. if want make entire td background clickable, can't wrap td a tag since html doesn't allow a child of tr , , behavior inconsistent across browsers. rails gladly (just put td inside link_to block), wouldn't behave way want to. you'd need different markup.

reflection - Trying to dynaimcally create properties at runtime with Python using reflected data -

so i'm trying figure out if want possible. writing test code application, , have objects contain properties representing of elements have in interface our product. want able pass in applciation runner , data object new class , have dynamically generate set of accessor properties based upon subset of properties in data object. idea far: create subclass of property includes metadata required extracting information interface refactor existing data objects use new property subclass relevant fields in ui create new generator class accepts ui driver object , data object reflects data object list of members of of new property subclass type stores information ui based upon metdadata in property subclass members of generator class instance (planning on using setattr) create properties @ run time make members created in (b) read-only , provide interface consistant existing code (ie using .[name] instead of .[name]() ) i think have figured out except step 3c. there way cr...

jQuery - how to write 'if not equal to' (opposite of ==) -

i need reverse of following code. how can make animation run if width not 500px. $(".image-div").not(this).each(function() { if ($(this).css('width') == '500px') { $(this).animate({ width: '250px' }, 500, function() { // animation complete. }); } }); in other words, opposite of this?: == thanks the opposite of == compare operator != .

php - How to do a multidimensional array within a while loop? -

im stuck simple problem in php: $words = array(); while ($allrow = mysqli_fetch_array($all)) { $words = "".utf8_encode($allrow["eng"])."" => "".$allrow["id"].""; } foreach ($words[] $key => $word) { i wanna have array words , id. in foreach loop need able know id each word has. you array building syntax off, try this: // array key id, swap if needed, assume ids unique $words[$allrow["id"]] = utf8_encode($allrow["eng"]); every time $words = $anything , overwriting last iteration. this should have generated parse error: ."" => "". not sure how slipped testing. no need empty "" strings either.

iphone - Open Link in UIWebview not UIShared Application -

i have been having rough time trying open links user clicks in simple web view instead of multitasking , going safari. quite pain users have leave app every time link clicked , know quite simple still having terrible time making happen. here code using still when link clicked opens safari. if can point me in right direction appreciative! thank you! - (void) handleurl:(nsurl*)url { [web loadrequest:[nsurlrequest requestwithurl:[nsurl urlwithstring:@"%@"]]]; } - (bool)webview:(uiwebview *)webview shouldstartloadwithrequest:(nsurlrequest *)request navigationtype:(uiwebviewnavigationtype)navigationtype { nslog(@"expected:%d, got:%d", uiwebviewnavigationtypelinkclicked, navigationtype); if (navigationtype == uiwebviewnavigationtypelinkclicked) { [uiapplication sharedapplication] ; return no; } if (navigationtype == uiwebviewnavigationtypelinkclicked) { [web loadrequest:[nsurlrequest requestwithurl:[ns...

iphone - In Xcode4, the new interface builder says "no selection" -

i using xcode 4.02 iphone programming. in new interface builder, when click button (or other gui-element) , go "attributes inspector" says "no selection". while thought solve problem saving nib-file, not work. how can solve problem? there seems bug in attributes inspector in xcode 4. when happens me this: switch (non ib) file in current tab launch new tab (cmd t) open original ib file in new tab the attributes inspector magically show in new tab.

nhibernate join criteria help -

i have table driverscans joins driverimages. want return driverscans driverimage has it's sent field equal false. essentially select driverscan.* driverscan inner join driverimages on driverimages.driverscanid = driverscan.driverscanid driverimages.sent = 0 the code below driverscans sql query created pulls inner join of driverscan , driverimages, includes image field. how write code sql returns driverscan info? public ienumerable<driverscan> getnewscans() { var session = getcleansession(); var query = session.createcriteria(typeof(driverscan)); query.createcriteria("driverimages", jointype.innerjoin) .add(cr.restrictions.eq("sent", false)); return query.list<driverscan>(); } if relevant mapping driverimages is hasmany<driverdoc>(x => x.driverdocs) .withkeycolumn("driverscanid").isinverse() .cascade.alldeleteorphan().lazyload(); do have use createcriteria? can pretty hql. al...

ruby - share code between a rails helper and a background worker -

i have code in rails helper being used in view , have same code in background worker class. how extract code out own class or module use both helper , background class? please can 1 help. to me, code needs shared between background tasks , rails goes logically in lib/my_library.rb . require 'my_library' in controller , job files. lib/my_library.rb: class mylibrary def self.do_something(foo) end end in app/jobs/my_job.rb: require 'my_library' # ... mylibrary.do_something( "x" )

xcode - How to make partly transparent png-image buttons for iPhone? -

my iphone app has custom buttons display png-images. replace white color in images transparent color. there tool on mac allows me that? (or there other way indicate color transparent in xcode?) the preview application has mode on select tool called "instant alpha" eases selection of backgrounds. once have background selected, can press "delete" key , area of image removed. save png "alpha" box checked , you're done. most other image editing tools, particularly supporting multiple layers in image, support png alpha channels. these easier using preview, third-party , many cost money need make decision. please note if starting image solid background things have faded edge blends in background, unlikely you'll able remove background entirely satisfaction without cutting in actual image. you may have seen gif images in past designed blend in on white background , had bright pixels @ edges stood out , ugly on darker backgrounds. i...

ASP.net How to hide a menu item from visitor? -

i want hide "admin panel" menu item visitor, without going role approach. <?xml version="1.0" encoding="utf-8" ?> <sitemap xmlns="http://schemas.microsoft.com/aspnet/sitemap-file-1.0" > <sitemapnode url="" title="nav" description=""> <sitemapnode url="~/default.aspx" title="home" description=""></sitemapnode> <sitemapnode url="~/about.aspx" title="about" description=""></sitemapnode> <sitemapnode url="" title="admin panel" description=""> <sitemapnode url="~/admin/addposts.aspx" title="add posts" description=""></sitemapnode> <sitemapnode url="~/admin/editposts.aspx" title="edit posts" description=""></sitemapnode> <sitemapnode...

Applying a discount code to a specific product in Shopify -

i've been working on setting shopify store. 1 major feature don't have built in being able provide discount specific product, though looks people have been requesting since 2008! does have idea how accomplished api? thanks! unfortunately, shopify api doesn’t offer product-specific discounts yet. it’s in pipe, feature not available yet.

types - Force Excel 2007 to treat all values in a column as text -

i have large column of data in excel. data should treated text, in cells excel "magically" changing data numeric. screwing vlookpup() functions in part of spreadsheet, , need override excel's automatic data type detection. if manually go through cells, , append ' each numeric cell, works. don't want hand several thousand cells. for example, works: manually type '209 and not work: manually type 209 , right click , format text. if changing format of column not option, it's helpful create column that's 'vlookup friendly' , leave main column alone. this trick i've used few times: say 'mixed' column column a. in column b, enter formula: =concatenate(a1) or jean-françois pointed out in comment, shorter version: =a1 & "" and drag down bottom row. column b strings. vlookup can use column b.

ios4 - iPhone: How to make a UITextField, UITextView uneditable when switching views -

i have 2 views - 1 table view , other detail view in iphone app. when row in table selected, detail view displayed. i using nib detail view editing record, adding new record displaying record. detail view has uitextfield , uitextview need made uneditable when displaying record. in didselectrowatindexpath method of tableview tried this... -(void)tableview:(uitableview *)tableview didselectrowatindexpath:(nsindexpath *)indexpath { // navigation logic may go here. create , push view controller. memodetailviewcontroller *memodetailviewcontroller = [[memodetailviewcontroller alloc] initwithnibname:@"memodetailviewcontroller" bundle:nil]; memodetailviewcontroller.memo = [self.resultscontroller objectatindexpath:indexpath]; // making text field , text view uneditable - did not work??? memodetailviewcontroller.memotitletext.enabled = no; memodetailviewcontroller.memotextview.editable = no; // pass selected object new view controller. [s...

windbg - Help me analyze dump file -

customers reporting problems every day on same hours. app running on 2 nodes. metastorm bpm platform , it's calling our code. in dumps noticed long running threads (~50 minutes) not in of them. administrators telling me before users report problems memory usage goes up. slows down point can't work , admins have restart platforms on both nodes. first thought deadlocks (long running threads) didn't manage confirm that. !syncblk isn't returning anything. looked @ memory usage. noticed lot of dynamic assemblies thought maybe assemblies leak. looks it's not that. have received dump day working fine , number of dynamic assemblies similar. maybe memory leak thought. cannot confirm that. !dumpheap -stat shows memory usage grows haven't found interesting !gcroot. there 1 thing don't know is. threadpool completion port. there's lot of them. maybe sth waiting on sth? here data can give far fit in post. suggest diagnose situation? users not reporting proble...

c++ - Is it possible to compile a VST on linux? -

for class project i'm attempting write vst plugin backed cuda. current cuda workflow on linux box, i'd prefer compile , link there. according wikipedia , should possible (i couldn't find steinberg documentation relevant linux) can't find makefile or instructions on how build if aren't using xcode or visual studio. i'm vst 3 sdk doesn't support linux. when try compile plugin under linux, error: ./base/source/fatomic.cpp:39:30: fatal error: libkern/osatomic.h: no such file or directory this issue caused following code in "vst3 sdk/base/source/fatomic.cpp" #if mac #include <libkern/osatomic.h> #if mac_os_x_version_min_required > mac_os_x_version_10_4 #define native_atomic_type (volatile int32_t*) #else #define native_atomic_type (int32_t*) #endif #elif windows #include <windows.h> #endif but hope compiling under linux work vst sdk 2.4. reading. jvstwrapper seems run on lin...

ruby on rails - Trouble on `validates_inclusion_of` using radio buttons -

i using ruby on rails 3.0.7 , have problem on using validates_inclusion_of method. i model file have: class user < activerecord::base inclusion_values = ['beautiful', 'ugly', 'good', 'bad'] validates :test, :inclusion => { :in => user::inclusion_values } end in view file have <%= form_for(@user) |f| %> <% user::inclusion_values.each |test| %> <%= f.radio_button :test, test %> <% end %> <% end %> the above "view" code generate this: <input type="radio" value="beautiful" name="user[test]" id="user_test_beautiful"> <input type="radio" value="ugly" name="user[test]" id="user_test_ugly"> <input type="radio" value="good" name="user[test]" id="user_test_good"> <input type="radio" value="bad" name="user[te...

html - Shifting focus in JQuery not working -

<input type="text" id="title" value="write post..." /> <input type="button" id="save_post" class="button" value="submit" style="cursor:pointer;"/> so binded enter key on keyboard something, here is: $(document).keypress(function(e){ if (e.which == 13){ $("#save_post").click(); $("#save_post").focus(); } }); problem is, want shift focus if clicking button, takes focus away text field (in have character counter for), , takes cursor out of text field, isn't working. cursor stays in field , character counter still counts submitted though nothing in textbox anymore. what doing wrong? the following worked me: /* cache reference save_post since use more once */ var $btn_savepost = $("#save_post"); /* make sure know when our button hit */ $btn_savepost.click(function(){ alert("clicked me");...

ruby - Set rvm default interpreter in user's .rvmrc? -

i'm curious if it's possible set default ruby interpreter within $home/.rvmrc file (i.e. equivalent of rvm --default use 1.9.2 ). i tried setting rvm_ruby_interpreter , rvm_ruby_version , no luck. just cleaning out unanswered questions... ended taking phrogz's suggestion , adding .zprofile : rvm_default=ruby-1.9.3-p194@home if [ -x ~/.rvm/bin/rvm-prompt ] && [ "$(~/.rvm/bin/rvm-prompt)" != $rvm_default ] ; rvm use $rvm_default fi looking it's kind of weird question, due fact new rvm , relatively new ruby (but familiar unix , dotfiles).

io - ReadFile() indicating EOF when file system says otherwise -

i've application running on windows ce 6.0 we'll call "foo" logging error , status messages "foo.log". i've second application we'll call "bar" should open foo.log reading, seek end of file, make foo write output log, output. the problem ... bar doesn't find new output foo has logged, though file viewer indicates file's size has changed. calling readfile bar on opened handle returns 0 bytes when else tells me there should @ least 8k. missing something?

PHP closure scope problem -

apparently $pid out of scope here. shouldn't "closed" in function? i'm sure how closures work in javascript example. according articles php closures broken , cannot access this ? so how can $pid accessed closure function? class myclass { static function gethdvdscol($pid) { $col = new pointcolumn(); $col->key = $pid; $col->parser = function($row) { print $pid; // undefined variable: pid }; return $col; } } $func = myclass::gethdvdscol(45); call_user_func($func, $row); edit have gotten around use: $col->parser = function($row) use($pid) . feel ugly. you need specify variables should closed in way: function($row) use ($pid) { ... }

ruby on rails - How parse the data from TXT file with tab separator? -

Image
i using ruby 1.8.7 , rails 2.3.8. want parse data txt dump file separated tab. in txt dump contain css property has invalid data. when run code using fastercsv gem fastercsv.foreach(txt_file, :quote_char => '"',:col_sep =>'\t', :row_sep =>:auto, :headers => :first_row) |row| col= row.to_s.split(/\t/) puts col[15] end the error written in console "illegal quoting on line 38." can 1 suggest me how skip row has invalid data , proceed data load process of remaining rows? here's 1 way it. go lower level, using shift parse each row , silent malformedcsverror exception, continuing next iteration. problem loop doesn't nice. if can improve this, you're welcome edit code. fastercsv.open(filename, :quote_char => '"', :col_sep => "\t", :headers => true) |csv| row = true while row begin row = csv.shift break unless row # things row here... rescue f...

c# - How to download/open the file that I retrive by server path? -

i making module shows tree view of documents stores on drive in folder. retrieving well. problem documents in different format like(.pdf, .docx etc). not opening in browser on click. there shows 404.4 error. tell me how can download/open different format files through button click? following code: protected void page_load(system.object sender, system.eventargs e) { try { if (!page.ispostback) { if (settings["directorypath"] != null) { binddirectory(settings["directorypath"].tostring()); } else { binddirectory(server.mappath("~/")); } } } catch (directorynotfoundexception dnex) { try { system.io.directory.createdirectory("xibdir"); binddirectory(server.mappath("xibdi...

Is there any way to list out the applications installed in iphone -

my requirements want enterprise application need list installed apps in iphone , should allow user delete apps current application. that's not possible without jailbreak. all apps sandboxed can't see outside folder.

objective c - How to get global screen coordinates of currently selected text via Accessibility APIs. -

Image
i need find out, how dictionary app showing following popup dialog selected text on pressing cmd+ctrl+d on application. want implement same kind of functionality cocoa app, app run in background , showing suggestions on hot key press selected text. i have implemented hot key capturing, need have code rectangle area of selected text on screen, can show dialog dictionary app. thanks you can use accessibility apis that. make sure "enable access assistive devices" setting checked (in system preferences / universal access). the following code snippet determine bounds (in screen coordinates) of selected text in applications. unfortunately, doesn't work in mail , safari, because use private accessibility attributes. it's possible work there well, requires more work , possibly private api calls. axuielementref systemwideelement = axuielementcreatesystemwide(); axuielementref focussedelement = null; axerror error = axuielementcopyattributevalue(systemwid...

java - XSSF Apache POI -

i used below setting default column style in xssf sheet? not working can suggest bug fix. format = workbook.createdataformat(); style = workbook.createcellstyle(); style.setdataformat(format.getformat("@")); sheet.setdefaultcolumnstyle(1, style); probably this bug causing headaches. trying code apache poi 3.7 added effect second column gets hidden (width = 0) , format not applied. cheers, wim ps note talk second column, code referring to; if wanted apply style first column should have used 0 (zero-based).

ruby on rails - sharing constant between models -

i want have constat defined in 2 models, don't want repeat code. i've placed constant in config/application.rb . practice? there better way that? a better place declare application constants in .rb file in config/initializers folder. declaring constant in initializer (or have done in config/application.rb) makes available in models/controllers/views in application.

Vim - if/elseif/else statements in for loop (command mode) -

i'm trying generate bunch of text in vim (command mode) using loops, e.g. :for in range(1,10) | put=i | endfor this outputs 12345678910 i want add logic inside of loop following pseudo code: :for in range(1,10) | if i>5 put=i endif | endfor my issue that, after exhausting google searches, unable find proper syntax producing kind of if statement. know how perform if , elseif and/or else statements in vim's command mode? edit: found vimscript so have: func! test() in range(1,10) j in range(1,10) if i<10 echo i*j endif endfor endfor endfunction so can :call test() which outputs 12345678910 , doesn't insert page.. every if/elseif/else/endif command on own, on 1 line be: :for in range(1,10) | if > 5 | put =i | endif | endfor

Can't get Android ApiDemos to work in Eclipse -

i feel bit stupid since develop android apps while now. problem can't apidemos work eclipse. please have @ screenshot of errors in eclipse: http://cheat-database.com/android.png it looks can't find xml files in apidemos project. although looks fine me. suggestions might doing wrong? other (own) android applications work fine in eclipse. lot help. the r.java automatically generated file. updated/re-generated whenever layout files, etc changed. i'm going assume tried set project directly samples. i've seen cause issues write access if don't have privileges, , doesn't seem play nice when try either. one thing try copying relevant apidemos folder alternate location , try creating new android project folder follows: create -> new android project -> create project existing source then point location , select relevant sdk. it's not ideal, @ least might application generating , running possibly.

Add 3rd party library to an eclipse plugin -

what right way include additional jar file in eclipse plugin? own plugin requires apache-commons-io. copied jar plugins directory , added via "dependencies" tab of plugin manifest. works me, other users of plugins have download commons-io manually. what correct way package commons-io in plugin? i use following strategy: if can find jar in question packaged bundle - i.e. manifest.mf contains correct entries - use this. have @ orbit project set of pre-packaged bundles of sorts. org.apache.commons.io here... if not possible, include jar in bundle, , updates manifest.mf - e.g. bundle-classpath: library.jar,.

php - Can't write the content to a file using rpc xml -

i have content want write file called bk_strategy-ptr-to-real-file.h . here code: echo $content = $header.$parameters.$footer; $myfile = "/home/vikas/hft/common/internal/config/trader/master/bk_strategy-ptr-to-real-file.h"; $fh = fopen($myfile, 'w') or die("can't open file"); fwrite($fh, $content); fclose($fh); is possible write file using xml rpc? you don't write files using xml-rpc, communications protocol. use php or asp write files. have fine: $myfile = "/home/vikas/hft/common/internal/config/trader/master/bk_strategy-ptr-to-real-file.h"; $fh = fopen($myfile, 'w') or die("can't open file"); fwrite($fh, $content); fclose($fh); but why file .h extension, should not .xml, or maybe .txt or .php depending on want response next.

Facebook like button "breaks" when logged in as page -

i have facebook 'like' button on page , it's working fine. when visitor logged in 'page' @ facebook includes photo , breaks design. guess because pages aren't allowed things. i pretty have iframe this: http://developers.facebook.com/docs/reference/plugins/like-box/ any ideas of how rid of image? way alter design, disable "feature" or check if user logged in page (to hide whole thing)? thanks edit: screenshot of issue: i.imgur.com/gla7q.png in top 1 i'm logged in regular user , bottom i'm "using facebook page" the code i'm using: <iframe class="facebook" src="http://www.facebook.com/plugins/like.php?href=<?=urlencode('http://www.mysite.com')?>&amp;layout=standard&amp;show_faces=false&amp;width=210&amp;action=like&amp;colorscheme=light&amp;height=45" scrolling="no" frameborder="0" allowtransparency="true"></iframe> ...

c# - Reflection in Objective C -

i on ipad , make reflection, in order methods names. methods remote windows application, developed in c#. problem c# methods' name doesn't give clue on arguments needs. know how method names , argument needs (or information on them) reflection ? edit : c# application running on remote windows machine. connect through bonjour protocol. manage send tuio events : can manipulate remote c# application ipad. moreover, through bonjour established streaming of remote application can see directly doing on ipad (the ipad becomes sort of multitouch remote control). unfortunately screen size of ipad bit small compare screen size of remote computer, precision not good. why incorporate menues on ipad app, these menues (possible actions) must coincide remote app menues. therefore, want methods of remote app. once again there : in c# definition of override methods different objective c. in c#, difference number of arguments passed on method (and not name of method). finally, why need me...

iphone - When we need Pointer of BOOL Variable in Objective C? -

in case need pointer of bool variable in objective c language? i have code collapsible uitableview in there function declaration: - (void)toggle:(bool*)isexpanded section:(nsinteger)section; and definition is: - (void)toggle:(bool*)isexpanded section:(nsinteger)section { *isexpanded = !*isexpanded; nsarray *paths = [self indexpathsinsection:section]; if (!*isexpanded) { [self.tableview deleterowsatindexpaths:paths withrowanimation:uitableviewrowanimationfade]; } else { [self.tableview insertrowsatindexpaths:paths withrowanimation:uitableviewrowanimationfade]; } *isexpanded = !*isexpanded; meaning of statement have never used kind of statement in case of bool variable. following other 2 functions of same code called in sequence of above function: - (nsarray*)indexpathsinsection:(nsinteger)section { nsmutablearray *paths = [nsmutablearray array]; nsinteger row; ( row = 0; row < [self numberofrowsinsection...

Looking for a pragmatic XML-Document Builder Design -

we have create numerous xml-documents, satisfying huge xml-schema. documents vary in size , structure. basic documents contain 10 elements there complex documents hundreds of elements, repetition, optional branches, etc. looking way design lightweight abstraction building documents , filling data business models. abstraction not need validate resulting document , not need assert invariants. is there basic technology, xslt, helps creating documents? not able spend lot of time build full fleged oo-abstraction/builder, looking pragmatic, least effort solution aid in constructing these documents. general ideas welcomed. our environment supports full oop no fp :/ may lightweight markup/template engine yaml or haml may useful purposes? there lots of implementations in many programming languages them , many text editors support highlightning syntax.

Android:notification problem -

i have application clear missed calls displayed on status bar. can clear when restart phone, missed calls on status bar still there? how can permanently remove using app? you cannot affect other applications' notifications in android.

c - drawing graphs in ubuntu -

i have c code collects data , places them in 2-d array. plot data on x-y graph (mathematics) automatically i.e. pass data parameters in command line , graph are there suggestions how so? gnuplot need. if want process data before, might want try octave , aims matlab equivalen (still uses gnuplot frontend graphing). if want more control, write script in python , use matplotlib .

What kind of escaping for java applet parameters? -

suppose want embed arbitrary characters in applet parameter tag. might chinese. might string embedder single or double quotes i've found no statement how should done. <param name='foo' value='this \"a string quotes\"'> would first guess, seems not enough. the strings defined in param tag interpreted browser , passed on java runtime. java not modify them in way. so param tag obeys standard rules html: in attributes, can use character valid in html attributes; escaping them, can use standard html entities : <param name="foo" value='this "a string quotes"'> <param name="bar" value="this &quot;another string quotes&quot;"> <param name="baz" value="using both double quotes: &quot &amp; single quotes &#39;, literal 文字 characters">

c# - Trapping a key press -

i using turotial here http://blogs.msdn.com/b/toub/archive/2006/05/03/589423.aspx this traps key press , prints console. have idea on how make work control , key, ctrl + w ? if guidance please or suggest need research find out? thanks system.windows.forms.control.modifierkeys should trick, telling whether shift, alt, and/or control pressed. for example; if (keys.w == (keys)vkcode && keys.control == control.modifierkeys) should check ^w combination, according link.

testing - Unit or integration test resource file directory layout -

what common approaches unit or integration test resource directory's nested layout? example, if code, tests, resources strucured in java project main/ java/ com/ example/ class.java test/ java/ com/ example/ classtest.java resources/ what approachs storing resource files test? in extremely simple case store file e.g. test/resources/a.xml , when have multiple tests each test has source , expected output files, doesn't work. example of solution be test/ resources/ com/ example/ classtest/ src/ a.xml b.xml exp/ a.xml b.xml are there common approaches structuring multiple resource files multiple tests. honestly there many ways of doing things there developers. realistically, think abou next developer - or else 6 months or 2 years now. able understand relationships between files , code. able add new tests, maintain old, etc. conv...

google app engine - Refreshing the token with the GAE channel API -

i'm building simple chat application google app engine (python) , channel api. when user logs on application, token issued them , added list in datastore. however, token expires after 2 hours (and there other kinds of errors occur). @ time onclose or onerror handler triggered in javascript , intent send ajax message tell server remove old token datastore , create new token reopen channel, sent ajax response. resend message every few seconds until ajax receives response. this works fine when test locally, when deploy application internet, works (maybe 5% of time). can suggest if there's better way i'm trying do, or can offer advice why method working inconsistently? seems though ajax message failing reach server entirely, strange because other ajax based functionality on page appears work fine.

iphone - iOS correct way (memory management) for a method to return a value -

if have class named foo , have function + getids should return ids. correct signature of + getids this: + (nsarray *)getids { nsmutablearray *ids = [[[nsmutablearray alloc] init] autorelease]; return ids; } what i'm wondering if should use autorelease on *ids ? there no other way assume? can't [ids release] after return statement right? you can send autorelease message along alloc, init messages. can do, return [ids autorelease]; note: should not both @ same time ;-) you can not return [id release] , because release method returns nothing.

c# - Will SecureString give me any advantage when it comes to MSIL decompilation? -

is in way better this char[] sec = { 'a', 'b', 'c'}; securestring s = new securestring(); foreach (char c in sec) { s.appendchar(c); } intptr pointername = system.runtime.interopservices.marshal.securestringtobstr(s); string secret = system.runtime.interopservices.marshal.ptrtostringbstr(pointername); than this string secret = "abc"; or this char[] sec = { 'a', 'b', 'c'}; string secret = new secret(sec); if want protect "abc" beeing detected in decompiled msil code? securestring protect string once in memory, string compiled msil still there in plain. if need hide sensitify information conside encrypted app.config described here: http://weblogs.asp.net/jgalloway/archive/2008/04/13/encrypting-passwords-in-a-net-app-config-file.aspx hth dominik

android - wrap_content for a listview's width -

is there way have listview with equal longest row? setting wrap_content listview 's width has no effect. listview covers whole screen horizontally. this activity layout <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"> <listview android:id="@+id/listview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/country_picker_bg" /> and row xml <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" > <linearlayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_vertical" ...

jquery - Simple onkeydown + length count -

i have simple function here: $('#input').keydown( function(e) { if( $(this).length === 8 ) { alert('we have winner!'); } else { return false; } }); it not work. why? appreciated. live example assuming want check length of value of #input , want: $(this).val().length instead of $(this).length . may want rid of return false; prevent being entered input field. see updated fiddle here . on separate note, work when there 8 characters in field, , key pressed. may way intended it, think may want keyup event instead.

problem with drawing circle in android using OpenGL -

i want draw circle in android using opengl on every mouse button click. how can this? start triangle . try render square. move pentagon. repeat until looks circle. for catching mouse events start here .

xml - Select elements with unique values -

i'm trying parse openoffice spreadsheet obtain rows unique values in first column. i.e., retrieve following xml fragment <table:table-row> elements unique <text:p> values in first child <table:table-cell> . <table:table table:name="foo"> <table:table-row> <table:table-cell> <text:p>1</text:p> </table:table-cell> <table:table-cell> <text:p>foo</text:p> </table:table-cell> </table:table-row> <table:table-row> <table:table-cell> <text:p>2</text:p> </table:table-cell> <table:table-cell> <text:p>bar</text:p> </table:table-cell> </table:table-row> <table:table-row> <table:table-cell> ...

javascript - Document.ready in external files? -

i referencing javascript follows on html page: <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script> <script type="text/javascript" src="http://code.jquery.com/mobile/1.0b1/jquery.mobile-1.0b1.min.js"></script> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&amp;region=gb"></script> <script type="text/javascript" src="js/shared.js"></script> <script type="text/javascript"> $('document').ready(function() { // in-page code: call functions in shared.js }); </script> the functions defined in shared.js not wrapped inside $('document').ready . so: is safe assume functions defined in shared.js available "in-page code"? if pull out in-page code separate file called local.js (keeping wrapped in $('document').ready ), s...

CakePHP encoding problem : storing uppercase S with caron on top, saves in the database but causes errors while processed by cake -

so working in site sores cuneiform tablets info. use semitic chars transliteration. in script, create term list translittaration of tablet. my problem Å , script created 2 different terms because thinks there space in word because of way cake treats special char. exemple : partial contents of tablet : utu-diÅ -nu-il2 terms tablet when treated script : utu-diÅ , -nu-il2 it should : utu-diÅ -nu-il2 when print contents of array in course of treatment of contents, see : utu-di� -nu-il2 so means uncorrect parsing of text creates space interpreted in script 2 words instead of one. in database, text fine... i these errors : warning (512): sql error: 1366: incorrect string value: '\xc5' column 'term' @ row 1 [core\cake\libs\model\datasources\dbo_source.php, line 684] query: insert terms ( term , lft , rght ) values ('utu-di�', 449, 450) query: insert terms ( term , lft , rght ) values ('a�...

sql server - sql subtract dates -

some of dates in column of dates recorded wrong. i'd make query subtracts 1 day each date if days in date range. i know i'll have use dateadd , update, can't seem figure out. in advance. this should it: update [sometable] set [datecolumn] = dateadd(d, -1, [datecolumn]) [datecolumn] between [date1] , [date2] here's msdn doc's on dateadd function: http://msdn.microsoft.com/en-us/library/ms186819.aspx when performing updates on data this, it's best run select statement first same criteria ensure you're updating correct records. helps reduce stress level of updating (especially if you're unfamiliar sql). select *, --depending on columns see, wildcard replaced dateadd(d, -1, [datecolumn]) proposeddate [sometable] [datecolumn] between [date1] , [date2]

session - Incrementing Oracle Sequence by certain amount -

i programming windows application (in qt 4.6) - @ point - inserts number of datasets between 1 , around 76000 oracle (10.2) table. application has retrieve primary keys, or @ least primary key range, sequence. store ids in list used batch execution of prepared query. (note: triggers shall not used, , sequence used other tasks well) in order avoid calling sequence x times, increment sequence x instead. what have found out far, following code possible in procedure: alter sequence my_sequence increment x; select my_sequence.curval + 1, my_sequence.nextval v_first_number, v_last_number dual; alter sequence my_sequence increment 1; i have 2 major concerns though: i have read alter sequence produces implicit commit. mean transaction started windows application commited? if so, can somehow avoid it? is concept multi-user proof? or following thing happen: sequence @ 10,000 session sets increment 2,000 session selects 10,001 first , 12,000 last session b sets increment...

python - Navigate manually with a cursor through nested lists by only providing "left()" and "right()" as commands? -

eventhough write in python think abstract concept more interesting me , others. pseudocode please if :) i have list items 1 of classes. lets strings , numbers here, doesn't matter. nested depth. (its not list container class based on list.) example : [1, 2, 3, ['a', 'b', 'c'] 4 ['d', 'e', [100, 200, 300]] 5, ['a', 'b', 'c'], 6] note both ['a', 'b', 'c'] same container. if change 1 change other. containers , items can edited, items inserted , important containers can used multiple times. avoid redundancy not possible flatten list (i think!) because loose ability insert items in 1 container , automatically appears in other containers. the problem: frontend (just commandline python "cmd" module) want navigate through structure cursor points current item can read or edited. cursor can go left , right (users point of view) , should behave list not nested list flat one. for h...

gridview does not bind datatable copy in C# -

i trying bind copy of datatable gridview, not display it. here sample code: var clonedata = originaldata.clone(); gvtable.datasource = clonedata; gvtable.databind(); if bind originaldata instead of clonedata, works.. what's wrong copy? asp.net c#. you need use copy() instead of clone() both copy , clone methods create new datatable same structure original datatable. new datatable created copy method has same set of datarows original table, new datatable created clone method not contain datarows. source

asp.net - Make Cache object expire at midnight -

i have following code: var templist = new brandcollection(); if (httpcontext.current.cache["cacheddevicelist"] == null) { templist = provider.getdevicedata(info); httpcontext.current.cache.insert(...); } else { templist = } cache.insert() method overloaded can set dependencies, sliding , absolute expiration. want make cache expire @ midnight. how do that? thank in advance! absolute expiration way - it's shorthand 'this expires @ absolute point in time' opposed 'in twenty minutes now'. when put item cache, need calculate when midnight , use expiration point e.g. var templist = new brandcollection(); if (httpcontext.current.cache["cacheddevicelist"] == null) { templist = provider.getdevicedata(info); // find out when midnight taking today , adding day datetime expirationtime = datetime.today.ad...

How to restart AsteriskWin32 via CLI Command? -

when used "reload" command, didn't reloading module asterisk start beginning. so, when used "reload" command, couldn't register sip client application. there command more restart asterisk? restart now should work you. if have concerns specific module, can try following: module load name_of_module.so module unload name_of_module.so

I unable to get child control from ListBox control in WPF using MVVM -

i in serious trouble. have listbox control in have many combo box. whenever select value in combo box, have make other controls hidden. using mvvm pattren. unable child controls listbox control can listbox control in viewmodel. how can these controls in viewmodel? possible? using framework 4.0. have shown code below write in view. <listbox x:name="lstitems" maxheight="300" fontsize="11" margin="12,0,20,38" itemssource="{binding source={staticresource listedview}, path=myitemssource, updatesourcetrigger=propertychanged, mode=twoway}"> <listbox.itemtemplate > <datatemplate> <border borderbrush="blue" margin="0,4,0,4" borderthickness="1" cornerradius="5"> <stackpanel orientation="horizontal"> <label content="show rules where:" name="lblshowrules">...

html - Links don't work in PISA -

here part of html: <h5 id="my-header">header header</h5> ... other stuff ... <a href="#my-header">go there!</a> i process using pisa: %pisa_bin% -s --encoding utf-8 %title%.html %title%.pdf in resulting pdf, link not working: it's shown in underlined blue usual link, when click on nothing happens. tested adobe reader, foxit reader , chrome embedded browser. also, in resulting html link works expected. what's wrong?

c# - Problem with Index of in Substring array -

profilepagelist string array each string containing pageid, pagename , pagecontent separated group of characters (#$%). asp.net application using c# foreach (string item in profilepagelist) { string pagecontent = ""; string pagename = ""; string pageid = ""; *** > part wrong. me here *** pageid = item.substring(0, item.indexof('#$%') + 2); pagecontent = item.substring(item.indexof('#$%') + 1); pagename = item.substring(0, item.indexof('#$%')); callsomefunction(pageid , pagename, pagecontent); } input string helloo#$%<p>how you??</p>#$%74396 i dont understand how use substring. can me please!! lot in advance.. have @ these: http://msdn.microsoft.com/en-us/library/system.string.substring(v=vs.71).aspx and http://csharp.net-informations.com/string/csharp-string...

Using mvc-mini-profiler database profiling with Entity Framework Code First -

Image
i'm using mvc-mini-profiler in project built asp.net mvc 3 , entity framework code-first. everything works great until attempt add database profiling wrapping connection in profileddbconnection described in documentation. since i'm using dbcontext, way attempting provide connection through constructor using static factory method: public class mydbcontext : dbcontext { public mydbcontext() : base(getprofilerconnection(), true) { } private static dbconnection getprofilerconnection() { // code below errors //return profileddbconnection.get(new sqlconnection(configurationmanager.connectionstrings["myconnectionname"].connectionstring)); // code below works fine... return new sqlconnection(configurationmanager.connectionstrings["myconnectionname"].connectionstring); } //... } when using profileddbconnection , following error: providerincompatibleexception: provider did not ret...

asp.net - Detect culture of number in VB.Net i.e. period or comma for decimal point / thousands separator -

in vb.net, there way of auto-detecting culture of string representation of number? i'll explain situation: our asp.net web site receives xml data feeds boat data. of time, number format prices use either simple non-formatted integer e.g. "999000". that's easy process. occaisionally, there commas thousands separators , periods decimal point. also, that's fine our data import understands this. example "999,000.00". we're starting data france of prices have been entered periods , thousands separators other way around that's way it's done in many european countries. e.g. "999.000,00". our system interpret 9 hundred , ninety 9 pounds instead of 9 hundred , ninety 9 thousand pounds intended. unfortunately, data feed contains prices in mixture of formats without culture indicator on each one. know of in-built .net functions auto-detect culture of string number based on period , comma are? there no built-in way determin...

windows xp - How to get socket information previously passed to a bind() call? -

winsock 2, windows xp sp3. i have socket, passed bind() function, want information socket. more specifically, want port number socket bound to. have socket instance. how go doing this? socket udp way. my purpose want create new raw udp socket , build ip header , udp header , tunnel information through raw socket instead, don't know put source port because don't know bound to. getsockname() should you.

Is it possible to hack GTK to render to OpenGL texture -

i'm writing opengl game, , want native looking gui elements. wondering if has hacked gtk+ using gtkoffscreenwindow , gtk_offscreen_window_get_pixbuf render opengl texture, , whether have reasonable performance, considering repeated re-uploading of texture data every time gui updated while possible, i'd instead use real opengl widget toolkit clutter. if want render gtk+ opengl, i'd start creating new gdk backend (x11/opengl or that), (re-)implements gdk drawing functions using opengl. nice side effect be, gtk+ windows allow ordinary opengl rendering, too, i.e. no more need gtkglwidget class.

c - error: "_structName" has already been declared in the current scope -

i running "already declared" compilation error when building program. know can caused including same header file twice. however, using ifndef preprocessor directive avoid such scenario. seems struct must declared in header file somewhere else in build path. there way figure out struct declared? (in root of build path) linux: find . | xargs grep name_of_your_struct windows (i not 100% on syntax, here, believe correct. try findstr /? if doesn't work.) findstr /s "name_of_your_struct"`

c# - SQL Update - Not updating multiple rows in a for loop -

i have datagridview(dgv) linked sqlite database. want update info on dgv. so, have context menu lets me change 1 column , update db well. want have ability select multiple rows , edit well. ex: if select 5 rows , change type alarms errors ; change reflected in dgv , when database , change isnt reflected. 1 row updated. my code snippet below foreach (datagridviewrow r in datagridview1.selectedrows) { sqlitetransaction sqlitetrans = connection.begintransaction(); sqlitecommand cmd = connection.createcommand(); messagebox.show(r.tostring()); if (r.cells["typedatagridviewtextboxcolumn"].value.tostring().contains("#") == false) { r.cells["typedatagridviewtextboxcolumn"].value = r.cells["typedatagridviewtextboxcolumn"].value.tostring() + " # " + max; } else { r.cells["typedatagridviewtextboxcolum...