Posts

Showing posts from July, 2013

Storing preferences that ship with the iPhone without a Settings App -

i want ship iphone app preferences don't need create "settings app" using plist , that. using nsuserdefaults , know how store , retrieve using class. however, i'm struggling how have initial set of preferences there when user loads app first time. should retrieve nsuserdefaults in viewdidload , if return nil, set them @ point? or there better method? i'd proposed. check whether user default keys exist , if not, create them using default values. where check you, of course should happen before part of app needs of info. so, mbehan suggested, might want perform init check within didfinishlaunching of appdelegate.

c# - Combinining several strings to a single string -

string f = dropdownlist1.selecteditem.value; string s = dropdownlist3.selecteditem.value.padleft(3,'0'); string q = dropdownlist2.selecteditem.value; string w = textbox2.text.tostring(); string o = textbox3.text.tostring(); i want combine single string i.e string u= f+s+q+w+o how it? the code gave should work fine: string u = f + s + q + w + o; note converted compiler into: string u = string.concat(new string[] { f, s, q, w, o }); edit: other answers far have suggested stringbuilder right way go here. it isn't . stringbuilder great avoid problems this: // bad code - don't use string result = ""; foreach (string value in collection) { result += value; } in case, there increasingly large temporary strings created because concatenation performed on each iteration of loop . intermediate value only required next iteration of loop. now, in case know whole result of concatenation in single go: f + s + q + w +...

gnu - Exclude certain filename patterns and directories from Find -

i'm trying find files not date compared cvs. our cvs structure broken (it not recurse in directories) i'm trying work around find now. what have this: for in `find . -not \( -name "*\.jpg" \) -path './bookshop/mediaimg' -prune -o -path '*/cvs*' -prune -o -path './files' -prune -o -path './images/cms' -prune -o -path './internal' -prune -o -path './limesurvey171plus_build5638' -prune -o -path './gallery2' -prune -o -print `; cvs status "$i" |grep status ; done &>~/output.txt but somehow attempt @ excluding images (jpg in case) not work, still show up. have suggestion on how them out of results find? this failing same reason mixing boolean , and or fails. what you're saying here (in pseudo-code): if ( file not named '*.jpg' , path matches './bookshop/mediaimg' , prone or path matches '*/cvs*' , prune or path matches ...

vba - disable shift key on startup in ms-access -

problem: in ms access can hold shift key when opening database in order bypass startup options , autoexec script. want disable permanently . first of know has been answered on numerous other sites, not find question here, have different need.the solutions found focused on placing invisible buttons re-enable shift-key shortcut passwords etc. i want very simple solution . want script can add autoexec script disable shift-key shortcut or that. i do not need way re-enable shift-key shortcut. the simplest , secure , , easiest way preferred. thanks! i have used bit of code function setbypass(rbflag boolean, file_name string) integer docmd.hourglass true on error goto setbypass_error dim db database set db = dbengine(0).opendatabase(file_name) db.properties!allowbypasskey = rbflag setbypass_exit: msgbox "changed bypass key " & rbflag & " database " & file_name, vbinformation, "skyline shared" ...

licensing - Does a GPL licensed font influence my own application's license? -

i want use gpl-licensed font in application don't want use gpl app itself. are there other obligations except providing the source of font , mentioning of gpl? if font gpl proper, can't embed actual stroke data in application without making license application gpl-compatible. if it's "gpl exceptions" embedding may acceptable provided font made available. embedding bit why gpl considered inferior license fonts. otherwise gpled font not interfere application license.

c++ - Nesting QMainWindows in Qt -

i'm making game in qt. game displayed qgraphicsview/qdockwidget in qmainwindow. i'm trying make menu it, thought make qmainwindow qpushbuttons. want integrated in 1 qmainwindow. when click "new game" in menu, game(qgraphicsview/qdockwidget) (and in same window) displayed, without first shutting down menu-window , showing game-window. it easier have 1 qmainwindow game , menu qwidgets, impossible because i'm using qdockwidgets, have make seperate qmainwindow display game. any solutions? best regards you switch qml (qt declarative) easy use state menus shown , 1 displaying game without menus.

c# - Detailed XML Documentation for field. Does it possible? -

i have define callback field , event property it: private action<int, int, taskcallbackargs> _callbackevent /// <summary> /// provides callback event task. /// </summary> public event action<int, int, taskcallbackargs> callbackevent { add { _callbackevent += value; } remove { _callbackevent -= value; } } in code have invoke _callbackevent . right, when type _callbackevent( vs show me intellisense method want (int arg1, int arg2, taskcallbackargs arg3) arguments. when open code time later don't remember arg1, arg2 , arg3. is there way use xml documentation field following? /// <summary> /// description /// </summary> /// <param name="current">param description...</param> /// <param name="total">param description...</param> /// <param name="additional">param description...</param> thanks! action<int, int, taskcallbackargs> dele...

Trouble Loading thumbnails from XML in Flash as3.0 -

