Posts

Showing posts from May, 2011

c# - The calling thread must be STA, because many UI components require this in WPF -

my scenario: void installer1_afterinstall(object sender, installeventargs e) { try { mainwindow objmain = new mainwindow(); objmain.show(); } catch (exception ex) { log.write(ex); } } i got error "the calling thread must sta, because many ui components require this" what do? normally, entry point method threads wpf have [stathreadattribute] set threadmethod , or have apartment state set sta when creating thread using thread.setapartmentstate() . however, can set before thread started. if cannot apply attribute entry point of application of thread performing task from, try following: void installer1_afterinstall(object sender, installeventargs e) { var thread = new thread(new threadstart(displayformthread)); thread.setapartmentstate(apartmentstate.sta); thread.start(); thread.join(); } private void

delphi - How to return WideString from COM server? -

this interface @ _tlb.pas file // *********************************************************************// // interface: itmycom // flags: (256) oleautomation // guid: {d94769d0-f4af-41e9-9111-4d8bc2f42d69} // *********************************************************************// itmycom = interface(iunknown) ['{d94769d0-f4af-41e9-9111-4d8bc2f42d69}'] function mydrawws(a: integer; b: integer): widestring; stdcall; end; this looks @ os windows [ odl, uuid(d94769d0-f4af-41e9-9111-4d8bc2f42d69), version(1.0), helpstring("interface tmycom object"), oleautomation ] interface itmycom : iunknown { bstr _stdcall mydrawws( [in] long a, [in] long b); }; function in com server looks as function ttmycom.mydrawws(a, b: integer): widestring; begin result := widestring(inttostr(a+b)); end; in com client i`m calling function edit1.text := string(mycom.mydrawws(1,1)); and error first chance exception @ $75a9fbae. exception class eaccessviolation message 'acces

java - Error with foreign key -

