Posts

Showing posts from August, 2012

How can I convert this XOR-encryption function from Delphi to C#? -

the following delphi routine long-ago compuserve posting, , used encrypt various information in our database. below both delphi 2007 , (thanks unicode differences) delphi xe versions. we have been trying convert c#, , have gotten close-ish, we're missing somewhere. unfortunately, our delphi guy (me) doesn't know c#, , c# guy new delphi. c# doesn't (appear to) have concept of ansistring, solution involve byte or char arrays? we'd appreciate in converting c#. delphi 2007 version (ascii) function encodedecode(str: string): string; const hash: string = '^%12hdvjed1~~#29afdmsd`6zvuy@hbkdbc3fn7y7euf|r7934093*7a-|- q`'; var i: integer; begin := 1 length (str) str[i] := chr (ord (str[i]) xor not (ord (hash[i mod length (hash) + 1]))); result := str; end; delphi xe version (unicode) function tfrmmain.encodedecode(str: ansistring): ansistring; const hash: string = '^%12hdvjed1~~#29afdmsd`6zvuy@hbkdbc3fn7y7euf|r7934093*7a-|- q`'; var

Linq to XML, C# -

i have xml in xdocument object (linq xml). need add namespace each xelement/node in xdocument. i dont want add in below way. beceause have xml in xdoc. xdocument xdoc = new xdocument( new xelement(ns + "root", new xelement(ns + "person", new xattribute("id", 1), new xelement(ns + "firstname", "jack"), below format have <root> <person>1</person> <firstname>jack</firstname> </root> i want convert below format <emp:root> <emp:person>1</emp:person> <emp:firstname>jack</emp:firstname> </emp:root> foreach (var node in xdoc.descendants()) { node.name = ns + node.name.localname; } that should work: side note namespace appear on root node.

vb.net - Get Result in Next Row in a DataGridView -

i have single row in datagridview shows different results selected oids..the problem next result replaces first 1 in same row..is there way next result in next rows datagridview can show previous results also..my datagrid not bound data source. private sub button1_click(byval sender system.object, byval e system.eventargs) handles button1.click dim host string dim community string host = datagridview1.rows(0).cells(1).value.tostring community = datagridview1.rows(3).cells(1).value.tostring dim txt4b new datagridviewtextboxcell() txt4b.value = "public" dim result dictionary(of oid, asntype) dim requestoid() string = nothing dim snmp new simplesnmp snmp = new simplesnmp(datagridview1.rows(0).cells(1).value.tostring, datagridview1.rows(3).cells(1).value.tostring) result = snmp.get(snmpversion.ver1, new string() {datagridview1.rows(1).cells(1).value.tostring()}) if not snmp.valid messagebox.show("invali

cocoa - first mac app - push viewcontroller -

i have question, iphone application , want little mac application. from clean application add button on mainmenu xib, add nsviewcontroller mainmenu (from ib) 1 action. create new nsviewcontroller (firstviewcontroller) nib file , button. want create function push firstcontroller mainmenu , simple function push mainmenu firstcontroller. something this viewcontroller = [[viewcontroller alloc] initwithnibname:@"viewcontroller" bundle:[nsbundle mainbundle]]; [self.navigationcontroller pushviewcontroller: viewcontroller animated:yes]; how can it??? i think you're trying bring ios-style interface macos x, , won't work in many cases. macos x user interface different of ios. ios apps limited single (and small) window, , users 1 thing @ time. navigation interface standardizes way users drill down through different parts of task journey predictable. interface modal in sense user navigating between different parts of app, , user actions linked part of app t

Store plus and minus in a variable PHP -

how can solve problem: if ($variable == 1) { $math = "-"; } else { $math = "+"; } $numberone = 10; $numbertwo = 10; $result = $numberone $math $numbertwo; this doesn´t work, there way solve this? this work example. subtraction same adding negative. far safer alternative of using eval . if ($variable == 1) { $modifier = -1; } else { $modifier = 1; } $numberone = 10; $numbertwo = 10; $result = $numberone + ($numbertwo * $modifier);

crash - Eclipse(CDT) crashes on Ctrl-clicking in Ubuntu -

i relatively new eclipse , trying browse thru existing c++ project created. every time try & use ctrl-click on function invocation - instead of taking me declaration (or definition?), eclipse crashes. i running eclipse 3.2 on 64-bit ubuntu. tried setting -xx:-usecompressedoops in ~/.eclipse/eclipserc suggested here , resulted in: /home/dp/.eclipse/eclipserc: line 1: -xx:-usecompressedoops: command not found any suggestions appreciated! tia. note: btw, didn't find eclipserc file in ~/.eclipse, created new 1 1 line in it(being -xx:-usecompressedoops ). i upgraded eclipse 3.7.0 , problem resolved. helpful suggestions, though.

Ruby kind_of? and is_a? returning false for a subclass -

i'm trying take advantage of ruby methods kind_of? , is_a? . understand synonyms of 1 another. i have object of class child . call child.ancestors gives array list [child, #<module>, parent, ...] . call child.new.is_a?(parent) or child.new.kind_of?(parent) returns false. calling child.ancestors[2].new.is_a?(parent) returns false. can't seem figure out why considering calling parent.new.is_a?(parent) returns true should. these classes descend activeresource::base if has it. class parent < activerecord::base include mymodule def self.my_method(obj) if obj.is_a?(parent) puts 'hello' end end end class child < parent def my_method self.class.my_method(self) end end = child.new a.my_method class parent def self.my_method(obj) if obj.is_a?(parent) puts 'is parent' else puts 'is not parent' end end end class child < parent def my_method self.class.my

Go map of functions -

i have go program has function defined. have map should have key each function. how can that? i have tried this, doesn't work. func a(param string) { } m := map[string] func { 'a_func': a, } key, value := range m { if key == 'a_func' { value(param) } } are trying this? i've revised example use varying types , numbers of function parameters. package main import "fmt" func f(p string) { fmt.println("function f parameter:", p) } func g(p string, q int) { fmt.println("function g parameters:", p, q) } func main() { m := map[string]interface{}{ "f": f, "g": g, } k, v := range m { switch k { case "f": v.(func(string))("astring") case "g": v.(func(string, int))("astring", 42) } } }

gwt - Realizing the design from a design professional in code -

i typically work on web apps used small group of well-controlled people, find i'm writing has potential used large population. means design , "look" important success. while can code functional, ain't gonna pretty, know i'll need outside designer make things good. never having worked way before had few questions mechanics of how happens , how try make things easier. we java, when building rich interface, use gwt. know when working designers, typically provide images of interface should without type of "useable" output. question how best bridge gap between simple drawing of interface functional realized one. any thoughts appreciated. well, "it depends", always. nowadays, don't think can work wit provides photoshop mockups. @ least not @ level. mockups static, , translating mockups actual pages work different browsers skill set own. so, need beyond designer, if planning javascript wizardry, animations, or other dynamic

objective c - iPhone Dev: error: cannot find protocol declaration for 'NSXMLParserDelegate' -

i've got xcode project know works, when try build on different machine, error: error: cannot find protocol declaration 'nsxmlparserdelegate' along 90 other random syntax errors. wonder if has build configuration? because can't think else would've changed. appreciate input, thanks!

objective c - Is there a way to create reports in PDF for iOS? -

i looking way create report in ipad, lib in c, c++ or objc or something. what want do, fill invoice data, , let user choose template set. report must pdf. edit: need crystal reports, or way have lots of predefined templates , able render them. edit2: in end had create own report-system handle creation of pdf. here official documentation creating pdf's.

PHP ORM with NOSQL and RDBMS support -

are there php orm projects supports mysql , nosql databases such mongodb? i using redbean mysql orm, woud introduce mongodb applicatoin , perhaps replace of mysql mongodb in future. an orm can allow me transition between both nice. however, tend not orm requires configuration (i.e. yaml, xml etc). redbean nice in allows 1 things working without configuration. yes, doctrine supports various rdbms , nosql storages well

printing - What is the best way to print a Gtk.Widget to the printer? -

i have couple of (mostly) text widgets render printer through standard "print..." menu option. 1 widget mono.texteditor document, , other gtk.textview. i'm looking pretty basic print now, might wrap long lines, , add page numbers. need code of myself somehow? if have pointers, great, if in c#. for line wrap , justification, 1 can use pango layout options, described python @ pygtk/class-pangolayout or c @ pango/pango-layout-objects . see functions pango_layout_set_wrap() , pango_layout_set_justify(). also see example-code routines begin_print, do_page_setup, , do_print in file pygtk-demo/demos/print_editor.py, if have installed pygtk on system. (on system, full path directory of python gtk demo files /usr/share/doc/pygtk2-2.17.0/examples/pygtk-demo/demos) for printer setup dialog, see gtk-high-level-printing-api c, or class-gtkprintoperation python. update 1: posted answer above new user rep. 1, , had disable 2 links because of following messa

ruby on rails - Using select_month in form_for -

i working in ruby on rails , cant figure out how use select_month in form_for. trying is <%= form_for(@farm) |f| %> <div class="field"> <%= f.label :harvest_start %><br /> <%= select_month(date.today, :field_name => 'harvest_start') %> </div> <div class="actions"> <%= f.submit %> </div> <% end %> wich outputting ["harvest_start", nil] thank help. sorry if formatting incorrect. (this answered in comments t. weston kendall making proper answer) the following code got work. _form.html.erb <div class="field"> <%= f.label :harvest_start %><br /> <%= f.collection_select :harvest_start, farm::months, :to_s, :to_s, :include_blank => true %> </div> farms_controller.rb @farm.harvest_start = params[:harvest_start] i got select_month work needed :include_blank , didn't want spend time figuring out nil in array

ruby on rails 3 - Create new record gets NameError: undefined local variable or method 'through' -

i'm new rails , following railscast #258 implement jquery tokeninput, , reason in trying create new record i'm getting error: nameerror: undefined local variable or method `through' #<class:0x101667ef0> /library/ruby/gems/1.8/gems/activerecord-3.0.5/lib/active_record/base.rb:1008:in `method_missing' /users/travis/desktop/yourturn/app/models/tag.rb:4 /library/ruby/gems/1.8/gems/activesupport-3.0.5/lib/active_support/dependencies.rb:454:in `load' /library/ruby/gems/1.8/gems/activesupport-3.0.5/lib/active_support/dependencies.rb:454:in `load_file' /library/ruby/gems/1.8/gems/activesupport-3.0.5/lib/active_support/dependencies.rb:596:in `new_constants_in' /library/ruby/gems/1.8/gems/activesupport-3.0.5/lib/active_support/dependencies.rb:453:in `load_file' /library/ruby/gems/1.8/gems/activesupport-3.0.5/lib/active_support/dependencies.rb:340:in `require_or_load' /library/ruby/gems/1.8/gems/activesupport-3.0.5/li

Jquery math addition -

i'm trying add through jquery event , i'm getting nan. missing? <input type="hidden" id="skillcount" name="skillcount" value="3" onchange="valueadd(this)"/> function valueadd(ok){ var value=parsefloat($(this).val())+1; } the code should be: function valueadd(ok){ // "this" inside here refers window var value=parsefloat(ok.value)+1; } the inline onchange anonymous function: function() { //"this" inside here refers element valueadd(this); } so "this" argument gets called "ok" in valueadd scope. others have stated, though, want use jquery's bind "this" inside of valueadd point element.

c# - ASP.net webservice debugging problem - have tried numerous things! -

been trying create asp.net web service in iis, every time try run newly created webservice following error: unable start debugging on web server. web server not configured correctly. we have tried following far: made sure website within iis using correct version of asp.net made sure following in web.config file <compilation defaultlanguage="c#" debug="true" /> made sure windows integrated authentication enabled in iis since iis installed after visual studio 2008 have run aspnet_regiis.exe any awesome has stuffed me close day now if else fails, easy workaround provided can can indeed access url ok - use menu option in visual studio debug->attach process find worker process (aspnet_wp.exe on xp or w3wp.exe after) should able debug without problem.

statistics - How to use ChebyShev's Inequality in R -

i have statistical question in r , hoping use chebyshev inequality theorem, don't know how implement it. example: imagine dataset nonnormal distribution, need able use chebyshev's inequality theorem assign na values data point falls within lower bound of distribution. example, lower 5% of distribution. distribution one-tailed absolute zero. i unfamiliar how go this, sort of example might help. if helpful know, problem stemming large amount of different datasets different types of distribution - nonnormal. need able select lower percentage of distribution , assign na values them discount them rest of analysis. appreciate help! thanks! from description "i need able select lower percentage of distribution , assign na values them discount them rest of analysis," sounds pretty simple: x <- runif(1000) # simulate data cutpt <- quantile(x,probs=.05) x[x<cutpt] <- na

c# - How to apply the icon for my popup window in WPF? -

i have created 2 windows in project root folder, mainwindow.xaml , popupwindow.xaml respectively. through project properties , managed set icon mainwindow couldn't find available settings popupwindow. therefore, popupwindow still showing system default icon in top left corner. can tell me can set customized icon popupwindow? many thanks. edit: i guess made mistake in xmal code previously. :[ should have been more careful code. anyways, here correct one icon="/[your project name];component/[your ico file name]" are running in debug mode in visual studio? wpf windows don't inherit icon application in debug mode. try ctrl+f5 ("start without debugging") , see if icons appear.

wpf - How do I create a button that has a uniform width and height? -

i create button size of it's largest edge. the reason want button small information circle embedded inside datagrid column. currently have: <datagridtemplatecolumn> <datagridtemplatecolumn.celltemplate> <datatemplate> <button content="i" padding="2" margin="0" verticalalignment="center" horizontalalignment="center" width="{binding source=self, path=height}"> <button.template> <controltemplate targettype="{x:type button}"> <grid> <ellipse fill="#fff4f4f5" stroke="#ff6695eb"/> <contentpresenter margin="0" recognizesaccesskey="false"

code first - MS Entity Framework 4.1 - Maintain data across restructuring -

i using code first approach manage ef. examples have seen don't seem allow use ef able make changes db schema , preserve data. so have entity/object of: public class person int id; string nickname; and add age so: public class person int id; string nickname; int age; how can preserve data may in database "person"? dont call system.data.entity.database.setinitializer(). or call system.data.entity.database.setinitializer() createdatabaseifnotexists(). calling dropcreatedatabasealways or dropcreatedatabaseifmodelchanges drop db.

vbscript - Problem connecting to MySql -

i trying connect mysql server asp vb application. the connection string use : driver=org.gjt.mm.mysql.driver;server=myserveraddress;database=mydatabase;uid=myusername;pwd=mypassword; the code use connect : public sub sqlcommand(objcommand, strsqlcommand) 'run query using command object set objcommand = server.createobject("adodb.command") response.write(application("database_connectionstring_external")) objcommand.activeconnection = application("database_connectionstring_external") objcommand.commandtext = strsqlcommand objcommand.commandtype = adcmdtext end sub i getting error '80004005' what problem in code ? thanks error 80004005 means wrong username/password have checked whether work manually?

javascript - What's the difference between declaring a function by itself or attaching it to window? -

sorry, title doesn't make sense, want know difference between: window.myfunc = function(){} and function myfunc(){} with jsfiddle, functions seem work when attached window. i'm assuming how it's set read javascript , html separately, there otherwise no difference? the first 1 garanties function global , available everywhere. the second 1 same. second 1 take scope of first function embed it. first case: function foo() { window.bar = function (){} } foo(); bar(); // valid; second case function foo() { function bar(){} } foo(); bar(); // fail i hope makes sense you

object - Java Static Method Calling -

is calling static java method ( factory class method ) creates object of class ? i mean static method returns value let's array's size ( array variable of class ) i've checked code couldn't see object of class never instantiated before calling static method. ? public static boolean isfiveinstance() { return _instances.size() == 5; } and _instances class variable private static arraylist<localmediaplayer> _instances; and being created , filled in constructer. no, static invocations not instantiated objects (because not require one). the first time refer class, including static method invocation, class loaded. classloader. that's static initializer comes play: static { // } this block called whenever class initialized (once per classloader)

windows phone 7 - WP7 number of Push Notification channels limit -

in microsoft documentation mentioned "there limit of 1 push notification channel per application. there limit of 15 push notification channels per device. if application exceeds either of these limits, invalidoperationexception(channel quota exceeded) exception thrown.". i understand if user has installed 15 apps use push notifications , if installs app uses push notifications 16th one, invalidoperationexception(channel quota exceeded) thrown. but have no idea have catch exception in code. can suggest? this link gives alot of information using pushnotifications. http://windowsteamblog.com/windows_phone/b/wpdev/archive/2010/05/06/using-push-notification-from-your-windows-phone-application.aspx i think need catch exception when trying create channel.

ios - passing argument 1 of 'setBackgroundColor:' from incompatible pointer type -

- (void)drawrect:(cgrect)rect { // drawing code. // backgroundcolor calayer *mylayer = [self layer]; [mylayer setbackgroundcolor:[uicolor colorwithred:0 green:0 blue:0 alpha:0.5].cgcolor]; ... } when want setbackgroundcolor layer, warning occurred. code runs ok. =========================================================== the best answer : #import <quartzcore/quartzcore.h> if don't include quartz in module compiler not know cgcolor type , issues warning. put #import <quartzcore/quartzcore.h> in header , should remove warning. hope helps, dave

ios - iPhone App Update. "createSymbolicLinkAtPath" released? -

i using symbolic link iphoneapp. nsstring* js_path = [[nsbundle mainbundle] pathforresource:@"js" oftype:nil]; nsarray *paths = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes); if (js_path != nil) { nsfilemanager *fm = [nsfilemanager defaultmanager]; nsstring* move_js_path = [nsstring stringwithformat:@"%@/js", [paths objectatindex:0]]; nserror *error; if ([fm createsymboliclinkatpath:move_js_path withdestinationpath:js_path error:&error]) { } else {} } i updated application program. becomes impossible read file afterwards. however, file able read reinstalling after application program had been deleted once. is there problem in code? if anyones wondering this, reason application moves directory every time it's updated, solution might use relative paths bundles located @ /var/mobile/applications/[unique id changes every update]/app.app whereas documents directory located @ /var/mobile/

custom settings in CKEditor config.js file -

what custom settings can in ckeditor config.js file, changed few, config.font_defaultlabel = 'arial'; other settings can in config.js file? please me in this. solution: took me quite while figure out. let want use verdana default font. here can do: open contents.css , change font tag: font-family: verdana; in application/page output published, add style: .entry-content {font-family: tahoma;} that's it! have change default font successfully. works font size well.

c# - Linq Syntax - Selecting multiple columns -

this linq syntax using entity model iqueryable<string> objemployee = null; objemployee = res in _db.employees (res.email == giveninfo || res.user_name == giveninfo) select res.email; how can select multiple columns? want select res.id aswell. , how can receive those? iqueryable not work think. , called linq sql - right ? as other answers have indicated, need use anonymous type. as far syntax concerned, far prefer method chaining. method chaining equivalent be:- var employee = _db.employees .where(x => x.email == giveninfo || x.user_name == giveninfo) .select(x => new { x.email, x.id }); afaik, declarative linq syntax converted method call chain similar when compiled. update if want entire object, have omit call select() , i.e. var employee = _db.employees .where(x => x.email == giveninfo || x.user_name == giveninfo);

binding - JSF 1.x ValueBinding is deprecated, what is the correct replacement? -

i have jsf 1.0/1.1 code: facescontext context = facescontext.getcurrentinstance(); valuebinding vb = context.getapplication().createvaluebinding("#{somebean}"); somebean sb = (somebean) vb.getvalue(context); since jsf 1.2, valuebinding deprecated , replaced valueexpression . i'm not sure how change above code in order use valueexpression . the part valuebinding vb = context.getapplication().createvaluebinding("#{somebean}"); somebean sb = (somebean) vb.getvalue(context); should replaced by valueexpression ve = context.getapplication().getexpressionfactory().createvalueexpression(context.getelcontext(), "#{somebean}", somebean.class); somebean sb = (somebean) ve.getvalue(context.getelcontext()); or, better somebean bc = context.getapplication().evaluateexpressionget(context, "#{somebean}", somebean.class); see also: get jsf managed bean name in servlet related class how create dynamic jsf form fields

oracle - Issue "ORA-01722: invalid number" error at many places has been created -

i getting error "ora-01722: invalid number" @ many places oracle driver. can point out workaround/solution? pdoexception: select base.fid fid, base.uid uid, base.filename filename, base.uri uri, base.filemime filemime, base.filesize filesize, base.status status, base.timestamp timestamp {file_managed} base (base.fid in (:db_condition_placeholder_0)) (prepared: select base.fid fid, base."uid" "uid", base.filename filename, base.uri uri, base.filemime filemime, base.filesize filesize, base.status status, base.timestamp timestamp "file_managed" base (base.fid in (:db_condition_placeholder_0)) ) e: sqlstate[hy000]: general error: 1722 ocistmtexecute: ora-01722: invalid number (ext\pdo_oci\oci_statement.c:146) args: array ( [:db_condition_placeholder_0] => ) in drupaldefaultentitycontroller->load() (line 196 of c:\xampp\htdocs\new\drupal\includes\entity.inc). without context, hard sure. i'm in

redirect - Javascript's redirection logic -

so, if have javascript function such as function dosomething() { alert("starting..."); window.location = "http://www.example.com"; alert("completed."); } why last line not work? i'm sure it's security issue, maybe i'm doing wrong. thanks in advance. pretty sure it's because have left page , browser doesn't run javascript pages not displayed. to you'd need use frames or else load new page in iframe or equivalent.

c# - LINQ extension methods: use Lambda expressions or methods? -

when using linq extension methods enumerable.select, better use lambda expression, or regular method? i'm asking both respect (memory) optimization*, , readability**. example code: private void main() { var array = new int[1]; var result1 = array.select(x => x.tostring()); // lambda var result2 = array.select(linqhelper); // method } private string linqhelper(int x) { return x.tostring(); } * i'm thinking of closures creating scopes unused instantiated variables in them, because variables in scope when lambda created . edit - stupid thinking, since variables captured closure when they're referenced in lambda expression. **both options ok me. from optimization point of view, there should no difference. from readability point of view, i'd think whether need same logic in several places. if so, use method , use method group conversion. way don't repeat yourself, don't have change several bits of code if requirements c

performance - cassandra massive write perfomance problem -

i have server 4 gb ram , 2x 4 cores cpu. when start perform massive writes in cassandra works fine initially, after couple hours 10k inserts per second database grows 25+ gb, , performance go down 500 insert per seconds ! i find out because compacting operations slow don't understand why? set 8 concurrent compacting threads cassandra don't use 8 threads; 2 cores loaded. appreciate help. we've seen similar problems cassandra out-the-box, see: http://www.acunu.com/blogs/richard-low/cassandra-under-heavy-write-load-part-ii/ one solution these sort of performance degradation issues (but no means only) consider different storage engine, castle, used in above blog post - opensource (gpl v2), has better performance , degrades more gracefully. code here (i've pushed branch cassandra 0.8 support): https://bitbucket.org/acunu/fs.hg and instructions on how started here: http://support.acunu.com/entries/20216797-castle-build-instructions (full disclos

objective c - Can't get custom @protocol working on iOS -

note: below using ios automatic reference counting (arc) enabled. think arc may have lot why isn't working set per examples i've found via google. i trying create protocol notify delegate of filename user selects uitableview. filelistviewcontroller.h @protocol filelistdelegate <nsobject> - (void)didselectfilename:(nsstring *)filename; @end @interface filelistviewcontroller : uitableviewcontroller { @private nsarray *filelist; id <filelistdelegate> delegate; } @property (nonatomic, retain) nsarray *filelist; @property (nonatomic, assign) id <filelistdelegate> delegate; @end filelistviewcontroller.m #import "filelistviewcontroller.h" @implementation filelistviewcontroller @synthesize filelist; @synthesize delegate; this gives error @ @synthesize delegate; line "filelistviewcontroller.m: error: automatic reference counting issue: existing ivar 'delegate' unsafe_unretained property 'delegate&#

javascript - Infinite new window loop when triggering click event -

i have overview page shows data in table. pop-up opens when user clicks on row. pop-up get's reloaded on , on again until hangs. the overview code: <tbody> <tr> <td> <a href="/pop-up/details/1/" onclick="mywindow=window.open('/details_screen/1/','window1','toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=800,height=600'); return false;">details screen 1</a> </td> </tr> <tr> <td> <a href="/pop-up/details/2/" onclick="mywindow=window.open('/details_screen/2/','window2','toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=800,height=600'); return false;">details screen 2</a> </td> </tr> </tbody> the javascriptthat makes rows clickable: function make_rows

How to upload a file from the browser to Amazon S3 with node.js, Express, and knox? -

i'm trying find example code utilizes node.js, express, , knox. the docs knox give clear examples of how upload file stored in file system. https://github.com/learnboost/knox#readme additionally, there number of simple tutorials (even in express itself) on how upload files directly express , save file system. what i'm having trouble finding example lets upload client upload node server , have data streamed directly s3 rather storing in local file system first. can point me gist or other example contains kind of information? all of previous answers involve having upload pass through node.js server inefficient , unnecessary. node server not have handle bandwidth or processing of uploaded files whatsoever because amazon s3 allows uploads direct browser . have @ blog post: http://blog.tcs.de/post-file-to-s3-using-node/ i have not tried code listed there, having looked on it, appears solid , attempting implementation of shortly ad update answer findings.

.htaccess - CakePHP remove "?url=" from the URL after a redirect -

i'm using cakephp php application. by default puts .htaccess file: rewriterule ^(.*)$ index.php?url=$1 [qsa,l] after rule, doing this: redirectmatch ^/resources(.*)$ http://domain.com/community$1 [qsa,r=permanent,l] this makes redirected url: http://domain.com/community/view/171/?url=resources/view/171/ how can rid of appended "?url=" without breaking cakephp's routing? if understand question correctly, want have requests /community/* routed resourcescontroller . should able acheive adding following app/config/routes.php . /** * rename /resources/* /community/* */ router::connect('/community', array('controller' => 'resources')); router::connect('/community/:action/*', array('controller' => 'resources')); the second rule of magic, mapping matching requests resourcescontroller , passing in action also. with above approach can take advantage of reverse-routing: echo $this->ht

Question reg. ASP.NET ViewState -

i've been going through excellent article http://msdn.microsoft.com/en-us/library/ms972976.aspx says viewstate not responsible form fields retain values between postbacks. form fields values never stored in viewstate? edited: mean form fields asp.net controls textbox, dropdownlist etc. edited: if user enters value in asp.net textbox , submit form, new page still has textbox value thinking because of viewstate article says it's not so! as say, form values not stored in viewstate. reason (for example) text of textbox control retained between 2 postbacks because implements ipostbackdatahandler -contract , automatically maps keys in request.form-collection appropriate properties of control. these 2 mechanisms confused. see http://www.mikesdotnetting.com/article/65/viewstate-form-fields-labels-and-javascript explanation.

authentication - Best way to way a php script that logs a user in when they click a link on another website? -

possible duplicate: single sign on - how implement? i have 2 website totally unrelated. need write php script send user second site , log them in. need securely , send on user information (like username, profile details etc). what best way achieve this? setup ssl connection between 2 sites. and add user information example json string , send other site. on other site need check credentials (in json string) again.

FTP access on Windows Azure -

quick question. i'm moving asp.net mvc web application windows azure platform. working out okay apart 1 thing. in application @ moment, make use of ftp accounts each user import large quantities of files our database. i understand ftp on azure not straightforward. i've googled , found article: ftp on azure this seems need except we'll need able add new users own separate ftp account. know of easy workaround this? thanks in advance did consider running (ftp) service that's not iis based, , add users programatically? also, how going solve data sync issues when role recycles or when upgrade it? make sure backup blob on regular basis! personally, i'd mount vhd drive (azure drive) hosted on blob storage, , have ftp server point drive. however, make sure have 1 instance of server (problem #1) unless don't need higher 99,9% reliability can solve running single instance. step 2 i'd implement user management in relation program. it's no

javascript - Dynamically adding JQUERY tabs, getting "Uncaught SyntaxError: Unexpected token ILLEGAL" -

i'm pretty sure there's error in 1 of strings, can't find it. goal of code dynamically add facebook comments plugin tabs depending on episode of show work listening to. $('body').attr('id', 'tabs'); $( "#tabs" ).tabs(); $('#tabs').ready(function(){discussion(222); }); function discussion(episodenumber){ var tabnum =$('#tabs').size('a') + 1; console.log(tabnum); $('#tabs').append('<div id=\"#tabs-'+tabnum+'\">'+episodenumber+'</a></li>'); $('#tabs-'+tabnum).ready(function(episodenumber,tabnum){$('#tabs-'+tabnum).append('<p><div id=\"fb-root\"></div><script src=\"http://connect.facebook.net/en_us/all.js#xfbml=1\"></script><fb:comments href=\"http://www.facebook.com/l.php?u=http%3a%2f%2fwww.foo.com%2fep

ruby on rails - Access join-model on .build with has_many, :through -

is there way access join model of "has_many, :through =>" association created on ".build"? i'm sorry don't have actual code here, hope understand want ;) a: has_many :bs has_many :cs, :through => :bs b , c defined correctly (w/ belongs_to, has_many, has_many-through) now: in controller i'm trying var = @a.cs.build (within transaction, don't think that's relevant here),which "creates" c-instance , joining b. how can access automatically created b, i'd pass attributes? possible @ all, or have work around @a.create_c # or varb = b.new varb.someattr1 = "foo" # <- want w/ .build varb.someattr2 = "bar" varb.a = @a varc = c.new varc.someattr3 = "asdf" varb.c = varc # ... , .save! or sth that? don't think that's style, nor 'break' wrapping transaction reason rly hope want. edit umh, first of all: answers, i'm still stuck. i'll try more precise: @a

android - how to implement this sliding navigation menu? -

Image
i'm trying replicate following sliding navigation menu functionality (the 1 "top stories", "world", "u.s" etc.) no luck far. i'm feeling there obvious way achieve this, i'm seeing in many apps. based on library shipped android? starting point or materials used achieve welcomed. keep in mind, don't care design/xmls, implementation logic. it nothing horizontalscrollview contains child views.

android - What is the best way to find out the number of Tabs in a TabActivity? -

i create tabs dynamically in tabactivity. there simple way ask number of existing tabs? maybe bit of workaround, should able use: gettabhost().gettabwidget().gettabcount() . i tested in app , worked correctly. see here more info: http://developer.android.com/reference/android/widget/tabwidget.html#gettabcount()

hibernate - Ejb3Configuration.addPackage() does not find entities -

i want add known jpa entities programatically when creating entitymanagerfactory. have sequence (hibernate 3.6) ejb3configuration ejbconf = new ejb3configuration(); ejbconf.configure("testpu", null); ejbconf.addpackage("org.jboss.jawabot.irc.ent"); ejbconf.addpackage("org.jboss.jawabot.irc.model"); emf = ejbconf.buildentitymanagerfactory(); i tried calling addpackage()'s before configure(). adding packages fine. however, hibernate not find entities. when persist it, get: unknown entity: org.jboss.jawabot.irc.model.ircmessage what's wrong? how make hbernate recognize entities packages? thanks, ondra update: project here . bit messy because trying few tricks in that. and note, entities "core" module (jar) of app picked up. the anwser is, purpose of addpackage() tell hibernate take given package's annotations account, not load it's entities. more, ejb3configuration deprecated 4.0 in favor o

jquery - How to select ajax response to use in colorbox javascript? -

i have ajax function outputs results of +1 , -1, in javascript, want +1 response use in colorbox. ajax function: function my_ajax_obj_lightbox() { global $post; if ( !empty( $_post['obj_id'] ) ) { $obj = new my_obj( $_post['obj_id'] ); if ( $obj instanceof my_obj ) { my_objs_ajax_response_string( 1, $obj->html() ); } } my_objs_ajax_response_string( -1, 'invalid request' ); } add_filter( 'wp_ajax_obj_lightbox', 'my_ajax_obj_lightbox' ); now , in javascript, want this: var response = ......; if ( response[0] >= 1 ) { j.fn.colorbox({ html: response[1], maxwidth: '90%', maxheight: '90%' }); } how define var response , ajax response value ? it sounds need setting ajax request, , parsing response javascript object... let's have php file returns response in json format: &

how to convert an HTML template into Cake PHP template -

i'm beginner in cake php. have needed convert html template cake php template. idea? it easy. replace template main file extension .ctp index.html index.ctp look @ layout of file (html code) , determine section of template want appear on pages; usually templates setup follows: <html> <head> <title>my site</title> // include javascript , css files here <?php echo $this->html->css(array('cake.generic','default')); echo $this->html->script(array('myscript','jquery')); ?> </head> <body> <div id="container"> <div id="header"></div> <div id="body"> <div id="main_content" style="width:600px;float:left"> <?php //code should in home.ctp // in pages folder. cut content

java - Google App Engine datastore Entity not being deleted -

i using google app engine datastore store 4 string values. string vlaues added datastore in servlet: datastoreservice datastore = datastoreservicefactory.getdatastoreservice(); entity balances; key primarykey; string table = "maintable"; string name = "values"; primarykey = keyfactory.createkey(table, name); transaction t = datastore.begintransaction(); // if 'table' exists - delete datastore.delete(primarykey); // make sure it's deleted/ t.commit(); t = datastore.begintransaction(); balances = new entity("balances", primarykey); updatebalances(balances); datastore.put(balances); // save new data t.commit(); resp.sendredirect("/balance.jsp"); i want able update 4 string values each time servlet run - why key first , delete it. use separate transaction ensure happens.

json - Advice on JavaScript library for visualizing Yahoo Pipe Output -

i'm writing javascript library. project school need make easier visualize data yahoo pipes. data format json string, can contain anything, contains list of items, different attributes each item. this approach quite general , wondering functionality insert library. how can deal general flow of data make usable library kinds of data.. data yahoo pipes can news items (title, description, postdate, images, links,..) yahoo pipes has functionality parsing csv files, "data tables" possible. also thinking structure of library, best way implement it. in general library needs load in data pipe (json string) , pass visualization library google chart or d3.js (formerly protovis) i consider javascript skill level 'rookie' :) replies, advice welcome!

How do I add a auto_increment primary key in SQL Server database? -

i have table set has no primary key. need add primary key, no null, auto_increment. i'm working microsoft sql server database. understand can't done in single command every command try keeps returning syntax errors. edit --------------- i have created primary key , set not null. however, can't set auto_increment. i've tried: alter table tablename modify id nvarchar(20) auto_increment alter table tablename alter column id nvarchar(20) auto_increment alter table tablename modify id nvarchar(20) auto_increment alter table tablename alter column id nvarchar(20) auto_increment i'm using nvarchar because wouldn't let me set not null under int it can done in single command. need set identity property "auto number" alter table mytable add mytableid int not null identity (1,1) primary key more precisely set named table level constraint alter table mytable add mytableid int not null identity (1,1), add constraint pk_mytable p

jquery - Getting the masked value of a password field? -

i've got normal password field "get" masked value - yep, ugly ********** obfuscated value. html: <input type="password" name="password" value="" id="password"></input> js/jq dom: $("#password").val(); // password in cleartext if mean want string contains * number of characters inserted in password field do: var password = $("#password").val(); password = password.replace(/./g, '*');

osx - How to launch the “To open “Java Preferences", you need a Java runtime. Would you like to install one now?” in Lion? -

how can make lion's new java installer prompt launch when application opened? example: http://kb2.adobe.com/cps/909/cpsid_90908.html eclipse appears netbeans not. going terminal , typing "java" triggers popup looking for, provided java not installed on system. i don't know how trigger popup afterwards

networking - iPhone - How to identify all available wifi networks programatically? -

i want identify available wifi networks available. checking file @ path /library/preferences/systemconfiguration/com.apple.wifi.plist but gives networks iphone has connected till date. not give available networks. does know how ? ok if private api . have anyhow .. please me !! there no way can access available wifi's ssid in iphone app . tried api apple rejected app saying private api. sent query apple developer support , replied saying not possible in current ios version.

c# - Can I know width of TextBlock when create it? -

i create textbox on canvas this: textblock t = new textblock(); t.foreground = new solidcolorbrush(...); t.fontsize = 10; t.horizontalalignment = horizontalalignment.left; t.verticalalignment = verticalalignment.top; t.text = ...; canvas.setleft(t, "f(width)"); canvas.settop(t, ...); canvas.children.add(t); i want know width of textblock, because left coordinate depends on this. can it? actualwidth 0. thanks. before add it, call measure on it, use desiredsize. edit: ok because canvas not affect size of element once placed. if added to, say, grid fixed-size row, wouldn't give real height once added since adding grid change it. as mario vernari points out, if have real complex positioning needs it's pretty easy override arrangeoverride (and measureoverride) , make custom panel. canvas written way, stackpanel, etc. specific-measuring , arranging panels, , ca

asp.net - Display image instead of text in Calendar "NextPrev" -

how can display image instead of '<' or '>' asp.net calendar ? i've tried following, won't display (and seems bit messy): cal.prevmonthtext = "<img src='/style/images/calanderright.png' alt='previous' />" check this link out, think you. have done through css, because control has little customization nextprevstyle property.

ruby - Rails namespaced routes - Windows vs Linux -

i'm working on old client application running under rails 2.3.11 on windows server 2003. application relies on simple catch-all route (hell yeah!) : map.connect ':controller/:action/:id' i have nested modules , working fine on windows (prod) , mac os (dev). url_for(:controller=>'/settings/users', :action=>:index) #=> settings::users#index recently changed mac os ubuntu 11.04. works, except these nested routes. url_for(:controller=>'/settings/users', :action=>:index) #=> settings#users does have clue going on? why problem linux only? it's not os-specific problem if affects routing in such specific way. there reason you're prefixing controller name / ? named routes avoid of mess being specific, it's unfortunate you're left without them. there's slight difference in gem versions on 2 systems, maybe subtle.

tfs - How to create web deployment package from team build? -

i've been reading , experimenting days. bought latest "inside microsoft build engine - using msbuild , team foundation build". i've been trying figure things out looking @ build targets. i able package built on build server, want able specify installation folder, doesn't go wwwroot. read have switch project on using cassini local iis server. went through of that. the args i'm passing msbuild through definition: /p:deployonbuild=true /p:deploytarget=package /p:msdeploypublishmethod=inproc /p:createpackageonpublish=true /p:msdeployserviceurl=localhost i've got many questions, i'll start simply. if can provide guidance i'd super thankful. if named application doesn't exist on build server (which shouldn't!) package creation fails. if add shell app named accordingly package built. even if hack way past #1 when try deploy using web.deploy.cmd, fails: error: using 64-bit source , 32-bit destination provider apphostconfig not

make a TextView scrollable + Bug in Android -

Image
i have read post: making textview scrollable on android without success. my app looks this: where black space textview. declared @ xml this: <textview android:id="@+id/consola" android:layout_width="320px" android:layout_height="333px" android:layout_alignparenttop="true" android:layout_alignparentleft="true" android:scrollbars = "vertical" android:gravity="top|left" android:inputtype="textmultiline" > </textview> and code takes text edittext when button pressed, , writes new line @ textview text. code looks like: public class helloworldactivity extends activity { /** called when activity first created. */ @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); final textview miconsola = (textview) findviewbyid(r.id.consola); miconsola.setmovementmethod(new scrollingmovementmethod()); fin

ios - Xcode 4.2 link error: libz issue? -

moving project xcode 4.2, getting number of mach-o linker unresolved errors, things _crc32, _expf, , _unwindsjlj_register, on project compiles , links fine in xcode 4.0.3. i suspect might libz issue, since previous project linked libz.1.2.3.dylib. removed reference, , added libz.1.2.5.dylib, found in /platforms/iphoneos.platform/devicesupport/5.0 (9a5259f)/symbols 1/usr/lib folder. i same 39 unresolved references whether include libz.1.2.5.dylib or not, seems suspicious. link against libz.dylib , add through build phases tab. project >> target >> build phases >> link binary libraries press + under list , select libz.dylib add lib work inbetween sdk updates.

python - Dynamic per-request database connections in Django -

i'm building centralised django application interacting dynamic number of databases identical schema. these dbs used couple legacy applications, of in php. our solution avoid multiple silos of db credentials store info in generic setting files outside of respective applications. setting files created, altered or deleted without django application being restarted. for every request django application, there http header or url parameter can used deduce setting file @ determine database credentials use. my first thought use custom django middleware parse settings files (possibly caching) , create new connection object on each request, patching django.db before orm activity. is there more graceful method handle situation? there thread safety issues should consider middleware approach? rereading file heavy penalty pay when it's unlikely file has changed. my usual approach use inotify watch configuration file changes, rather trying read file on every request.

php - Making zend EmailAddress form validator return only one custom error message -

i'm creating email form element (inside zend form): //create e-mail element $email = $this->createelement('text', 'username') ->setlabel('e-mail:') ->setrequired(true) ->addfilters(array('stringtrim', 'stringtolower')) ->addvalidator('emailaddress', false, array( 'messages' => array( zend_validate_emailaddress::invalid => 'dit e-mail adres ongeldig.', ) )); //add element $this->addelement($email); now, when invalid e-mail entered quite lot of messages appear: '#' no valid hostname email address '@#$@#' '#' not match expected structure dns hostname '#' not appear valid local network name '@#$' can not matched against dot-atom format '@#$' can not matched against quoted-string format '@#$' no valid lo

Facebook - refer a friend -

i'd enquire facebook heads on here how best following: i'd run promotion facebook business page encourages users recommend friend in order gain access enter competition. being in facebook environment preferred encourage facebookers refer friend's on profile. know if there's app out there (i've searched , not found) this? facebook api allow access select specific friend(s) notify on facebook? thanks & suggestions. yes, need have read_friendlists added permission facebook app. from there think can fb.api() kind of call information source

c# - .NET Encryption -

what trying when user registers password gets encrypted, , encrypted password gets saved in database, , when user logs in should decrypt password compare if user entered correct password, when try decrypt gives me "bad data" exception. please guys. here code: protected void btnlogin_click(object sender, eventargs e) { try { private cryptography crypt = new cryptography(); var registeruser = new test.model.user(); registeruser.emailaddress = txtemail.text; registeruser.password = txtpassword.text; //new test().getbyusername(registeruser); new test().getbyemail(registeruser, crypt); } catch (exception ex) { } } public void getbyemail(user user, cryptography crypt) { try { var repo = new userrepository(); var test = repo.getencryptedpasswrd(user); var o = repo.getprivatekey(user.emailaddress); crypt.privatekey = o; var j = repo.getpublickey(user.email

Grails session handling in waiting thread with Hibernate and MySQL InnoDB -

in order realize client-side notifications in ajax-driven application developing grails (and gwt), have implemented service method block until being signaled. using monitor object wait signal. once signaled, thread query database new objects , return entities browser. it working fine memory database not expect when use mysql database connector. happens: whenever findallby... call find objects created before request started. the lifecycle of service method request client hibernate session being created grails service querying database new objects if there none: wait incoming signal: query database new objects ( does not new objects when using mysql, works fine memory db) the mysql query log shows queries expected result of findallby... empty array. i disabled query , second level cache. behaviour same no matter if data connection pooled or not. what doing wrong? should close hibernate session? flush it? use transaction queries? or somehow enforce findallby... meth

c# accessing Outlook calendar from a custom Excel add-in -

is possible create add-in excel accesses/imports calendar outlook? using c# in visual studio 2010. it possible - excel add-in dll library , can there. (i believe seen msdn page developing add-ins: http://msdn.microsoft.com/en-us/library/bb157876.aspx ). on outlook side, bit more complicated, calendar folder accessible via outlook interop , folder hierarchy. see http://support.microsoft.com/?kbid=310244 , http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.folder.aspx hth

iphone - How to make an image scroll forever -

i trying make image scroll end of screen automatically , jump beginning of image , scroll again in continuous loop. don't want user know end of image released? know how make that? image must scroll itself, not because user touched it, that's why can't use wwdc video. help! you scroll 2 uiimageviews adding to/subtracting x values. when 1 scrolls off screen, set x value behind second one, , continue scrolling. ex: ([ ] screen) <------------------------------------ | [ ] | b | | a[ ]| b | | [ | ] b | [ ] b | |

ASP.NET MVC - how to get a full path to an action -

inside of view can full route information action? if have action called dothis in controller mycontroller. can path of "/mycontroller/dothis/" ? you mean using action method on url helper: <%= url.action("dothis", "mycontroller") %> or in razor: @url.action("dothis", "mycontroller") which give relative url ( /mycontroller/dothis ). and if wanted absolute url ( http://localhost:8385/mycontroller/dothis ): <%= url.action("dothis", "mycontroller", null, request.url.scheme, null) %>

sql - MYSQL filter by count of another table -

i'm beggining mysql. have following query: select answers.data. * , count( answers.reports.id ) rcount answers.data left join answers.reports on answers.data.id = answers.reports.answer_id answers.data.question='4' group answers.data.id it's returning me answers current question added column called rcount (number of reports) i want return less 3 reports. tried following code: select answers.data. * , count( answers.reports.id ) rcount answers.data left join answers.reports on answers.data.id = answers.reports.answer_id answers.data.question='4' , rcount < '3' group answers.data.id but aprrently that's not new condition goes. can't find in manual solution since i'm new this. thanks use having clause: select answers.data.* , count( answers.reports.id ) rcount answers.data left join answers.reports on answers.data.id = answers.reports.answer_id answers.data.question='4' group answers.data.id having count( ans

Using python to run a C++ program and test it -

suppose have simple c++ program takes in inputs , outputs string. (actual program more complicated still text based): $ ./game $ kind of game? type r regular, s special. $ r $ choose number 1 - 10 $ 1 $ no try again $ 2 $ no try again $ 5 $ yes win! i haven't used python before, possible write python script run program, feeds input, , outputs results standard output? have ask question here running using c++ seems complicated. awesome direct me code examples. appreciated. use pexpect . normal stdin/stdout piping doesn't work, because standard library facilities in parent , child processes tend buffer i/o more aggressively when file descriptor isn't tty (via isatty call). obviously, can fix in parent, since own code; call flush @ appropriate points. child process running preexisting code don't own. pexpect module feeds child process pseudo-tty, tricks child thinking it's talking console. same trick gui terminals xterm , rxvt use.

Check if object exists - Objective C -

instead of recreating object on , on again, there way can check if object exists in if statement? thanks! assuming object reference set nil if there no object, can use nsthing *myobj = nil; if (!myobj) myobj = [[nsthing alloc] init]; [myobj message];

objective c - Window-less Cocoa application -

i'm complete beginner in objective-c , cocoa. i create window-less application, shows nsstatusitem in system tray. tray works fine, however, there 1 problem. for reason application automatically creates window me, not want. i thought caused automatic interface builder template created when created application in xcode, deleted .nib file project. window still gets created. the lines contain reference window in header: nswindow *window; @property (assign) iboutlet nswindow *window; and in implementation file: @synthesize window; both added automatically, did not write this. how stop app creating window? tried removing references window code, including nswindow *window , window still got created. my temporary fix right call [window close]; in application, surely there better way? my suspicion nothing in code creating window. when create new cocoa xcode application, xcode sets xib interface you. open mainmenu.xib (should under resources) in interfa