i have made gallery script loads xml large image, text, , 3 thumbnails. having trouble getting thumbnails load reason. have 3 thumbnails should previous image, current image, , next image. except when click on current image should load random image. buttons work if try load thumbnails. don't appear. to load thumbnails have created loop array of thumbnails , number of image recorded variable noofimage. load other thumbnails subtracting 1 noofimage if prev button clicked(mousewheel down or key dwn or key left) , adding 1 noofimage if next button clicked(wheel , keys...) when trace variables thumbnail number seem correct @ times , other times receiving errors. for ex. if load swf , click next. previous image "4294967295" , next 1 outputs "error #2044: unhandled ioerrorevent:. text=error #2035: url not found." if value of nextimage = 1 dont see why isn't loading. , why giving weird number should 0? can not tell if problem if statements use handle no...

asp.net - Where to write exceptions -

i making web application, first application. want know when there not matching catch block exception generated , don't want display exception generated, instead want display message or want forward other link or page, should write message or how should display this? please elaborate me on this. i think want customerrors property in web.config file. looks this: <customerrors mode="remoteonly" defaultredirect="error.aspx"> <error statuscode="403" redirect="403.htm"/> <error statuscode="404" redirect="404.htm"/> </customerrors> this let redirect own error pages thrown exceptions, error 403's, , error 404's.

c++ - find middle elements from an array -

in c++ how can find middle 'n' elements of array? example if n=3, , array [0,1,5,7,7,8,10,14,20], middle [7,7,8]. p.s. in context, n , elements of array odd numbers, can find middle. thanks! this quick, not tested basic idea... const int n = 5; // middle index int arrlength = sizeof(myarray) / sizeof(int); int middleindex = (arrlength - 1) / 2; // sides int side = (n - 1) / 2; int count = 0; int mynewarray[n]; for(int = middleindex - side; <= middleindex + side; i++){ mynewarray[count++] = myarray[i]; }

Which mapping type to choose for associative Arrays? Doctrine ODM -

i have simple question (by way great!) doctrine odm. assume have document like: /** * @document */ class test { /** @id */ public $id; /** @whichtype */ public $field = array(); } now want store associative array like array("test" => "test1", "anothertest" => "test2", ......); in $field property of class. no problem mongodb, know, in doctrine when use example @collection or @field, values stored (array_values being used in mapping driver collection example). stored value looks like array("test1", "test2", ....) does know doctrine-odm mapping type should use in order preserve key-value pairs in database? thank in advance, andi (greetz germany) it should hash type: http://readthedocs.org/docs/doctrine-mongodb-odm/en/latest/reference/annotations-reference.html?highlight=hash#hash

regex - Searching and capturing a character using regular expressions Python -

while going through 1 of problems in python challenge , trying solve follows: read input in text file characters follows: dqheabsamljtmaokmnslzivmenfxqdatqijitwtychyemwqtnxbblxwzngmdqhhxnlhfeyvzxmhsxzd bebaxeapgqpttvqrvxhpeoutisttpdeeugfgmdkkqceyjusuigrogfypzkqgvccdbkrcywhflvpzdmek myupxvgtgsvwgrybkonbeghqhuxhhnyjfwsftfaiwtaombzescsosumwpssjcpllblspigffdlpzzmkz jarrjufhgxdrzywwosrblprasvrupzlaubtdhgzqtvzovhevstbhpitdlluljvvwrwvhpnvzewvyhmps kmvcdehzfzxtwocgvakhhcnozrsbwsiehpenfjarjlwwcvkftlhuvsjcziyfpcyrojxopkxhvucqcuge luwlbcmqpwdvupubrrjzhfexhxsbvljqjvvfegruwrshpekujcpmpisrv....... what need go through text file , pick lower case letters enclosed 3 upper-case letters on each side. the python script wrote above follows: import re pattern = re.compile("[a-z][a-z]{3}([a-z])[a-z]{3}[a-z]") f = open('/users/dev/sometext.txt','r') line in f: result = pattern.search(line) if result: print result.groups() f.close() the above given s...

eclipse - ScrolledComposite splits the screen vertically and content is displayed in the right half -

i using scrolledcomposite existing control(with many children) based on method2 mentioned here :http://www.placelab.org/toolkit/doc/javadoc/org/placelab/util/swt/swtscrolledcomposite.html the change instead of creating new shell & display using existing control's parent. seeing scroll bars expected existing control/content displayed form centre & not start. first half(vertically split) of layout empty & actual control/content gets displayed in right-half. checked bounds, origin, size etc. seem fine. screenshot putup here :http://img818.imageshack.us/i/contentstartsfrommiddle.jpg any clues thanks in advance did delete composite c1 ? maybe in left side. you provide change code.

.net - "Maximum-Count of Selected Items"-Validator for ListBox -