i'm having problems creating mysql table within java program. can't create table... errno: 150 here code: string url="jdbc:mysql://192.168.1.128:3306"; connection con=(connection) drivermanager.getconnection(url,user,pass); statement stmt=(statement) con.createstatement(resultset.type_scroll_sensitive, resultset.concur_updatable); statement stmt1=(statement) con.createstatement(resultset.type_scroll_sensitive, resultset.concur_updatable); string mysql_new_table=("create table if not exists dbtest.t_ajpes_tr " + "(" + "row_count int primary key auto_increment," + "rn char(15),sspre char(5),reg char(5),eno varchar(10),davcna varchar(15),ime varchar(75),priimek varchar(75),log_id int,index l_id (log_id),foreign key(log_id) references t_ajpes_tr_log(id_log) on delete cascade on update cascade) engine = innodb;"); string mysql_log = ("create

Alpha transparency in indexed-png images -

here image: gradient1 http://adamhaskell.net/img/gradient1.png image simple black-to-transparent gradient saved in full rgba png. here same image, converted indexed-alpha png gimp (photoshop produces same result) gradient2 http://adamhaskell.net/img/gradient1b.png can see, gradient half-opaque, half-transparent. here same image again, time converted indexed-alpha png php script wrote: gradient3 http://adamhaskell.net/img/gradient1c.png so question is: why gimp , photoshop unable support partial transparency in indexed images, when php script shows such image can created no problems? there "wrong" image pallette contains alpha information? more programming-related question: transparency in last image work in internet explorer 6? another option besides fireworks pngquant , command line application convert rgba png indexed png transparency. i found this post talks more how use it. ie6 , earlier in windows not support variable transparency pngs w

sql - MySQL transaction and triggers -

hey guys, here 1 not able figure out. have table in database, php inserts records. created trigger compute value inserted well. computed value should unique. happens time time have exact same number few rows in table. number combination of year, month , day , number of order day. thought single operation of insert atomic , table locked while transaction in progress. need computed value unique...the server version 5.0.88. server linux centos 5 dual core processor. here trigger: create trigger bi_order_data before insert on order_data each row begin set new.auth_code = get_auth_code(); end; corresponding routine looks this: create function `get_auth_code`() returns bigint(20) begin declare my_auth_code, acode bigint; select max(d.auth_code) my_auth_code orders_data d join orders o on (o.order_id = d.order_id) date(now()) = date(o.date); if my_auth_code null set acode = ((date_format(now(), "%y%m%d")) + 100000) * 10000 +

c# - How to store formatted snippets of Microsoft Word documents in sql server -

i need extract formatted text snippets of word document , store inside sql server table, later processing , reinsertion in word document using c#. i've had @ word dom , seems need use combination of document.load(), document.save() , range.copy(), range.paste() methods create file each snippets load db. isn't there easier (more efficient way)? by way code snippets can hidden text , thinking storing snippets rtf. finally got use aspose.words .net extract code snippets word file i'm interested in , store them rtf: // insteresting code snippets (in case text runs // style "tw4winmark") document sourcedocument = new document(filename); var runs = sourcedocument.getchildnodes(nodetype.run, true) .select(r => r.font.stylename == "tw4winmark").tolist(); // store snippets temporary document // read aspose documentation details document document = new document(); if (runs.count > 0) { nodeimporter nodeimporter = new nodeimpor

shell - How linux Os let applications read from pipe -

i confused how linux let application read pipe "cat /etc/hosts | grep 'localhost'". know in independent program fork child , communicate pipe between each other. 2 independent program communicating pipe don't know how. in example "cat /etc/hosts | grep 'localhost'" how grep know file descriptor should read input "cat /etc/hosts". there "conventional" pipe provided os, let grep know input? want know mechanism behind this. grep in example gets stdin. shell's responsibility call pipe(2) create pipe , dup2(2) in each of fork(2) children assign end of pipe stdin or stdout before calling 1 of exec(3) functions run other executables.

iphone - How to get an NSDate from a specific time zone and perform calculations based on that date -

i have been trying wrap head around nsdate , nscalendar , nsdatecomponents , nstimezone , , nsdateformatter . nsdate , nstimezone , nsdateformatter pretty straightforward. other classes not. i want current eastern time (the actual date/time in est @ moment code run). then want advance date 1 month, taking account daylight savings may (or may not be) in effect. from understand, adding 84600 improper way this, wrong. can please post example of how this? it's pretty easy: nsdate *now = [nsdate date]; nsdatecomponents *onemonth = [[[nsdatecomponents alloc] init] autorelease]; [onemonth setmonth:1]; nscalendar *calendar = [nscalendar currentcalendar]; nsdate *onemonthfromnow = [calendar datebyaddingcomponents:onemonth todate:now options:0]; nsdateformatter *df = [[[nsdateformatter alloc] init] autorelease]; [df settimezone:[nstimezone timezonewithname:@"america/new_york"]]; [df setdatestyle:nsdateformattermediumstyle]; [df settimestyle:nsdateforma

pathauto - What's the difference between "Update URL alias" and "Update automatic nodetitles" in Drupal? -

these options appear on admin page /admin/content/node in "update options" drop-down. the url aliasses fake addresses, while page may stored @ /node/13 alias makes can see page @ /this-website-is-cool the automatic nodetitles option related seperate module, " automatic nodetitles " module, entirely unrelated

vb.net - API for Determining if App is Running on Citrix or Terminal Services -

i'm looking api/function can call determine if software running on citrix, terminal services, or stand-alone pc. optimally, work this: select case apiwhatsystem.type.tostring case "citrix" bcitrix = true case "ts" bterminalservices = true case "pc" bpc = true end select i prefer worked api call opposed looking @ in registry we're having more , more customers locking down registry. thanks. according to: http://forums.citrix.com/message.jspa?messageid=1363711 can check sessionname environment variable. another simpler way read system environment variable "sessionname". if exists , starts "ica" you're running within citrix session. if starts "rdp" you're running within rdp session. i tested pc , locally get: c:\>echo %sessionname% console while remotely got c:\>echo %sessionname% rdp-tcp1 so seems might easy route go, otherwise sounds checking re

user interface - How to make a simpe UI for android? -

the ui want below: ------------------------------+ head|btn1|btn2|btn2 | ------------------------------- content | content | | | | | | | | | | | ------------------------------| foot|btn3|btn4|btn5 | ------------------------------| anyone know how design xml ui? this type of xml layout you'll looking for: <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <linearlayout android:id="@+id/header" android:layout_width="fill_

c# - Directory.CreateDirectory strange behaviour -

i have windows service runs separate thread function may do if (!directory.exists(tempupdatedir)) { directoryinfo di = directory.createdirectory(tempupdatedir); di.refresh(); eventlog.writeentry("downloader", string.format("debug: trying create temp dir:{0}. exists?{1},{2}",tempupdatedir, directory.exists(tempupdatedir), di.exists)); } which not throw exceptions, directory.exists says true (inside if block) , yet there no such directory on disk, when explorer. i've seen directory created couple of times, of time directory isn't created, no exceptions thrown either. (this service runs under local system) later on service starts program using process class , exits. program suppose work files, copy them created directory, doesn't either. code has problems on windows 2003 server. what the....????????????? my guess tempupdatedir relative directory name, , doesn't refer think do

c++ - Async FTP Library -

is there cross platform , asynchronous ftp client library c or c++? thanks. what libcurl ? it's well-known, widely-used, , supports async ftp. imagine it's cross-platform well. as bonus, it's smaller library link against than, e.g., of qt.

java - Converting System.currentTimeMillis() into the current, readable time -

hey - there way use system.currenttimemillis(); have convery number basic output hh:mm in droid? i using sample code: toast.maketext(this, string.valueof(system.currenttimemillis()), toast.length_long).show(); that outputs current time in ms since epoch. there has got better way rather convert large number , display current time right? simpledateformat timingformat = new simpledateformat("hh:mm"); timingformat.format(new date());

ios - Array of NSManagedObject attributes -

i'd array of attributes nsmanagedobject can use kvo export them. can create array manually , iterate through it, however, i'd list automatically, iterate. an nsmanagedobject has entity associated it. use nsentitydescription 's -attributesbyname , -relationshipsbyname . you'll dictionary each of methods. ask dicts -allkeys .

Wix: Deploying a file in multiple directories being detected at runtime -

this related wix: i have situation in have deploy file multiple directories values being fetched registry. these directories 1 many. and don't want create many directory entries values determined @ runtime. can call custom action in loop detecting target directories , setting-up our target folder values? i know can such copying inside custom action. i'm looking way via wix entries. i reading duplicatefiles action not getting proper methodology achieve goal. thanks lot the wix element copyfile maps duplicatefiles action. can use appsearch set properties , use copyfile duplicate file directory. duplicatefiles smart enough not if property null. if number of copies known when create installer can that. if think it's going somehow more dynamic @ runtime, can write custom action emits temporary rows duplicatefile table way duplicatefiles , removeduplicatefiles still heavy lifting. you can use principals described @ dynamic windows installer ui .

Replace wordA to wordB in a txt and then save it in a new file. MATLAB -

how write function take in following: filename: (a string corresponds name of file) worda , wordb: both 2 strings no space the function should this: a- read txt file line line b- replace every occurrence of worda wordb. c- write modifified text file same original file, preprended 'new_'. instance, if input file name 'data.txt', output 'new_data.txt'. here have done. has many mistakes got main idea. please find mistake , make function work. function [ ] = replacestr( filename,worda, wordb ) % replace worda wordb in txt , save in new file. newfile=['new_',filename] fh=fopen(filename, 'r') fh1=fgets(fh) fh2=fopen(newfile,'w') line='' while ischar(line) line=fgetl(fh) newline=[] while ~isempty(line) [word line]= strtok(line, ' ') if strcmp(worda,wordb) word=wordb end newline=[ newline word ''] end newline=[] fprintf('fh2,newline') end fclose(fh) fclose(fh2) end you can re

rendering - Simple volume ray casting -

the question might simple, realize answer may not be. keep clear possible. can explain basic idea volume ray casting technique in 3d volume rendering. cheers, timo this reference presents reasonable introduction simple raycasting link . concepts (ray-plane intersections, etc) can extended volume ray casting link . to summarize, ray cast through volume , accumulates color each intersection meets criteria. example, each voxel along ray possessing value > 128 might contribute small percentage of opacity desired rgb color. degree of opacity weighted, (voxel_value - 128)/127 might suitable weighting function in simplified case (assuming negative values handled appropriately). scheme represent proportional, thresholded transfer function. rendering, pixel associated ray assigned color determined summed opacities encountered along path. (this front-to-back alpha blending - other methods exist.) other transfer functions exist, well: functions might weight gradients

c - Eclipse + CDT + Cygwin: How do you fix the "Multiple targets" bug? -

update 1: original post long , obscured real problem. have discovered causing "multiple targets" bug when make called. update 2: found out 'multiple targets' bug caused gnu make version 3.8.1 (see here1 , here2 ). gnu make 3.8.1 current gnu make released cygwin. summarize link: old v3.8.0 handled windows paths fine , newer v3.8.1 reports errors windows paths (maybe it's passive aggressive jab fsf?). when start new project in eclipse+cdt+cygwin w/o external includes/libraries, works fine me. as try use external include/library "multiple targets" bug. here steps needed reproduce bug on windows+eclipse+cdt+cygwin: project project properties --> c/c++ build --> settings --> tool settings --> cygwin c compiler --> includes --> include paths (-i) -- > add button --> pick directory --> "c:\dir1\dir2" i hit build. it builds no errors first time. i hit build again... build errors "multiple targets. st

java - How can I show different markers on a map? -

i displaying markers on map. not sure how can specify different drawable resource different markers? i show green pin if locations distance < 50, etc. etc. pin = getresources().getdrawable(r.drawable.pushpin); itemizedoverlay = new myitemizedoverlay(pin, mapview); (record element : list) { geopoint point; overlayitem overlayitem; double lat = double.parsedouble(element.getlatitude()); double lng = double.parsedouble(element.getlongitude()); double locationdistance = double.parsedouble(element.getlocationdist()); geopoint.add(new geopoint((int) (lat * 1e6), (int) (lng * 1e6))); listofoverlays = mapview.getoverlays(); point = new geopoint((int) (lat * 1e6), (int) (lng * 1e6)); log.i("deep", "deep " + point); overlayitem = new overlayitem(point, "", element.gettitle()); if(locationdistance < 5

javascript - Changing image in jQuery -

i new jquery , may question basic. implementing expandable panel in jquery , above have image of + when clicked panel expand. want change image - when panel expanded. want change + image - once + clicked. below code plz help. <script type="text/javascript"> $(document).ready(function () { $('#addimage').click(function () { $('#pbody').slidetoggle('slow'); }); }); </script> <asp:panel id="pbody" runat="server"> duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur </asp:panel> </div> </form> the jquery should this: <script type="text/javascript"> $(document).ready(function () { $('#addimage').click(function () { $('#pbody

Jquery Extract URL from Text -

i need extract url text using jquery. lets have sowhere on page following textarea code <textarea rows="20" name="textarea" style="width:100%;"> @techreport{blabl, blabla = {}, url = {http://server.com/thepdf.pdf}, wrongurl ={http://server.com/thepdf2.pdf}, blablabla = 1998, blablablabla= {blablablablabla}} </textarea> i need url, , url contents - not wrongurl. update: has same structure , need extract once , has "url = {" in front of it. how this $(document).ready(function() { $('#click').click(function(){ var 1 = document.getelementbyid('one'); one.value.match(/url ={([^}]*)}/,""); alert( regexp.$1); }) }) or runnable demo http://jsfiddle.net/peps7/10/ oops, bit late game ammended example , jsfiddle show url

iphone - UIImagePNGRepresentation and masked images -

i created masked image using function form iphone blog: uiimage *imgtosave = [self maskimage:[uiimage imagenamed:@"pic.jpg"] withmask:[uiimage imagenamed:@"sd-face-mask.png"]]; looks in uiimageview uiimageview *imgview = [[uiimageview alloc] initwithimage:imgtosave]; imgview.center = cgpointmake(160.0f, 140.0f); [self.view addsubview:imgview]; uiimagepngrepresentation save disk : [uiimagepngrepresentation(imgtosave) writetofile:[self finduniquesavepath] atomically:yes]; uiimagepngrepresentation returns nsdata of image looks different. the output inverse image mask. area cut out in app visible in file. area visible in app removed. visibility opposite . my mask designed remove face area in picture. uiimage looks right in app after save on disk, file looks opposite. face removed else there. please let me know if can help! i had exact same issue, when saved file 1 way, image returned in memory exact opposite. the culprit & solutio

design patterns - jQuery hasclass structure -

see link: http://james.padolsey.com/jquery/#v=1.4&fn=jquery.fn.hasclass var classname = " " + selector + " "; .... (" " + this[i].classname + " ") many times in career i've had uses functions trim whitespace, have never seen reason add whitespace. purpose of empty strings being prepended , appended these variables. say have element classes foo , foobar , adding spaces @ start , end, ensures have spaces sourrding name of each class. allows search " foo " , avoid matching foobar . off: moved answer question marked answered.

Tutorials on optimizing non-trivial Python applications with C extensions or Cython -

the python community has published helpful reference material showing how profile python code, , technical details of python extensions in c or in cython . still searching tutorials show, however, non-trivial python programs, following: how identify hotspots benefit optimization conversion c extension just importantly, how identify hotspots not benefit conversion c extension finally, how make appropriate conversion python c, either using python c-api or (perhaps preferably) using cython. a tutorial provide reader methodology on how reason through problem of optimization working through complete example. have had no success finding such resource. do know of (or have written) such tutorial? for clarification, i'm not interested in tutorials cover only following: using (c)profile profile python code measure running times using tools examine profiles (i recommend runsnakerun ) optimizing selecting more appropriate algorithms or python constructs (e.g., sets membe

.net - Update code to use Linq -

are there tools analyze code , suggest rewrites use linq? resharper includes "upgrade linq" functionality, i've never used it, may useful: http://www.jetbrains.com/resharper/whatsnew/index.html#code_analysis

ios4 - I need to scroll a background image larger than the screen size and make it loop endlessly -

i writing ipad app have locked orientation landscape mode for. want have png file 100 pixels high 4 times width of ipad screen. what want background image shown on screen automatically begin scrolling on timer. have made sure start , end parts of image match up. once end of image reached, start bit show again. image should scroll along either @ 1 pixel movements or larger jumps if slow. i stuck looking example code show how show this. it not game writing not want use opengl or fancy. the examples have looked @ far not after. can simplify , state stuck on.. lets load image memory 1000 pixels wide 100 in height. can show me few lines of code let me cut out rectangle begins 200 pixels across x axis larger image , rectangle 100 100 pixels. how cut rectangle out , show on screen - speed not important stated before. i can work out scrolling part myself (i hope) , post here later.. i thinking along lines of cgcontext type commands despite looking @ examples , @ docs st

branch - How can I download only the necessary parts of a remote project in Git? -

if working on large remote repository , want restrict download few branches working on, how configure git-clone command, assuming right command in case? if you're working on 2 branches in 2 separate directories, can set 1 clone of other: git clone http://remote/repo.git branch-a git clone branch-a branch-b then, fix origin remote in branch-b : cd branch-b git remote add origin http://remote/repo.git (you may have remove previous origin first). way, local repository information shared hard links between 2 directories, saving space compared making 2 separate clones of remote. or, go buy 1 tb drive, they're cheap.

java - Uploading Large Text File Into A DB2 CLOB Field -

alrighty, i've been banging head against wall on 1 while, here goes... i'm writing java (1.5) program can upload large (200mb+) text files db2 clob column, have been running few issues. during research, several code examples suggested use preparedstatement method setcharacterstream() upload data clob field, giving me this: preparedstatement preparedstatement = connection.preparestatement("insert bookcovers values(?,?)"); file imagefile = new file("c:\\redbookcover.jpg"); inputstream inputstream = new fileinputstream(imagefile); preparedstatement.setstring(1," 0738425826"); preparedstatement.setbinarystream(2,inputstream,(int)(imagefile.length())); preparedstatement.executeupdate(); this fine, except fact setcharacterstream() method requires length value, specifying number of characters write field. in mind, limits number of characters can written clob field integer.max_value . doing little math, limit size of text fil

What is faster ASP.NET MVC or Ruby On Rails -

this not meant subjective or argumentative question. i investing time in learning asp.net , more asp.net mvc , curious how stacks competition. seeing far framework, , think icing on cake if shows rock solid speed have seen asp.net form sites. has done or seen fair comparisons or benchmarks? interested see how asp.net mvc stacks against other solutions such php mvc too. if compare raw execution .net faster php or ror. however, speed , overall performance of application depends on architecture. example: stackoverflow runs on less 10 servers. work company runs website pretty same hardware (+- 10 heavy work servers) way faster , has hundred times more access company's website. so in case how implement software other platform itself.

Rails, DEVISE - Preventing a user from changing their email address -

when user registers on app have confirm email, powered devise + rails 3. the email address defines user's permissions don't want user able change once registered. removed :email users.rb attr_accessible worked logged in user, user's can't register. what's right way handle this? users can't update email can register email using devise. thanks this perfect case custom validator. since rails3, easier before. class immutablevalidator < activemodel::eachvalidator def validate_each(record, attribute, value) record.errors[attribute] << "cannot changed after creation" if record.send("#{attribute}_changed?") && !record.new_record? end end class user < activerecord::base validates :email, :immutable => true end

Example of Asynchronous page processing in ASP.net webforms (.NET 2.0) -

can provide me simple example of asynchronous page processing in asp.net webforms 2.0 (i'm using vs 2010, new syntax lambdas ok)? i have long running requests don't want tying iis threads. for simplicity's sake, let's current code looks this: protected void page_load(object sender, eventargs e) { string param1 = _txtparam1.text; string param2 = _txtparam2.text; //this takes long time (relative web request) list<myentity> entities = _myrepository.getentities(param1, param2); //conceptually, iis bring new thread here can //display data after has come back. dostuffwithentities(entities); } how can modify code asynchronous? let's assume set async="true" in aspx page. edit i think figured out how i'm looking for. i've put example code in answer here . feel free point out flaws or changes can made. i asked folks on asp.net team. here's emailed response me, , now, you. all code ends

delphi - Is it possible to store a record in a ListBox's Item.Object property? -

i have record store each item add listbox. need make record class instead accomplish this? tserverrec = record id: integer; displayname: string; address: string; port: integer; end; procedure tmainform.popuplateservers; var server: tserverrec; begin server in fserverlist begin lbservers.addobject(server.displayname, server); end; end; no, store pointer record bit of typecasting. you're getting dynamic record pointer allocation, can bit of headache. why not make tserverrec object?

sqlite sqlite3_close() does not release the memory acquired -

we trying integrate sqlite in our application , trying populate cache. planning use in memory database. using first time. our application c++ based. our application interacts master database fetch data , performs numerous operations. these operations concerned 1 table quite huge in size. replicated table in sqlite , following observations: number of fields: 60 number of records: 1,00,000 as data population starts, memory of application, shoots drastically ~1.4 gb 120mb. @ time our application in idle state , not doing major operations. normally, once operations start, memory utilization shoots up. sqlite in memory db , high memory usage, don’t think able support these many records. now when close db using sqlite3_close(), memory not released? tried dropping table, still memory remains high? needs done sqlite releases acquired memory , memory of applications comes normal? forget sqlite part of question issue applies user process under linux. a process can grow dat

header - PHP buffer why \r\n -

i have few conceptual questions (all related, think) regarding following script, @ comments. script works fine. <?php ob_start(); // create string overflow browser buffer ...? $buffer = str_repeat(" ", 4096); // indicate new header / html content ...? $buffer .= "\r\n<span></span>\r\n"; ($i=0; $i<5; $i++) { echo $buffer.$i; ob_flush(); flush(); sleep(1); } ob_end_flush(); ?> first, why need send \r\n<tag>\r\n browser? assume has headers. second, why need html in middle? third, there many examples use 256 bytes instead of 4096. however, script doesn't work if use 256. these examples outdated, , number change again in future? //edit regarding source links this code gathered commentary in php.net sleep() function , the solution question . neither mentions why include \r\n . //edit regarding headers if don't add \r\n , html tag, , second set of \r\n , script not execute in chrome or safari (it dumps

jquery - How can I check the number of the item that was clicked -

let's have many items click event (all have same element name , possibly same class). <a>a</a> <a>b</a> <a>c</a> <a>d</a> then have method triggered on click event. how can check number of item clicked? in example if 'c' clicked should 3 answer. you can use .prevall() : $('a').click(function() { alert($(this).prevall('a').length + 1); }); or .index() : $('a').click(function() { alert($(this).index() + 1); });

iphone - Moving an object without animating it in an animation block -

i'm animating bunch of buttons move left of screen should magically move right of screen. calling: [nstimer scheduledtimerwithtimeinterval:0.20 target:self selector:@selector(movethebuttons) userinfo:nil repeats:yes]; in viewdidload. they animate quite happily left, animate right. want them disappear , reappear right-off-screen. because i'm new assumed since after commitanimations call wouldn't animate. think problem animations 'commit' after movethebuttons function returns, can't think of elegant (or standard) way around this. how move uibutton off screen without animating it, preferably still in movethebuttons function? as can infer, i'm new animations on iphone, if see other mistakes i'm making feel free give me pointers. -(void)movethebuttons{ nslog(@"movethebuttons"); [uiview beginanimations:@"mov-ey" context:clouda]; [uiview setanimationduration: .20]; [uiview setanimationcurve:uiviewanimationcurvelinear]; cloud

asp.net - Executing C# code from front end -

i have this <script language="c#" runat="server"> private string getuserimage(string userid) { membershipuser user = membership.getuser(); profilebase profile = profilebase.create(user.username); return profile.getpropertyvalue("photo").tostring(); } </script > it works fine, need create user object passing guid this membershipuser user = membership.getuser(new guid(userid)); what may cause. woks fine c# code behind. regards, tvr to call method page should public or protected. not private.

c - Trying to convert morse code to english. struggling -

i'm trying create function read morse code 1 file, convert english text, print converted text terminal, , write output file. here's rough start... #define total_morse 91 #define morse_len 6 void morse_to_english(file* inputfile, file* outputfile, char morsestrings[total_morse][morse_len]) { int = 0, compare = 0; char convert[morse_len] = {'\0'}, *buffer = '\0'; //read in line of morse string file // fgets(buffer, //then what? while(((convert[i] = fgetc(inputfile)) != ' ') && (i < (morse_len - 1))) { i++; } if (convert[i + 1] == ' ') convert[i + 1] = '\0'; //compare read-in string w/morsestrings (i = 48, compare = strcmp(convert, morsestrings[i]); //48 '0' < (total_morse - 1) && compare != 0; i++) { compare = strcmp(convert, morsestrings[i]); } printf("%c", (char)i); } i have initialized morsestrings morse code. that's function right now. not work, , i'm not sur

vb.net - Saving the result of a linq query to an XML file -

here original xml file <?xml version="1.0" encoding="utf-8"?> <configuration> <setup> <cap>33</cap> </setup> <setup> <cap>dd</cap> </setup> </configuration> in example below delete node cap equals 33 dim cap integer = 33 dim query = q in xelement.load(environment.currentdirectory & "\sample.xml").elements("setup") _ q.value = cap _ select q each q in query if cap = q.element("cap").value q.remove() next now how can write result of query .xml file? like... <?xml version="1.0" encoding="utf-8"?> <configuration> <setup> <cap>dd</cap> </setup> </configuration> well, can create new xdocument data. (c# syntax, converted...) xdocument doc = new xdocument(new xelement("configuration", query)); doc.save(fil

How to call next() on a resultset in clojure.contrib.sql? -

originally going ask why having problems calling (seq) on result set test emptiness, bit of research showed it's apparently because jdbc cursor hasn't moved anywhere. fine , dandy. there way call next() on resultset if don't know name? can bind symbol in clojure, haven't been able figure out how call method there. edit: in case it's not clear, i'm referring java resultset method next(), not clojure (next) edit#2 here's code snippet: (defn user-exists? [email] (with-connection db (with-query-results res ["select guid users email=?" email] (.next res) (seq res)))) (thanks on .next, btw...haven't done java interop yet) still, though, using (seq) throws nullpointerexception if query didn't return anything. i'm wondering if there's cleaner, idiomatic way this? res bound clojure sequence based on resultset each item map of result record output column names keywords in keys. can't underlying act

objective c - When should I add self before an object? is it save to always add it for view level objects? -

yesterday found needed add self object causing problem. i've been adding self few other objects today, compiles , seems work fine when do. i'm wondering if maybe shouldn't adding self ? if have ivar backing property myfoo , self.myfoor use property, whereas myfoo directly not. example property: @property(nonatomic, retain) myclass myfoo; self.myfoo = temp; retain temp myfoo = temp; not retain temp

How to find which device is attached to a USB-serial port in Linux using C? -

we making device , has 8 serial ports. runs on monta vista pro5 kernel. , working in c. suppose: device gets attached ttyusb0, ttyusb1 , ttyusb2. next device gets connected ttyusb3 , ttyusb4. how can know device gets attached port ?? ie ttyusb0 or ttyusb1 or on. there way directly query device , find port attached to. or, in c, open ttyusb0, query somehow , reply device ?? a rather complicated way: stat of, /dev/ttyusb0. device number. , search in /proc/bus/usb/devices , find vendor id or identify device. or: there way reserve ttyusb0,ttyusb1 , ttyusb2 1 device, ttyusb3 , on when plugged in ? way know device connected port. help please..... :) thanks in advance. nubin stanley you can use udev rules create symbolic links device: (these rules go in /etc/udev/rules.d/-name.rules -- @ udev documentation kernel=="ttyusb*", attrs{idvendor}=="<vendorid>", mode="0666", symlink+="mydev" you have specify vendor id and

ruby on rails 3 - Getting current_user error when using Ryan Bates' CanCan authorization plugin -

the portion of view applicable: <% @projects.each |project| %> <tr> <td><%= project.name %></td> <td><%= project.description %></td> <td><%= link_to 'show', project %></td> <% if can? :update, @project %> <td><%= link_to 'edit', edit_project_path(project) %></td> <% end %> <% if can? :destroy, @project %> <td><%= link_to 'destroy', project, :confirm => 'are sure?', :method => :delete %></td> <% end %> </tr> <% end %> models/ability.rb class ability include cancan::ability def initialize(designer) can :read, :all end end this error get: nameerror in projects#index undefined local variable or method `current_user' #<projectscontroller:0x000001016d62d8> extracted source (around line #18): 15:

javascript - Does VML have an equivalent to SVG's marker element? -

i'm working on project uses raphael render svgs chrome, firefox, , safari, , vml internet explorer. since raphael doesn't have built-in support svg marker elements, decided write plugin myself. got svg side working no problem, vml docs aren't giving me in finding way implement markers in vml. can point me in right direction? no. otherwise part of raphaël.

Fade in jquery load call -

i have basic question jquery. don't know how that's why i'm here looking help. code: edit: <a href="javascript:$('#target').load('page.html').fadein('1000');">link</a> as see want load page.html div called #target. want wich doesen't work make page.html fade in when loads. what's right way that? best regards first, should put javascript code outside element itself. simple do. makes html , javascript more comprehensible , allows more organised code. first, give a element id : <a href='#' id='loadpage'>link</a> then make call in script tag: <script type="text/javascript"> $(document).ready(function() { // when whole dom has loaded $('#loadpage').click(function(){ // bind handler clicks on #loadpage $('#target') .hide() // make sure #target starts hidden .load('page.html'

linux - How to get hard disk serial number using Python -

how can serial number of hard disk drive using python on linux ? i use python module instead of running external program such hdparm . perhaps using fcntl module? linux as suggested, fcntl way on linux. c code want translate looks this: static struct hd_driveid hd; int fd; if ((fd = open("/dev/hda", o_rdonly | o_nonblock)) < 0) { printf("error opening /dev/hda\n"); exit(1); } if (!ioctl(fd, hdio_get_identity, &hd)) { printf("%.20s\n", hd.serial_no); } else if (errno == -enomsg) { printf("no serial number available\n"); } else { perror("error: hdio_get_identity"); exit(1); } translated python on ubuntu 9.10, goes little this: import sys, os, fcntl, struct if os.geteuid() > 0: print("error: must root use") sys.exit(1) open(sys.argv[1], "rb") fd: # tediously derived monster struct defined in <hdreg.h> # see comment @ end of file v

get a method to return json in C# and asp.net MVC 2 or 3 -

i use json return allot of results when building website, find myself writing a lot of code this: return json(( s in searchresults select new { orderid = s.orderid, orderrealid = s.orderrealid, orderstatus = s.orderstatus, orderdate = s.orderdate, ordervenue = s.venuename + " - " + s.venuelocation + " (" + s.venuenumber + ")", orderstatustext = s.statusordervalue } ), jsonrequestbehavior.denyget); what this: public string resultstojson<t>(hashtable fields){ s in t select new { // loop through hash table } } and call function whatever ienumerable results have question on right lines here, best possible way makes no sense writing in mvc , oop keep rew

ios4 - setting Round scrollview in iphone -

i wants set rounded scrollview in iphone app. the same effect available on following link of apple store. http://itunes.apple.com/app/iretrophone-rotary-dialer/id284700702?mt=8 i have tried horizontal , vertical scrollview. possible set rounded scrollview or arch scrollview?? thanks in advance. idea appreciated. not current uiscrollview , , opening whole world of pain yourself. if want animation of scrolling rainbow colours make image-based animation. if need people scroll through scroll view that's going incredibly complicated build. you're best off creating looping image sequence run when user scrolls on image, or similar. can test gestures. won't able add other objects , subviews.

select next option in jquery selectmenu -

trying create button goto next option in selectmenu has $selectmenu assigned it. $('option:selected', 'select').removeattr('selected').next('option').attr('selected', 'selected'); works on standard html select menu not when has jquery $selectmenu assigned it. $('select#toolmenu').selectmenu({ style:'popup', width: 600, menuwidth: 600, maxheight: 400, format: addressformatting, change: function () { var val = this.value; window.location=val; } }); any idea how can control selectmenu? any appreciated... dan. you should use plugin value method. $("select#toolmenu").selectmenu("value", theindex); where theindex 0 based index of options please note if modifying @ runtime <option> list inside select have destroy , create plugin scratch. following function example ajax call update option list of select element $.ajax({

visual c++ - How come VC++ 2010 uses char buffer rather than wchar_t buffer to represent basic_filebuf<wchar_t>? -

it very strange me vc++ docs says: (at: http://msdn.microsoft.com/en-us/library/tzf8k3z8(vs.90).aspx ) "objects of type basic_filebuf created internal buffer of type char * regardless of char_type specified type parameter elem. means unicode string (containing wchar_t characters) converted ansi string (containing char characters) before written internal buffer. store unicode strings in buffer, create new buffer of type wchar_t , set using basic_streambuf::pubsetbuf() method. see example demonstrates behavior, see below." why? this guess may way handle common case (at least on windows) program's internals wchar_t (16-bit unicode characters) most/all text files outputs 8-bit ansi. most text files still seem ansi unless need otherwise, , many programs cannot cope unicode text files. i wonder if it's really ansi string or utf-8 string converts to...

python - In django, how can I retrieve a value from db into a custom field template? -

i using custom class on model provide image uploading, through app called django-filebrowser . # myapp/models.py class book(models.model): name = models.charfield(max_length=30) image = filebrowsefield("image", max_length=200, blank=true, null=true) ... the model uses filebrowser's custom field "filebrowserfield", adds link separate upload page (http://site/admin/filebrowser/browse/?ot=desc&o=date). i'd tweak custom form's template add "dir" parameter, so: (http://site/admin/filebrowser/browse/?ot=desc&o=date&dir=book1). book1, in case, retrieved "name" charfield of book. i know template want modify rendered filebrowser's fields.py, , there variable sets "dir" parameter, i don't know how fetch string value own model fields.py can set variable . have suggestions? found solution elsewhere, thought i'd share it: # models.py class book(models.model): name = models.char

Can Java String.indexOf() handle a regular expression as a parameter? -

i want capture index of particular regular expression in java string. string may enclosed single quote or double quotes (sometimes no quotes). how can capture index using java? eg: capture string --> class = ('|"|)word('|"|) no . check source code verification workaround : not standard practice can result using this. update: charsequence inputstr = "abcabcab283c"; string patternstr = "[1-9]{3}"; pattern pattern = pattern.compile(patternstr); matcher matcher = pattern.matcher(inputstr); if(matcher.find()){ system.out.println(matcher.start());//this give index } or regex r = new regex("yourregex"); // search match within string r.search("your string string"); if(r.didmatch()){ // prints "true" -- r.didmatch() boolean function // tells whether last search successful // in finding pattern. // r.left() returns left string , string before matched pattern int

.net - Should a GetEnumerator method still be idempotent when the class does not implement IEnumerable -

this question piggy backs of question raised regarding abusing ienumerable interface modifying object iterate on it. the general consensus no implements ienumerable should idempotent. .net supports compile time duck typing foreach statement. object provides ienumerator getenumerator() method can used inside foreach statement. so should getenumerator method idempotent or when implements ienumerable? edit (added context) to put context round suggesting when iterating on queue each item dequeued goes. additionally new objects pushed onto queue after call getenumerator still iterated over. it's not type idempotent - doesn't make sense; may mean immutable, that's not clear. it's getenumerator method typically idempotent. while i'd that's typically case, can envisage special cases makes sense have non-idempotent getenumerator method. example, you've got data can read once (because it's streaming web server won't service same r

bash - Awk regex for a string of exact length that ends in ":" -

i can't regex right: awk '$6 ~ /:${14}/ {print $6}' file i need print out 6th field if it's 15 characters long , ends ":". here's example: oafkq7xs001224: you need use --posix as: awk --posix '{ if ($6 ~ /^.{14}:$/) print $6}' file command in action from awk manual page: interval expressions available if either --posix or --re-interval specified on command line.

How to call Rest Webservice in iPhone using the following details -

i have url supports rest webservice https://xxx.yyy.zzz/abc/xyz.svc (added masking) the following operations supported: get create update getlist $metadata the following options supported: $top (-1 get’s records) $select $filter (only ‘eq’ , ‘and’ operators supported) now need test above operation in iphone. simple soap request creat nsurlrequest , set parameters , here things confusing, dont know how use these above operations , options. if know info please share thanks ok got know myself, the operations get, create , update , getlist supported server can used following way https://xxx.yyy.zzz/abc/xyz.svc/get here can replaced create, update , getlist. this url need used in nsurlconnection no header fields. may response xml/json needs parsed. now options https://xxx.yyy.zzz/abc/xyz.svc/get ()?$filter=spras eq 'd' , land1 eq 'ai' here using $filter option , get becomes get() i still not su

c - How to generate without repeat value in using two random () -

i generating random nos store matrix index row , column . different row , column index nos every time not repeat. time same value generating.how rectify problem. this written .. example 4 * 4 matrix. running loop , storing date int i; (i=0;i<6;i++) { row = arc4random() % 4 ; column = arc4random() % 4; cgfloat xoffset1 = (block.contentsize.width+350)+((block.contentsize.height-15)*column); fireblock.position = ccp(xoffset1,row*15); statement 1--- store column; statement 2--- store row; } with 16 different combinations, i'd write of them in array, shuffle array, select array. struct row_col_index { int row; int column; }; /* ... */ struct row_col_index all_combinations[4*4] = { {0, 0}, {0, 1}, {0, 2}, {0, 3}, {1, 0}, {1, 1}, {1, 2}, {1, 3}, {2, 0}, {2, 1}, {2, 2}, {2, 3}, {3, 0}, {3, 1}, {3, 2}, {3, 3}, }; shuffle(all_combinations); (int = 0; < 6; i++) {