i have asked myself if there easy way check if listbox has maximum of 5 selected items. there must @ least 1 , @ 5 items selected. do need customvalidator server-side validation? many in advance... you can customvalidator routine. <asp:customvalidator id="listbox5itemsvalidator" runat="server" onservervalidate="listbox5itemsvalidator_servervalidate" clientvalidationfunction="listbox5itemsvalidator_clientvalidate" controltovalidate="mylistbox"> </asp:customvalidator> server-side code: protected void listbox5itemsvalidator_servervalidate( object source, servervalidateeventargs args) { int selectioncount = 0; foreach (listitem item in mylistbox.items) { if (item.selected) selectioncount++; } args.isvalid = (selectioncount >= 1 && selectioncount <= 5); } client-side code: function listbox5itemsvalidator_clientvalidate(sender, args) { var se...

c# - Create multiple gridviews in code behind -

this interesting.. i want have multiple gridviews in panel. , number of gridviews not fixed.. so think there should no code in .aspx page have create gridview in codebehind. i have code 1 gridview in 1 panel.. define grid view in html page , populate code behind. here code that.. can 1 please me multiple gridviews... this on .aspx page <asp:gridview id="gridview1" runat="server" autogeneratecolumns="false" allowsorting="true" cellspacing="2" onsorting="gridview1_sorting" width="100%" forecolor="white" gridlines="none" ondatabound="gridview1_databound1"> <columns> <edititemtemplate> <asp:label id="label1" runat="server" text='<%# eval("policyid") %>'></asp:label> ...

c# - Implementing "Fallback" Classes -

i have set of classes, each of need decide @ point of 2 or 3 approaches should use internally implement same functionality externally. ideally, should include fallback functionality, if approacha fails, falls through try approachb (and perhaps approaches c, d, etc.). until now, i've been using coding if (!success) { approachb code } . problem several later methods need aware of approach chosen , of them develop own if (methodchosen) { } else { } statements well. want address issue less unwieldy...except none of other options i've considered seems "wieldy". here 3 approaches thought of: implement static .create method decides of 2 derived classes create, 2 classes have interface backing them. disadvantage of you're writing lot of same code twice, , it's not creating "fallback" since forces decision-making done front in .create method. should work 9/10 times, there'll other 1/10 times want fallback kick in when primary has tried , failed. ...

ruby - help with a simple method -

hi i'm trying solve exercise https://github.com/alexch/learn_ruby i must write method should "multiplies 2 numbers" , "multiplies array of numbers". i'm fresh ruby , solved it, 1 method this: def multi(*l) sum = 1 l.flatten! if l.is_a? array l.each{|i| sum = sum*i} return sum end i'm sure there better ways, how can improve method? more ruby syntax :) the if l.is_a? array not necessary because way multi define, l array. the pattern result = starting_value xs.each {|x| result = result op x} result can written more succinctly using xs.inject(starting_value, :op) . so can write code as: def multi(*l) l.flatten.inject(1, :*) end if you're ok, calling method multi(*array) instead of multi(array) multiply array, can leave out flatten, well.

jquery Doing Simple Math? -

i have little div this: <div id="counter">2</div> i'd use jquery either subtract or add let 1, resulting in 3 or 1... is there way in jquery this? convert string int maybe? $('#counter').text(function(i,txt) { return parseint(txt, 10) + 1; }); example addition: http://jsfiddle.net/2ubmy/ example subtraction: http://jsfiddle.net/2ubmy/1/ to add check negative, this: $('#counter').text(function(i,txt) { var result = parseint(txt, 10) - 1; return (result > 0) ? result : 0; });

Ruby on Rails JSON.parse(object.to_json) doesn't return the original object -

it seems object this: #<course id: 1, name: "targeting triple negative breast cancer", description: nil, disclosure: nil, created_at: "2010-11-11 14:43:31", updated_at: "2010-11-11 14:43:31", picture: nil, course_reference_id: nil, authors: "lisa a. carey, m.d.", volumn_number: nil, publication_date: nil, expiration_date: nil, credits: 1, featured: false> i should able json.parse(course.to_json) , when try this, instead of returning original object, equivalent of course.new (an object nil attributes). when course.to_json get: "{\"attributes\":{\"name\":\"targeting triple negative breast cancer\",\"expiration_date\":null,\"created_at\":\"2010-11-11 14:43:31\",\"featured\":\"0\",\"publication_date\":null,\"updated_at\":\"2010-11-11 14:43:31\",\"id\":\"1\",\"disclosure\":null,\"volum...

c# - LINQ to Entities group-by failure using .date -

i trying linq group on date part of datetime field. this linq statement works groups date , time. var myquery = p in dbcontext.trends group p p.updatedatetime g select new { k = g.key, ud = g.max(p => p.amount) }; when run statement group date following error var myquery = p in dbcontext.trends group p p.updatedatetime.date g //added .date on line select new { k = g.key, ud = g.max(p => p.amount) }; the specified type member 'date' not supported in linq entities. initializers, entity members, , entity navigation properties supported. how can group date , not date , time? use entityfunctions.truncatetime method: var myquery = p in dbcontext.trends group p entityfunctions.truncatetime(p.updatedatetime) g select new { k = g.key, ud = g.max(p => p.amount) };

php - jquery check ip before doing rest of stuff -

hey all, have jquery script that's pretty fun game, can view here link text . now after play button clicked, send users ip via ajax see if matches ip stored site. if rest of action performed. i'm having trouble getting 1st ajax work. here's script. var hitcount = 0, misscount = 0; function isnumeric(n) { return !isnan(n); } $("#getit").click(function() { var hitcount = 0, misscount = 0; $('#hitcount').text(0); $('#misscount').text(0); /* ajax check ip goes here if successful below performed*/ $('#message').hide(100); var li = [], intervals = 0, n = parseint($('#mynumber').val()); var intervalid = -1; if (isnumeric(n)) { intervalid = setinterval(function() { li[intervals++ % li.length].text(math.random() > .1 ? math.floor(math.random() * (10 + n) + (n / 2)) : n).attr('class', ''); }, <?php echo $time ?>); } $('#randomnumber').empty(); (var = 0; <...

using jsp to check username and password -

hello i'm learning bit jsp , have problem code below. create 1 index.jsp file , try run eclipse or directly tomcat 6.0. error line " if (name.equals("user") && password.equals("1234")) ". error java.lang.nullpointerexception . glad advise. <?xml version="1.0" encoding="iso-8859-1"?> <!doctype html public "-//w3c//dtd xhtml 1.1//en" "http://www.w3.org/tr/xhtml11/dtd/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de"> <head> <title>practice</title> </head> <body> <h2>practice</h2> <h3>please enter name , password.</h3> <form method="post" action=""> <table> <tr><td style="text-align:center">name</td> <td><input type="text" name="name" size="80" /></td> </tr> ...

php - Identify date-related text in a longer message -

i'm writing script extract dates message , convert them timestamps. php's strtotime (similar unix's date -c 'some date' ) perfect this, recognizes kinds of dates, such as: 5pm today 2010-11-15 16:30 thursday 8:00 however, i'm having trouble finding dates in first place. example, in following string, i'll there dinner tomorrow @ 9:00pm i need isolate "tomorrow @ 9:00pm", that's part strtotime recognizes. is there regular expression or similar return me dates can parsed strtotime? the thing can think of date_parse . regular expression matches any format accepted strtotime huge. an example of date_parse: $str = "i'll there dinner tomorrow @ 9:00pm"; $parsed = date_parse($str); print_r($parsed); it output (i removed unimportant parts make result lighter): array ( [year] => [month] => [day] => [hour] => 21 // 9:00pm [minute] => 0 /...

android - Writing to an ImageView in code with Droid -

how go writing text imageview in class? so, if in main class, using intent, have this: setcontentview(r.layout.result); if (currenthour > 8 && currenthour < 22) { //write formatted text textbox in imageview is there simple line of code that? thanks! just read , answer ... http://developer.android.com/resources/articles/layout-tricks-merge.html ...

Java awt performance anxiety -

there program generates hundreds or thousands of moving particles onscreen @ once. after several hundred displayed, slowdown occurs. performance analyzed using netbeans profiler , 80% of time spend in jpanel's paint method...so algorithm optimization seems unlikely make noticeable difference. there can done or time think new platform? paint method looks this: public void paintcomponent(graphics g) { super.paintcomponent(g); setbackground(color.white); (int = 0; < gamelogic.getparticlearrsize(); i++) { g.setcolor(gamelogic.getparticlecolor(i)); g.filloval(gamelogic.getparticlexcoor(i), gamelogic.getparticleycoor(i), gamelogic.getparticlesize(i), gamelogic.getparticlesize(i)); } g.setcolor(gamelogic.getcurrpartcolor()); g.filloval(mousex - mouseovalradius, mousey - mouseovalradius, mouseovalsize, mouseovalsize); g.setcolor(gamelogic.getcursorcolor()); g.filloval(mouse...

c++ - Set DCB Fails When Attempting to Configure COM Port -

i'm trying write c++ mfc application uses serial port (e.g. com8). every time try set dcb fails. if can point out i'm doing wrong, i'd appreciate it. dcb dcb = {0}; dcb.dcblength = sizeof(dcb); port.insert( 0, l"\\\\.\\" ); m_hcomm = createfile( port, // virtual com port generic_read | generic_write, // access: read , write 0, // share: no sharing null, // security: none open_existing, // com port exists. file_flag_overlapped, // asynchronous i/o. null // no template file com port. ); if ( m_hcomm == invalid_handle_value ) { trace(_t("unable open com port.")); throwexception(); } if ( !::getcommstate( m_hcomm, &dcb ) ) { trace(_t("cserialport : failed comm state - error: %d"), getlasterror()); throwexception(); } dcb.baudrate = 38400; ...

asp.net - How to test functions returning data from a database -

say have function: public list<car> getfourwheeldrives() { return datacontext.cars.where(c => c.isfourwheeldrive == true).tolist(); } firstly it's kind of obvious i'm trying here. suggestions on how i'm doing this? improvements? so want unit test this. unit test? unit test isn't suppose touch database right? functional test? so write test [test] public void getfourwheeldrives_noparameters_returnalistofonlycarsthatarefourwheeldrives { assert.greater(datacontext.cars.where(c => c.isfourwheeldrive == false).tolist().count, 0); var cars = getfourwheeldrives(); assert.greater(cars.count, 0); assert.areequal(cars.count, cars.where(c => c.isfourwheeldrive == true).tolist().count); } so first assert i'm making sure cars aren't 4wd exist in database otherwise wouldn't valid test. second assert i'm making sure @ least 1 returned. third assert i'm making sure cars returned in fact 4wd. i know isn't test...

cpan - Perl WebService::Blogger -

i've been trying use perl module webservice::blogger (from cpan) connect blogger account, i'm having problem creating new object of webservice::blogger class. when call new constructor example given in documentation: webservice::blogger->new(login_id=>'username', password=>'password'); i error saying that: attribute (password) required. however, if save details in ~/.www_blogger_rc, works fine. once remove it, starts giving me error. ideas? i looked @ code, , appears bug in buildargs method of webservice::blogger. handles loading login information file, doesn't call base class buildargs handle parameters passed new . as result, webservice::blogger->new(login_id=>'username', password=>'password'); equivalent webservice::blogger->new(); , since buildargs discarded parameters. please report bug .

android activity - Activities are always collapsed in rehosted designer -

Image
i'm trying rehost designer, every time slap workflow designer: _workflowdesigner = new workflowdesigner(); // added ui here properties.content = _workflowdesigner.propertyinspectorview; _workflowdesigner.load(myworkflowinstance); where myworkflowinstance workflow defined in referenced assembly. have done magic register default activity metadata registered: new designermetadata().register(); and i've registered custom nativeactivities: public static void register(ienumerable<type> activitytypes) { // activitytypes custom nativeactivities // , workflows (root of system.activities.activity) var builder = new attributetablebuilder(); var attrgroups = x in activitytypes y in x.getcustomattributes(true).oftype<attribute>() group y x g select g; foreach (var typegroup in attrgroups) builder.addcustomattributes(typegroup.key, typegroup.toarray()); metadatastore.addattributetable(b...

Actual Android device not found adb devices -

i have written simple app , try out on samsung galaxy i9000. after trouble finding proper usb-driver have device show in device manager under android phone/android composite adb interface. running vista sp1 , phone samsung galaxy i9000 2.1-update1. the problem i'm having when running "adb servies" in cmd device list empty, , device not showing in eclipse. the phone in developer (debug) mode i have added android:debuggable="true" app in manifest-file i have tried several times kill , restart adb in cmd-prompt without result i have rebooted both phone , computer several times used usddeview remove previous drives before installing proper ones i ran following in commandprompt: adb kill-server set adb_trace=all adb nodaemon server then ran eclipse , got (never mind wierd sdk-path :p): c:\program files\jcreatorv4le\android\android-sdk-windows\tools>adb kill-server c:\program files\jcreatorv4le\android\android-sdk-windows\tools>set adb...

javascript - JSON documentation -

is there tool writing json specifications? i'm looking improve internal team's documentation capabilities, , @ same time generation validators (which throw couchdb view). http://json-schema.org/ also see : cerny.js (javascript) jsontools (java)

postgresql - Add_Index() Error using Rails ,PostGres and Windows xp -

i'm trying add index models, keep getting error. pg:error error:column "user_id" not exist :create index "index_users_on_user_id" on "users" ("user_id") class createusers < activerecord::migration def self.up create_table :users |t| t.references :role t.references :carrier t.string "first_name" t.string "last_name" t.string "user_name" t.string "hashed_password" t.string "user_salt" t.string "telephone" t.timestamps end add_index("users", "user_id") add_index("users", "role_id") add_index("users", "user_name") end def self.down drop_table :users end end you don't have anywhere column user_id in migration. automagical column rails creates called 'id'.

JQuery UI "drop" event does not fire? -

i have drag , drop interface jqueryui, , when user drags element 1 of containers , drops it, want display information selected item. $(document).ready(function() { $( ".element" ).draggable({snap: ".elementcontainer"}); $( ".elementcontainer" ).droppable({ drop:function(){ $("table").append('<tr><td class="elementcontainer ui-droppable"></td></tr>'); }}); }); so it's creating new element ui droppable class. question is, why won't fire "drop" event on newly created element? it won't fire because when run $(".elementcontainer").droppable(...) binds droppable widgets .elementcontainer elements exist at time , s you'll need run plugin again newly created elements class. something this: $(document).ready(function() { $( ".element" ).draggable({snap: ".elementcontainer"}); $.fn.binddroppable = function() { re...

php - Problems with <form> and Dynamically-generated links -

related directly post , having trouble implementing sound advice given @sean, because can see on page: http://www.onestopfasteners.com.au/checkout.php - have wrapped form tags around table element, form doesn't seem working, , nothing ever gets "post"ed either. i've changed code around abit experiment, haven't found solution, , no search anywhere has proven useful yet. i'd appreciate @ all. i'm baffled! thanks! p.s. thought maybe fact wrapping form elements around dynamically generated content why form isn't working, doesn't make sense me and, i've done before, can't it, can it? code: i know, it's long, apologies in advance. :) <?php // (c) code removed ;) problem solved - helped! ?> i think problem with: function submit() { document.myform.submit(); } try: function submit() { document.getelementbyid('ct_form').submit(); ...

iphone - NSString stringWithCharacters Unicode Problem -

this has got simple -- surely method supposed work -- i'm having kind two-byte-to-one-byte problem, think. the purpose of code generate string of 0 characters of length (10 minus number of digits tacked onto end). looks this: const unichar 0 = 0x0030; nsstring *zerobuffer = [nsstring stringwithcharacters:&zero length:(10 - [[nsstring stringwithformat:@"%i", photoid] length])]; alternate second line (casting thing @ address &zero): nsstring *zerobuffer = [nsstring stringwithcharacters:(unichar *)&zero length:(10 - [[nsstring stringwithformat:@"%i", photoid] length])]; 0x0030 address of numeral 0 in basic latin portion of unicode table. if photoid 123 i'd want zerobuffer @"0000000". ends 0 , crazy unicode characters along lines of (not sure how show) this: 0䪨 燱ܾë¿¿﹔ i'm assuming i've got data crossing character boundaries or something. i've temporarily rewritten dumb substring thing, seems more efficient....

algorithm - How to calculate the cost of calculations in CPU vs. cost of sending the data to GPU+performing calculations+getting data back? -

how calculate cost of calculations in cpu vs. cost of sending data gpu+performing calculations+getting data back? i can't see quantitative, objective way other profiling each technique , determining faster - assume time/speed mean "cost."

artificial intelligence - Training neural network for XOR in Ruby -

i trying train feedforward network work perform xor operations ruby library ai4r. however, when evaluate xor after training it. not getting correct output. has used library before , gotten learn xor operation. i using 2 input neurons, 3 neurons in hidden layer, , 1 layer output, saw precomputed xor feed forward neural network before. require "rubygems" require "ai4r" # create network with: # 2 inputs # 1 hidden layer 3 neurons # 1 outputs net = ai4r::neuralnetwork::backpropagation.new([2, 3, 1]) example = [[0,0],[0,1],[1,0],[1,1]] result = [[0],[1],[1],[0]] # train network 400.times |i| j = % result.length puts net.train(example[j], result[j]) end # use it: evaluate data trained network puts "evaluate 0,0: #{net.eval([0,0])}" # => evaluate 0,0: 0.507531383375123 puts "evaluate 0,1: #{net.eval([0,1])}" # => evaluate 0,1: 0.491957823618629 puts "evaluate 1,0: #{net.eval([1,0])}" # => eval...

facebook - Selecting non-standard tag with jQuery -

is there way use jquery select <fb:like href="stackoverflow.com"></fb:like> tag? you can escape : in selector, this: $("fb\\:like") you can test out here . though...i can't guarantee work in every browser.

c# - customvalidator onServerValidate not firing -

i have radio button list , text box both validation. <asp:radiobuttonlist id="member" runat="server" repeatdirection="horizontal"> <asp:listitem>yes</asp:listitem> <asp:listitem>no</asp:listitem> </asp:radiobuttonlist> <asp:requiredfieldvalidator id="unionvalidator" runat="server" controltovalidate="member" errormessage="required" /> required if member == "yes" <asp:textbox runat="server" id="union"></asp:textbox> <asp:customvalidator id="customvalidator1" runat="server" validateemptytext="true" onservervalidate="unionvalidate" errormessage="your current union required" /> my servervalidate doesn't fire @ all. public void unionvalidate(object source, servervalidateeventargs args) { if (member.text == "yes" && union.text.trim() == ...

c# - How do I transfer ViewModel data between POST requests in ASP.NET MVC? -

i have viewmodel so: public class producteditmodel { public string name { get; set; } public int categoryid { get; set; } public selectlist categories { get; set; } public producteditmodel() { var categories = database.getcategories(); // made-up method categories = new selectlist(categories, "key", "value"); } } then have 2 controller methods uses model: public actionresult create() { var model = new producteditmodel(); return view(model); } [httppost] public actionresult create(producteditmodel model) { if (modelstate.isvalid) { // convert model actual entity var product = mapper.map(model, new product()); database.save(product); return view("success"); } else { return view(model); // fails } } the first time user goes create view, presented list of categories. however, if fail validation, view sent them, except time categories ...

wrapper - jQuery: How to create element then wrap this around another existing element? -

so know how use .wrap , .wrapinner , .wrapall wondering how use quick creation syntax introduced in jquery 1.4 , wrap function together. basically want able use var targetul = $(this), // populated script maxwidth = 1400; // populated script $('<div />', { 'id':'wrap', 'css': { 'width': maxwidth, 'overflow':'hidden' } }).wraparound(targetul); kinda .appendto method works wrapping stuff… can done? thanks. targetul.wrap( $('<div />', { 'id':'wrap', 'css': { 'width': maxwidth, 'overflow':'hidden' } }) );

css - How to get an ExtJS ComboBox to display inline with text? -

i want following display in single line. have tried using styles float , display. show input <input type="text" name="filterop" id="filterop"/> inline. <script type="text/javascript"> new ext.form.combobox({ applyto: 'filterop', triggeraction: 'all', name: 'item', mode: 'local', lazyinit: true, displayfield: 'name', valuefield: 'id', forceselection: true, typeahead: true, inputtype:'text', fieldlabel: 'item selection', style: "display: inline-block", store: new ext.data.jsonstore({ autoload: true, url: 'reporting/json_report_filter_operators.jsp', root: 'rows', fields:['id', 'name'] }) }) </script> the simplest way override styles on page. ...

iphone - About memory management (spec for object create by Interface builder) -

i have question on free object memory in object c . for example code : @interface mycell : uitableviewcell { iboutlet uiview* bindview; iboutlet uiview* unbindview; } as see, 2 object , first assign , bind via interface builder , no in dealloc code , try free avoid memory leak . follow: - (void)dealloc { [bindview release]; bindview = nil; [unbindview release]; unbindview = nil; [super dealloc]; } so, think free all..... code execute , strange because second object unbindview never assign in code or ib, seem should nil, code still can executed no nil pointer exception throws .... my question, whether free object code above right , best way ? because bindview never been retained , think should handle cocoa ? next question unbindview , know object weak language, rule type variable usage ? thanks answers ! because second object unbindview never assign in code or ib, seem should nil, code still can executed no nil point...

Rails 3.0.2 Array#join HTML Safe? -

i have rails gem uses snippet like: components = [] components << label_for(attribute) components << ... components << text_field(attribute) return components.join the gem worked fine in rails 3.0.1, escapes (renders text in browser) html after updating rails 3.0.2. doing wrong? thanks. as @sj26 points out, either use rails built-in helper: <%= safe_join(components) %> or use rails_join gem make array#join html-safe aware, in case original code work is.

python - Django in Eclipse, laying out the project -

any "best practice" or "recommended" project layouts django project in eclipse? in eclipse looks this: project name -src --project name ---__init__.py ---manage.py ---settings.py ---urls.py ---apps ----app1 -----__init__.py -----forms.py -----urls.py -----views.py -----templates ------app1 -------index.html i'm not sure how layout, repetition of app name in templates folder. think did way make url configs behave, i'm new django place improvement. you know can create django project without src folder in eclipse think cleaner; when want create new django project widget ask name of project in bottom can disable create default "scr" ... . and don't think it's idea put django application did can put related application in folder not of them , , template think have choice put 1 template directory in level settings.py can have same structure apps or put template directory in each application prefer first 1 this: project_n...

asp.net mvc - determine when a partialview is going to be rendered as fullview... and hijack the rendering - MVC -

so have page this: .... now updating comments div using ajax , all. now, if user has javascript disabled, actionresult "comments" still ends returning partialview except time replaces entire page instead of div "commentsdiv". ruins formatting of page, because masterpage gone. there lot of such scenarios throughout website. can universally specify if partialview rendered full view, something!! (like maybe redirect dummy full-page masterpage referencing partialview). other approaches? note can't "isajaxrequest",because first time page loads, won't ajax request, actionresult still supposed return partialview. if have understood comment isajaxrequest, first time page loads, want full view, not partial... pretty canonical reason using isajaxrequest. so need is: if (request.isajaxrequest) { return view(); } else { return partialview("mypartial"); } the other scenario can think of using redirect, eg, if i...

c# - How to access store certificates from client machine -

i using web application in need sign document @ client end.client should select certificate , able sign certificate.i using code access store certificates:- x509store st = new x509store(storename.my, storelocation.localmachine); but returning certificates server. how access certificates @ client machine. well, might have small conceptual problem: client has send server. if using web app, should think on using activex control or java applet... the code same have there. keep in mind should not send client's private key, , if signing or cryptographing something, should done in client.

objective c - Determine if a view is inside of a Popover view -

we have common views use in our application in many locations inside of uinavigationcontrollers . uinavigationcontroller s inside of popover views. views put nav controllers modify navigation controller's toolbar buttons and, in cases, use custom buttons we've created. need able figure out uiviewcontroller if view inside of popoverview can display correctly colored buttons. we can navigation controller reference uiviewcontroller, using uiviewcontroller.navigationcontroller , there doesn't seem finding uipopovercontroller . does have ideas how this? thanks! i looking way determine wether or not view being displayed in popover. came with: uiview *v=theviewinquestion; (;v.superview != nil; v=v.superview) { if (!strcmp(object_getclassname(v), "uipopoverview")) { nslog(@"\n\n\nim in popover!\n\n\n\n"); } basically climb view's superview tree looking see if of superviews uipopoverview. 1 c...

c++ - How to address C4191 warning around calls to GetProcAddress with FARPROC? -

recently tried use /wall visual c++ option enable warnings , found following code: typedef bool ( winapi * tiswow64processfunction )( handle, bool* ); tiswow64processfunction iswow64processfunction = reinterpret_cast<tiswow64processfunction> ( ::getprocaddress( kernel32dllhandle, "iswow64process" ) ); spawned c4191 : warning c4191: 'reinterpret_cast' : unsafe conversion 'farproc' 'tiswow64processfunction' calling function through result pointer may cause program fail if use c-style cast same warning appears mentions "type cast" instead of "reinterpret_cast". the same warning repeated case call getprocaddress() , convert return value usable function pointer. how address these warnings? need make alterations code? you casting farproc (function pointer no args) function pointer args. hugely dumb thing result in stack corruption. now turns out getprocaddress() doesn't return farproc , know yo...

query django date -

in ,models have class pick: t1 =models.datetimefield(auto_now_add=true) in views. the date variable in format s="2010-01-01" how o query date pick.objects.filter(t1=date(s)) datetime.date() expected arguments datetime.date(year, month, day) , creating date object s won't work. can use date string directly in filter picks_at_date = pick.objects.filter(t1=s) or when try find before or after date picks_before_date = pick.objects.filter(t1__lt=s) or picks_after_date = pick.objects.filter(t1__gt=s). django's "making queries" docs @ retrieving specific objects filters has examples on making queries date fields well.

c - Are pointers of the same size? -

possible duplicates: are there platforms pointers different types have different sizes? are data pointers of same size in 1 platform? sizeof(bucket *) same sizeof(int *) ,right? btw,is char arr[]; valid in c90? i believe there no requirement pointers same size. requirement object pointers can stored in void * , when cast void * , they'll same, , function pointers, if cast type of function pointer , again, same. (casting function pointers void * not guaranteed work. sorry if indicated otherwise.) in practice, think time you'll find pointers of different sizes if care c++'s member-function pointers, or work on more obscure architecture. in c90, char arr[]; valid way pre-declare global array of to-be-determined length. note char arr[] incomplete type, have declare before can use sizeof . it's not valid way in c99, make flexible array members.

javascript - Firefox 3.6 video full screen control -

firefox supports full screen mode on video html5 tag. ( right click on movie .. ) is there way create control ( html tag ) play/pause example ( using js ) ? <script> function play(){ var video = document.getelementbyid('movie'); var play = document.getelementbyid('play'); play.addeventlistener('click',playcontrol,false); function playcontrol() { if (video.paused == false) { video.pause(); this.firstchild.nodevalue = 'play'; pausecount(); } else { video.play(); this.firstchild.nodevalue = 'pause'; startcount(); } } } basically need creating function (triggered fullscreen button) in assign position: absolute, , higher z-index video wrapper the assign both video , video wrapper width , height : 100% (or fixed size if prefer) probably best way achieve behaviour defining class (e.g. fullscreen) , assign container, like .fullscreen { position : absolute; z-index : 1000; width ...

html - vertical centering in gwt -

how vertical centering in gwt using vertical panel.. or pls sugest me there way doing vertical cetering if want directly use verticalpanel code, need use setverticalalignment(hasverticalalignment.align_middle) you can use uibinder approach <g:verticalpanel verticalalignment='align_middle' horizontalalignment='align_center' width="100%" height="500px"> <g:cell></g:cell> </g:verticalpanel> take devguideuipanels examples , documentation

c++ - XML replacement -

i have server application rewriting in c++ , used use xml send data client/from client. have found real pain implement xml, using existing libraries. seems counter intuitive @ times , c++ library i've used seems overly complicated. i wondering if knew better ways send on data client server , in simpler , more intuitive way parsing xml. data consists of basic types. i thinking maybe use struct needed data types , send on raw socket. i have wasted time on this, it's unreal. i'd try json or google's protocol buffers see if work you.

flex - How to use fonts in external SWF files -

what flex app, uses fonts available in external swf. have succeded far is: to create class hat holds embedded font: package { import flash.display.sprite; public class _arial extends sprite { [embed(source='c:/windows/fonts/arial.ttf', fontname='_arial', unicoderange='u+0020-u+002f,u+0030-u+0039,u+003a-u+0040,u+0041-u+005a,u+005b-u+0060,u+0061-u+007a,u+007b-u+007e')] public static var _myarial:class; } } compiled swf following command: mxmlc.exe -static-link-runtime-shared-libraries=true _arial.as when try load font flex app, fails following error message: argumenterror: error #1508: value specified argument font invalid. @ flash.text::font$/registerfont() @ valueobjects::fontloader/fontloaded()[c:\documents , settings\nutrina\adobe flash builder 4\flex_pdf\src\valueobjects\fontloader.as:33] this code try load swf file: package { import flash.display.loader; import flash.display.sprite; import fl...