Posts

Showing posts from February, 2011

cocoa touch - how to get uiview to talk to controller -

i'm relatively new objective-c , cocoa... i've been trying understand how correctly implement mvc pattern in cocoa/cocoa touch long time now... understand idea behind it; makes complete sense conceptually: model holds data, view user sees , can interact with, , controller acts bridge between two. view can't talk model, model can't talk view. got it. what doesn't make sense me how use mvc efficiently… if user can interact view, , interact (i.e. iphone app, user clicks/drags within subclass of uiview, triggering "touchesbegan" , "touchesmoved" methods, etc.), how view communicate these events controller? i've looked @ countless examples , forums online, have yet find simplified all-purpose way of achieving this… know how communicate controller through buttons, sliders, , other things can connect outlet, things don't have target-action mechanism, what's best way it? thanks in advance suggestions regarding do, or look. ...

php - preg_match check if string is surrounded in double or single quotes -

can tell me regex see if surrounded in double or single quotes. "this string" i want return false if quotes not present @ or not present @ start , end. preg_match('/^(["\']).*\1$/m', $string); will return 1 if string surrounded double quotes , 0 if not.

Question on URL redirection for wordpress blog -

so long had installed wordpress blog on domain points url this http://www.domainname.com/xxxx/blogs/ now have shifted new hosting, had set blog in following way http://www.domainname.com/blog the search engines have indexed earlier url see same when search in search engines. is there easy way redirect old url new url. thanks in advance karthik you have put .htaccess file , set redirection. .htaccess file in public_html. rewriteengine on rewriterule ^/xxxx/blogs/(.*)$ /blog/$1 [r] this should doo...

Custom Python Encryption algorithm -

hey, have been working on while, , can remebr brother stepped me through same alogorithm. basicly, adds ascii values of both characters key, , phrase. i can encrypt this: def encrypt(key, string): encoded = '' in range(len(string)): key_c = ord(key[i % len(key)]) string_c = ord(string[i % len(string)]) encoded += chr((key_c + string_c) % 127) return encoded but can't seem remember did far decrypting. difficult revers mod :p ideas? that's simple, let's see how works. first of all, encrypted message obtained subtracting key. enc = msg + key (mod 127) how can obtain original message? that's easy, subtract key in both side enc - key = msg + key - key (mod 127) and here get: enc - key = msg (mod 127) for more details, please reference modular arithmetic , think should belong 1 of group/field/ring. i'm not expert in math, deeper theoretical knowledge, can found them in number theory . here refi...

iphone - Setting Property on UIButton in Loop -

i'm spinning in circles on best way implement this, maybe can me out: how can make when uibutton responds selector highlightimage , can set desired challengeid = index of appdelegate.availablearray ? in cellforrowatindexpath method, i'm creating uiscrollview buttons: scrollview = [[uiscrollview alloc] initwithframe:cgrectmake(0, 0, tv.frame.size.width, 78)]; [scrollview setcontentsize:cgsizemake(500, 78)]; [self createscrollbuttons]; [[cell contentview] addsubview:scrollview]; my createscrollbuttons loops , creates buttons in scrollview so, looping on number of elements in availablearray - (void) createscrollbuttons { superherogameappdelegate *appdelegate = (superherogameappdelegate *)[[uiapplication sharedapplication] delegate]; int x = 0; int y = 0; nslog(@"challenge array = %@",appdelegate.availablearray); (int = 0; < [appdelegate.availablearray count]; i++) { nslog(@" id= %d", [[[appdelega...

java - How would you test a Connection Pool -

i have implemented simple connectionpool in java. has no fancy features, get/release connection methods. how can test working? i know there plenty of connection pools ready use out there, more reliable i'll do, trying practice understand how connections pool work. thank you! here code in case helps: public class connectionpoolimpl implements connectionpool { private vector<pooledconnection> connections; // connections container string url; string username; string password; /** * instanciates new mysqlconnectionpool * @param nbconnectionsmax */ public connectionpoolimpl(string dburl, string username, string password){ this.connections = new vector<pooledconnection>(); this.url = dburl; this.username = username; this.password = password; } /** * returns connection pool, if available, or create new one. * * @return connection. */ public connection getcon...

Higher level file read/write with Objective-C -

as objective-c superset of c, guess can use fopen/fread/fwrite/fprint... c. does mean objective-c doesn't have unique file processing function? objective-c doesn't have file handling, nor c. however, c standard library does. , if want use objective-c, can use c standard library. objective-c used foundation, -[nsdata writetourl:atomically:] , -[nsstring writetourl:atomically:encoding:error:] can used if link foundation framework. for reading files methods -[nsdata initwithcontentsofurl:options:error:] , -[nsstring initwithcontentsofurl:encoding:error:] .

regex - What tools, or techniques are available for managing large sets of rewrite rules for Apache? -

we have little on 450 rewrite rules in our apache config spanning 4 different files. can imagine, vital way our site operates. we of course test rules add, have them in git, , ensure maintain correct ordering not step on each other's toes, growing set of rules due full-time development of product, it's number increase. what tools, and/or techniques use maintain vital (and potentially dangerous) configuration? safeguards have ensure improperly designed rewrite rule doesn't accidentally take out large portions of site? as facing problem, researched ways maintain large rulesets. in fact, there no real tool that. there might ways reduce / maintain rwrs. try using coherent url scheme, can translated program logic. this, can use routing controller 1 of symfony 2 you might able condense set of rules using apache's rewritemap . use testng , xenus link sleuth on test stages find out whether rules still work. therefore, every rule has have it's own test...

.net - Radio option GroupName problem in Dynamic loading user Control ASP.net -

Image
i have user control <table style="border-width: 0"> <tr> <td style="vertical-align: middle;"> <asp:radiobutton id="rdoption" runat="server" text="i m testing" groupname="questions" oncheckedchanged="rdoption_checkedchanged" autopostback="true"/> </td> <td style="vertical-align: middle; padding-left: 10px"> <asp:textbox id="txtothers" runat="server" cssclass="txtbox" visible="false"></asp:textbox> </td> </tr> </table> protected void page_load(object sender, eventargs e) { rdoption.groupname = "mygroup"; rdoption.text = option.optiondesc; } on survery.aspx loaded user control dynamically foreach (clsoptions option in _currentquestion.options) { ...

wpf - Using Visibilty with DataContext doesn't work in Button -

i have button trying add visibility attribute binds path. in cases path call , return visibilty(hidden or visible). if have button has datacontext set different binded path , try add visiblity stuff, visibilty binded path never gets called. if remove datacontext visibilty works fine. there kind of work around this? why happen? thank very much. <button visibility="{binding path=thisbuttonvisibility}" datacontext="{binding path=thisbuttondatacontext}" as set datacontext on button , make after databinding "inside" of button binding relative datacontext got set. searches property thisbuttondatacontext.thisbuttonvisibility. normally button inherits datacontext parent, set explicit 1 wont find anymore overlaying datacontext. so said: datacontext valid in element itself, not in content. so can do: move visibility in object thisbuttondatacontext , works

c# - Any way to get event, when some WPF data binding update occurs? -

any way event, when wpf data binding update occurs? upd i'm developing custom control extending 1 of standard controls. need notification, when datacontext property of ancestor control changes, or data binding causes update of property of ancestor control. it sounds require: inotifypropertychanged implemented on view model. depends on implementation assuming you've followed mvvm. this allows carry out work based on value of bound property changing (and event being raised).

c# - Escaping new-line characters with XmlDocument -

my application generates xml using xmldocument. of data contains newline , carriage return characters. when text assigned xmlelement this: e.innertext = "hello\nthere"; the resulting xml looks this: <e>hello there</e> the receiver of xml (which have no control over) treats new-line white space , sees above text as: "hello there" for receiver retain new-line requires encoding be: <e>hello&#xa;there</e> if data applied xmlattribute, new-line encoded. i've tried applying text xmlelement using innertext , innerxml output same both. is there way xmlelement text nodes output new-lines , carriage-returns in encoded forms? here sample code demonstrate problem: string s = "return[\r] newline[\n] special[&<>\"']"; xmldocument d = new xmldocument(); d.appendchild( d.createxmldeclaration( "1.0", null, null ) ); xmlelement r = d.createelement( "root" ); d.appendch...

hardware - Why do computers work in binary? -

i have done searching have not found satisfactory answer. developer want invest necessary time in understanding this, looking complete explanation on , feel free provide useful references. thanks. i recommend buying book andrew s. tanenbaum . developed 1 of predecessors linux called minix. used structured computer organization part of university course. why computers use binary not matter of switch context. relative reference voltage of 3v. +1v(4v) = true or 1 , -1v(2v) = false or 0. it has efficient method of creating controlling or logic circuits . has cost of implementation. how cost build circuits work binary compared circuits work decimal or analogue see answer . if compare how many billions of binary circuit transistors fit on modern cpu. cost of doing decimal (or analogue) system increases exponentially every digit want add have add more controlling circuitry. if want understand of important contributing components have helped make binary default sta...

java - How to inject entire managed bean via @ManagedProperty annotation? -

i'm trying inject entire jsf managed bean managed bean means of @managedproperty annotation (very similar possible inject @managedbean @managedproperty @webservlet? , i'm injecting bean, not servlet). i'm doing: @managedbean public class foo { @managedproperty(value = "#{bar}") private bar bar; } @managedbean public class bar { } doesn't work (jsf 2.0/mojarra 2.0.3): severe: jsf unable create managed bean foo when requested. following problems found: - property bar managed bean foo not exist. check appropriate getter and/or setter methods exist. is possible @ or need injection programmatically via facescontext ? you need add setters , getters @managedbean public class foo { @managedproperty(value = "#{bar}") private bar bar; //add setters , getters bar public bar getbar(){ return this.bar; } public void setbar(bar bar){ this.bar = bar;; } } when facescontext resolve , inject dependencies ...

eclipse - java multiple projects ClassNotFoundException -

i have 2 java projects projecta (java web app) , projectb (contains other java classes) in eclipse ide. e.g. projecta projectb |_helloworld.java |_printhelloworld.java |_helloworld( |_print() new printhelloworld().print() ) so projecta has class method calling method class in projectb. in order these projects build, have built projectb , added jar dependency on projecta's build-path. don't compilation errors , project seems build fine. however, when debug through code. classnotfoundexception @ line projecta calls method in project b does know doing wrong/have missed out? create war file if needed classes in that. the compiler build path not same deploy path. may need explicitly add dependent jar in deployment assembly option

Obscure conditional Java Syntax -

we found, colleague , i, strange compiling syntax if conditional syntax : if (true); { foo(); } is there here explaining strange syntax? thx. the first part, if (true); do-nothing conditional ends @ ; . rest call foo() inside new scope block. should find foo() called.

c# - What is the best ADO.NET 4.0 book for beginners? -

i searching book learn ado.net 4.0, book should excellent technical overview practical examples, want learn ado.net should start? ado.net may pretty broad topic. here books i've had success with: linq 2 sql entity framework classic ado.net , book v1.1 covers of basics well

Using Internet Explorer filters and ClearType -

i've read @ length issues ie disabling cleartype when using filters, , i'm hoping conclusions wrong. seems impossible turn cleartype on after applying filter (e.g. shadow or alpha ). so? with every other browser supporting text-shadow i'd able use it, falling on ie's shadow or dropshadow filter when necessary. applying filter text makes terrible. is there way enable both cleartype , filters in internet explorer? some sources: http://blogs.msdn.com/b/ie/archive/2006/08/31/730887.aspx ie losing cleartype correcting ie cleartype/filter problem when animating opacity of text jquery is there way enable both cleartype , filters in internet explorer? no. filters came before cleartype support in internet explorer , never designed work partial transparency. issue in blog post linked never fixed and, css3 improvements in latest browsers, future's bleak filters. there tricks can use approximate text-shadow in internet explorer, howeve...

android ImageButton gets gray background -

i have button nice background selector. fine. in stead of text in button, want image. have tried changing imagebutton src attribute. when this, looks gray background overlaid behind selector, behind src image. when change regular button, problem goes away. want background selector, plus src image (in stead of button text). any ideas? imagebutton should have android:background set. <imagebutton android:id="@+id/ibarrow" android:layout_width="35px" android:layout_height="50px" android:src="@drawable/arrow" android:background="@drawable/backgroundstate" /> and backgroundstate: <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_selected="true" android:drawable="@color/transparent" /> <item android:state_pressed="t...

asp.net mvc 2 - Earlier ActionFilterAttribute execution in base controller - MVC2 -

i have following setup. when action executed in guestdetailscontroller, how can have[loadthemeinfo] run prior [requirecheckoutavailability] without having specify orders on child controller's attributes? filters use onactionexecuting. [loadthemeinfo(order=1)] public class mgcontrollerbase : controller { } [requirecheckoutavailability(order=2)] public class guestdetailscontroller : mgcontrollerbase { } from msdn : the order property takes integer value must 0 (the default) or greater, 1 exception. omitting order property gives filter order value of -1, indicates unspecified order. action filter in scope order property set -1 executed in undetermined order, before filters have specified order. i prefer unspecifieds execute after specified order in case. there way trying achieve? maybe move load theme info code out of attribute , somewhere else? set order in constructor of attribute. in order keep execution orders in 1 place , keep easy maintain new attributes...

Return object from PowerShell using a parameter ("By Reference" parameter)? -

i have 1 powershell (2.0) script calling another. want receive not main output, additional object can use separately, e.g. display summary line in message. let's have test2.ps1 script being called: param([string]$summaryline) $issues = "potentially long list of issues" $summaryline = "37 issues found" $issues and test1.ps1 script calls it: $mainoutput = & ".\test2.ps1" -summaryline $summaryoutput $mainoutput $summaryoutput the output simply: potentially long list of issues although parameter $summaryline filled in test2, $summaryoutput remains undefined in test1. defining $summaryoutput before calling test2 doesn't help; retains value assigned before calling test2. i've tried setting $summaryoutput , $summaryline [ref] variables (as 1 can apparently functions), $summaryoutput.value property $null after calling test2. is possible in powershell return value in parameter? if not, workarounds? directly assigning parent-s...

Anyone know of a Silverlight / Windows Phone 7 control that displays fractions? -

Image
i'm looking silverlight / windows phone 7 control displays fractions. not gives "3/4" "prettier". below. thanks ps. i'm looking have each number added keydown event. similar way calculator work. need "dynamic" type of placement of numbers opposed placing them @ specific coordinates. i think it'd simple create own power of wpf. here couple examples hope helps! edit: there's wpf version of numericupdown control in kevin moore's bag-o-tricks project. think may able you're asking.

iphone - do I really have to override hash just because I override isEqual: for my subclass? -

apple's document says if override isequal: have override hash make sure hash value should same 2 objects consider equal isequal: then read docs hash , below part of it: therefore, either hash method must not rely on of object’s internal state information or must make sure object’s internal state information not change while object in collection. my customize class myclass have few of members int , bool , nsarray contains number of myclass , want 2 instance of myclass equal if of members equal. i have no problem how override isequal: hash . of understanding, hash should calculate hash value combine members' hash value using bit operation such xor or rotational shift. the problem how implement hash in such way meets apple's requirement mention @ above. docs says hash value should not rely internal state(which members) found have use them compute value. or need implement it? because sure not use class key nsdictionary , way know hash used. there othe...

android - Launching the google maps app from within my app -

Image
i've been searching around internet, android dev guide , stackoverflow 2 hours , can't seem find answer i'm looking i'm going go ahead , ask. i'm building app has button called "find nearby" that's purpose when user clicks on it, call on google maps app using perimeters set in place. not want use mapview within app, want launch , use full google maps app itself. now specific, have permissions needed , maps url inside of manifest. have of application code set in place (buttons, xml, classes etc) , ready , usable other code launch google maps app , once again, have looked on here, google searching, various books, , android dev guide no avail. i need know code need put app enable launch actual, full google maps app within app , not mapview. assistance welcomed string uri = "geo:"+ latitude + "," + longitude; startactivity(new intent(android.content.intent.action_view, uri.parse(uri))); at android sdk documentation,...

add a new number to an existing contact on Android 2.2 -

i trying add new numbers (or emails or websites) existing contact, code not work well. code followings: int rowid = cursor1.getint(cursor1 .getcolumnindex(contactscontract.rawcontacts._id)); contentvalues contentvalues = new contentvalues(); contentvalues.put(contactscontract.data.raw_contact_id, rowid); contentvalues.put(contactscontract.data.mimetype, contactscontract.commondatakinds.phone.content_item_type); contentvalues.put(contactscontract.commondatakinds.phone.number, "45435345"); contentvalues.put(contactscontract.commondatakinds.phone.type, phone.type_home); ops.add(contentprovideroperation .newinsert(contactscontract.data.content_uri) .withvalues(contentvalues).build()); when codes run ,there no errors,and there no changes.i depressed it.any save me!!! maybe need these 2 permissions: <uses-permission android:name="android.permission.read_contacts" /> <uses-permission andr...

iphone - Moving view up to accommodate keyboard -

i have view multiple text fields , want same effect contacts application when click on text field otherwise hidden keyboard when comes up. when dismiss keyboard plan on moving view down properly. i suspect changing frame value, need animated isn't jarring user. advice? examples? wrapping view in uiscrollview indeed way go. on textfielddidendediting delegate, instead subscribe uikeyboarddidhidenotification , uikeyboarddidshownotification , when receive notification keyboard did hide/show scroll view appropriately. can post code examples keyboard notifications if need : ) edit figured i'd post code anyway - might find helpful: you need declare listeners notifications: nsobject hideobj = nsnotificationcenter.defaultcenter.addobserver(uikeyboard.didhidenotification, handlekeyboarddidhide); nsobject showobj = nsnotificationcenter.defaultcenter.addobserver(uikeyboard.didshownotification, handlekeyboarddidshow); then action methods like: void handleke...

Using Javascript to ONLY hide a link/txt/div -

i have site javascript image viewer enlarge pics. therefore if browse js enabled dont have see link page witch shows pics enlarged. if js disabled wont see function enlarge pics javascript, see link enlarged page. i need code hide link. keep finding toggle switches. instead of hiding link, put in noscript tags: <noscript> <a href="/url">this link shows without javascript enabled</a> </noscript>

google maps - Getting error when changing from main to other activity - Android -

i have application using google maps - until moment works fine. when want click button in order add functionality on map have problems. managed visualise button on screen, works on click - shows toast correctly. aim start new activity (having own layout) - looking , reading tones of tutorials , stuff here have : //the add button in upper right corner button addbookmark = (button) findviewbyid(r.id.button); addbookmark.setonclicklistener(new view.onclicklistener() { @override public void onclick(view mapview) { intent addbookmarkintent = new intent(googlemapsapp.this, locationbookmaker.class); startactivity(addbookmarkintent); } }); also i've edited manifest file: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" ... <activity android:na...

.net - Need to know how the Asynchronous WCF HTTP Module/Handler in IIS7.5 (WAS) can benefit me -

i reading following article http://blogs.msdn.com/b/wenlong/archive/2008/08/13/orcas-sp1-improvement-asynchronous-wcf-http-module-handler-for-iis7-for-better-server-scalability.aspx , little confused. first of article 2008 i'm not sure if changed in .net 4.0. i have client relies on synchronous operations. first concept have hard time grasping difference between asynchronous behavior on worker thread level , asynchronous behavior on client level (when calling wcf proxies). know following: is asynchronous wcf http module default module in .net 4.0? if not, , enable it, client proxy calls asynchronous well. i understand problem using asynchronous wcf http module in iis6 because there no throtling on incoming requests server, there can potentially high number of requests being queued wcf. when dealing was, asp.net worker process not involved, mechanism prevents wcf queueing many requests (i.e. dos)? maxconcurrentrequestspercpu? my main question second bullet point...

Can a silverlight application open a socket (TCP/IP) connection to the same server or another server? -

i want develop silverlight application opens dedicated tcp/ip connection server run from. restrictions? the restriction in scenario port number connecting must in range of 4502-4534.

python - Pygame Making A Sprite Face The Mouse -

im new pygame kinda ok on python, im creating zombie shooting game overhead view. managed make character move when pressing arrow keys. need player face mouse/cursor without clicking screen time. help? for event in pygame.event.get(): if event.type == mousemotion: mousex, mousey = event.pos # build vector between player position , mouse position movevector = (mousex-playerx, mousey-playery) """ compute angle of movevector current vector player facing (facevector). should keeping , updating unit vector, each mouse motion assume have initial facing vector (1,0) - facing east """ # compute angle in [1] # rotate image angle , update facevector [1] - how find angle between 2 vectors: http://www.euclideanspace.com/maths/algebra/vectors/anglebetween/index.htm your image may lose quality when rotated @ small angle. it's discussed in pygame documentation pa...

css - Javascript for...in seems to only return every other index in array -

this question has answer here: how can replace 1 class on elements, using dom? 2 answers i have page (actually, thirty or so) i'm trying change classname of specific elements based on querystring variable. works fine except part, i'm getting weird result... var hitareas = document.getelementsbyclassname('hitarea'); alert(hitareas.length); for(hitarea in hitareas) { alert(hitareas[hitarea]); hitareas[hitarea].classname = 'hitarea_practice'; } the alert(hitareas.length); line returning number of elements (7, html below) classname 'hitarea', when iterate through hitareas, it's changing classnames every other element on page. halfway through returns undefined value alert(hitareas[hitarea]); assumably because it's trying reference array elements beyond index of 6. body of html page: ...

java - Boolean vs boolean(s) as trilean switches -

i'm developing android application , ran something. have anonymous classes (event listeners). parameterized database. did this: buttona.setontouchlistener(new view.ontouchlistener() { private boolean isactive = null; private boolean istrigger; private int onlevel; private int offlevel; private int chidx; @override public boolean ontouch(view v, motionevent event) { if (isactive == null) { cursor btnsettings = dbhelper.getbuttonstable().fetchbutton(1, profileid, currentmode); ... ... } return true; } is considered practice use boolean object trilean switch (it has null value if listener haven't been parameterized yet) or should use 2 bo...

iphone - how display image view with out losing image clarity -

i have image of size 200x200,i need place in 15x15 size imageview. just thumbnail,but loos clarity of image. but need display image clarity,is there way display image view image without loss of clarity. can 1 please me. thank u in advance. as maintaining aspect ratio, should not cause problem. 200x200 15x15 asking fit in small space, lose details, why don't create image of 15x15 straight way.

iphone - Does the SDK support @2x files for video -

we using mpmovieplayercontroller control video playback, wanted know (as couldnt find mention online) whether took advantage of @2x files when displayed on ipod4/iphone4, uiimage does it doesn't automatically uiimage will. implement system self. using subclass, category or in current code before set file played movie player. code like. if has retina display append @2x file path.

Why use HTML and not HAML? -

in various forums , blogs, see people promoting haml , promoting html. advantages , disadvantages of using haml vs html? i want understand i'm missing out on if use haml in favor of html (if any). you trying compare apples oranges. browsers understand html. haml templating language gets transformed html (e.g. same final output). if find haml syntax easier html go it. imho - abstracting away actual elements generating makes applying css , doing javascript navigation more difficult. personally if wanted "trim" html, put content tags (depends on serverside technology) <!doctype html> <html> <head>...</head> <body> <x:awesomelistthing data="$foo"/> <x:foreach data="$bar"> <x:renderbazwidget/> </x:foreach> <div>random content hasn't been "tagified" yet.</div> </body> </html> then inside tag's template you'll able see act...

jquery - Evaluate orientationEvent and setting a value? -

if have onchange function firing when orientation change has happened, how set value within onchange update jquery selector. instance: $(document).ready(function(){ var onchanged = function() { if(window.orientation == 90 || window.orientation == -90){ image = '<img src="images/land_100.png">'; }else{ image = '<img src="images/port_100.png">'; } } $(window).bind(orientationevent, onchanged).bind('load', onchanged); $('#bgimage').html(image); //won't update image }); you need put update image inside onchanged function every time orientation changes, image html changed. $(document).ready(function(){ // event orientation change var onchanged = function() { // orientation var orientation = window.orientation, // if landscape, use "land" otherwise use "port...

php - Regular Expressions - Match inside a Match -

i trying find way match inside match. still reading oreilly's book on regular expressions, have now: i need values inputs inside form. page contains multiple forms, similar this: type="checkbox" value="([^"])" but need target checkbox values inside specific form. using preg_match way. p.s. know form preg_match first, , match inside result, i'm wondering how in regex. preg_match("|type=\"checkbox\" value=\"(.*?)\"|");

ruby on rails - Rspec, expect scope to change by -

i have written following test in rspec: expect { ... }.to change( user.where(:profile.exists => true), :count ).by(1) but scope executed once , it's same array same size. how make rspec execute scope before , after running code in expect? the ops solution, posted answer this may or may not work else similar problem. no corpus included in original question, , not independently verified. expect { # test goes here }.to change{ user.where(:profile.exists => true).count }.by(1)

android - Fragments vs. Deprecated TabActivity on a pre 3.0 device -

so tabactivity officially deprecated of 3.0, i'm going through , switching of tabactivities fragments. first decided research little fragments i'm reading design philosophy , 1 of lines is: android introduced fragments in android 3.0 (api level "honeycomb"), support more dynamic , flexible ui designs on large screens, such tablets. now, i'm not developing tablet, nor app ever see tablet. barring bad idea of using deprecated code, have gain if i'm not going use big screens or animations, seems main thing touting? now, i'm not developing tablet, nor app ever see tablet. that may case if you're not shipping app. because writing phone not prevent tablet owners installing it. may using hardware capabilities tend used phones , not tablets (e.g., telephony), there's nothing stopping hardware manufacturer offering capabilities in tablet. barring bad idea of using deprecated code, have gain if i'm not going use big ...

c++ - Convert decimal dollar amount from string to scaled integer -

"35.28" stored char* . need turn integer (35280). i want avoid floats. how can this? remove dot char , then simplest not best use atoi see answer here , other possible ways.

mobile - Drawing in Android Tutorials -

i'm curious if there android drawing tutorials drawing sprites. specifically, want incorporate graphics , android views/widgets single display. example, want show group of textview views placed in different places on screen (not simple linear layout) , use java draw lines between views graphical "connectors." know can draw .png , try place textviews relative .png rather have java draw connecting line graphics. not talking complicated, paths mostly. i come flex background , there if want draw can attach displayobject graphics object , draw heart's content. how work in android? i've read tutorials @ android.com, reason, seem want make documentation confusing possible. i think looking canvas. has drawpath() methods should able need. http://developer.android.com/reference/android/graphics/canvas.html canvas tutorial part 1 canvas tutorial part 2 edit: nope things extend viewgroup can hold other views. there nothing stopping putting other k...

CUDA reduction using registers -

i need calculate n signals' mean values using reduction. input 1d array of size mn, m length of each signal. originally had additional shared memory first copy data , reduction on each signal. however, original data corrupted. my program tries minimize shared memory. wondering how can use registers reduction sum on n signals. have n threads, shared memory (float) s_m[n*m], 0....m-1 first signal, etc. do need n registers (or one) store mean value of n different signals? (i know how sequential addition using multi-thread programming , 1 register). next step want subtract every value in input correspondent signal's mean. your problem small (n = 32 , m < 128). however, guidelines: assuming reducing across n values each of n threads. if n large (> 10s of thousands) large, reductions on m sequentially in each thread. if n < 10s of thousands, consider using 1 warp or 1 thread block perform each of n reductions. if n small m large, consider using mul...

qt - virtual keyboard does not appear in QML-based application on Nokia 5230 -

i have qml-based application deployed on nokia 5230 phone, there several textinput components, when component takes input focus, input method status indicator changed, virtual keyboard not appear. my application full-screen displayed calling qdeclarativeview::showfullscreen(), have tried 4 different input methods including official aknfep, have same problem. did miss something? btw, works fine on desktop or in qt simulator. which version of qt using? did try opening vkb manually? textinput { id: textinput activefocusonpress: false mousearea { anchors.fill: parent onclicked: { textinput.forceactivefocus(); textinput.opensoftwareinputpanel(); } } }

exponential - How to represent e^(-t^2) in MATLAB? -

i beginner in matlab, , need represent e (-t 2 ) . i know that, example, represent e x use exp(x) , , have tried following 1) tp=t^2; / tp=t*t; x=exp(-tp); 2) x=exp(-t^2); 3) x=exp(-(t*t)); 4) x=exp(-t)*exp(-t); what correct way it? if t matrix, need use element-wise multiplication or exponentiation. note dot. x = exp( -t.^2 ) or x = exp( -t.*t )

java - Count occurrences of words in ArrayList -

this question has answer here: how count number of occurrences of element in list 20 answers i have arraylist of words duplicate entries. i want count , save occurrences each word in data structure. how can it? if haven't big strings list shortest way implement using collections.frequency method: list<string> list = new arraylist<string>(); list.add("aaa"); list.add("bbb"); list.add("aaa"); set<string> unique = new hashset<string>(list); (string key : unique) { system.out.println(key + ": " + collections.frequency(list, key)); } output: aaa: 2 bbb: 1

CakePHP: Cake Bake HasOne association -

i use following db setup: users: id name country_id (fk) countries id name i use setup data integrity. when user adds account, country dropdown presented in add form through find(list). the problem while cake baking, can not choose hasone relationship between users , countries. can choose user belongsto country. what goes wrong here? need add hasone association manually or belongsto relationship correct? thanks i assume mean hasmany, in country has many users. yes, you'll have define in country model, if wish have relationship.

Scala error - error: not found: type -

i java developer trying learn class creation in scala. i create 2 separate scala files. 1 file contains trait. second file extends trait , defines method. cola.scala contains trait. trait cola { def fizz(): string } pepsi.scala has class tries extend trait. class pepsi extends cola { override def fizz():string = "1 sugar" } var p = new pepsi println( " p = " + p.fizz ) when excecute "scala pepsi.scala" following error message: error: not found: type cola class pepsi extends cola both files in same folder. please how resolve this? using scala 2.8 not using editor forced scratch. improve knowledge computers. scala doesn't require put of traits , classes eponymous (that is, named same class) files. can put of in 1 file , work. or can specify both files on command line: scala not automatically cola in cola.scala .

Suspend and Resume thread (Windows, C) -

i'm developing heavily multi-threaded application, dealing lots of small data batch process. the problem many threads being spawns, slows down system considerably. in order avoid that, i've got table of handles limits number of concurrent threads. "waitformultipleobjects", , when 1 slot being freed, create new thread, own data batch handle. now, i've got many threads want (typically, 1 per core). then, load incurred multi-threading extremely sensible. reason this: data batch small, i'm creating new threads. the first idea i'm implementing regroup jobs longer serial lists. therefore, when i'm creating new thread, have 128 or 512 data batch handle before being terminated. works well, destroys granularity. i asked scenario: if problem comes "creating" threads often, "pausing" them, loading data batch , "resuming" thread? unfortunately, i'm not successful. problem is: when thread in "suspend" mode, ...

ios4 - Can we access iphone Images ,Audios and Videos Programiticaly for upload to Server? -

hi want videos, audios , images in iphone , upload them server can perform task programitically possible in iphone sdk ? starting ios 4, can use alassetslibrary retrieve images , videos: http://developer.apple.com/library/ios/#documentation/assetslibrary/reference/alassetslibrary_class/reference/reference.html edit: whole framework api can found here: http://developer.apple.com/library/ios/#documentation/assetslibrary/reference/assetslibraryframework/_index.html#//apple_ref/doc/uid/tp40009730

Delete file from ClearCase checked out on another branch -

Image
i trying delete file in clearcase. when attempt delete message element has checkouts. when version tree on file see file checked out user, in view, on different branch. how delete file? in addition why doesn't clearcase let me delete file? you can delete through command line , cleartool, forcing delete (option isn't available gui) cleartool rmname -force thefile don't forget checkout parent directory first, checkin same parent directory, in order see have dereferenced file within said directory. see cleartool rmname : –f/orce : forces removal of name when there @ least 1 checkout of element. when used –nco , suppresses prompt confirmation. that work when had before: , explained in technote " about cleartool rmname , checkouts ".

Remove quotes from a character vector in R -

suppose have character vector: char <- c("one", "two", "three") when make reference index value, following: > char[1] [1] "one" how can strip off quote marks return value following? [1] 1 as.name(char[1]) work, although i'm not sure why you'd ever want -- quotes won't carried on in paste example: > paste("i counting to", char[1], char[2], char[3]) [1] "i counting 1 2 three"

objective c - iPhone - Help with CGGradientCreateWithColorComponents and creating gradient as per screenshot -

Image
i trying apply same gradient per screen shot below using cggradientcreatewithcolorcomponents . this i'm using @ moment, it's not quite right , i'm after better way of trying guess these values. i'd know how determine these values code grabbed tutorial, didn't explain @ in terms of components are. cgcolorspaceref mycolorspace = cgcolorspacecreatedevicergb(); cgfloat components[8] = { 1, 1, 1, 1, 0.866, 0.866, 0.866, 1 }; cgfloat locations[2] = { 0.0, 1.0 }; cggradientref mygradient = cggradientcreatewithcolorcomponents(mycolorspace, components, locations, 2); i've played around , got picture: with colors: static const cgfloat colors [] = { 0.894, 0.894, 0.894, 1.0, 0.694, 0.694, 0.694, 1.0 }; using piece of code: - (void) drawrect:(cgrect)rect { cgcolorspaceref basespace = cgcolorspacecreatedevicergb(); cggradientref gradient = cggradientcreatewithcolorcomponents(basespace, colors, null, 2); cgcolorspacerelease(basespace),...

how to use hyperlink in wpf to get a file in network drive? -

i have web application...where can excel file network drive...using ..so not using impersonation. do have similar in wpf ? edit : want open excel file in network location...when user click link or button. also, dont want use impersonation...as dont have impersonate in case of a-href. <hyperlink navigateuri="file:///networkshare/file"> excel file </hyperlink>

c++ - variables not initializing in my constructor -

so problem simple, data initalizing in constructor not saving @ all. basically have pin pointed 1 point. have constructor in class strset::strset(std::string s){ std::vector<std::string> strvector; strvector.push_back(s); } and in main file have else if(command == "s"){ cout << "declare (to singleton). give set element:"; cin >> input >> single_element; vector_info temp; temp.name = input; strset set(single_element); set.output(); temp.vector = set; list.push_back(temp); } when constructor called , check length of vector answer appropriate, when check length of vector in output, resets 0? can me, appreciated!!!!!!! edit this .h file class strset { private: std::vector<std::string> strvector; // empty (when constructed) bool issorted () const; public: strset (); // create empty set strset (std::string s); // create sing...

c# - How can we get the current exchange rate? -

we have payment gateway , fedex shipping in our project. problem if person other country have charge different rates shipping. how can current exchange rate. there service available? here's webservice, offers functionality: http://www.xignite.com/xcurrencies.asmx

How do add a header on extjs 3.0 groupTab example? -

i trying add header on extjs 3.0 grouptab example ,and has given me headache days now.anybody idea how can approach that? in grouptab example component header modified appears @ left side of component(it can appear @ right side). if want component have 1 more header @ top, can set item of container has normal header.

objective c - Cocoa: distinguish input device / scrollWheel: as mouse-scroll wheel and TrackPad -

i looking method reliably distinguish within [nsresponder scrollwheel:] if users input device has one-dimensional scroll-wheel or 2 dimensional trackpad/magicmouse? in first implement different behavior. taking on deltax of nsevent little weak. suggestions? you can use private method call [theevent _scrollphase] tell whether device using inertial scrolling, indicates apple-supplied input device. (note: won't work if user has disabled inertial scrolling)

Spring annotations basic question -

as far understand, main purpose of dependency injection have dependencies separated declaratively, can review , change dependency structure easily...right? then using dependency annotations spread through out code, aren't going non-centralized system (similar simple new operator), harder tweak? @autowired / @inject annotations declare dependencies on interfaces rather on concrete classes (as in case of new ), still can control implementations should injected controlling beans declared in context. also, these dependencies can overriden manually. @component -family annotations can controlled well, since can exclude particular classes component scanning.

solaris - Starting the service admin svcadm, does not generate the pid file in /var/run. How is this file created? -

i have been trying write script start/stop service svcadm. not understand how pid of process executed /var/run/myprocess.pid? not clear me can not find on other scripts in /lib/svc/method writes /var/run. mean have explicitly extract target location of pidfile environment variable, let program query , write code put pid in /var/run/myprocess.pid file? the pid file created daemon binary itself, not service scripts. if code need portable non solaris 10+ oses, might use defines this: http://src.opensolaris.org/source/xref/amd/ibs-gate/usr/src/cmd/ipf/tools/ipmon.c#130

mysql - bulk insert in zend framework -

possible duplicate: how add more 1 row zend_db? everyone, i need have bulk insert in zend framework. normal sql have below query, want same in zend framework. insert `dbname`.'tablename` (`id`, `user_id`, `screen_name`, `screen_name_server`) values (null, '15', 'test', 'test'), (null, '15', 'test', 'test'); thanks. there's no way this, marcin states. if you'd messing around zend framework you'd try alter insert. you try make insert method can take array of arrays data. use arrays of data build bulk insert. for example, $data1 = array( ); //data first insert $data2 = array( ); //data 2nd insert //a zend_db_table object $dbtable->insert( array( $data1, $data, ) ); you have edit insert method bit detect multiple data inserts , build insert accordingly. unfortunately haven't looked how code built or put here use.

PHP/MySql - putting data to table -

i'm learning put values db php. simple form wrote test (its in table) <form action="connect2db.php" method="post"> <table width="500" border="0"> <tr> <td width="200">first name:</td> <td><input type="text" width="258" name="fname" id="fname"/></td> </tr> <tr> <td width="200">last name:</td> <td><input type="text" width="258" name="lname" id="lname"/></td> </tr> <tr> <td> email address: </td> <td> <input type="text" width="258" name="email" id="email"/> </td> </tr> <tr> <td width="200">your message:</td> <td...

php - jQuery tab losing focus -

i using following jquery code toggle between tabs on page: jquery(document).ready(function(){ jquery('#questions > div').hide(); jquery('#questions div:first').show(); jquery('#questions ul li:first').addclass('active'); jquery('#questions ul li a').click(function(){ jquery('#questions ul li').removeclass('active'); jquery('#questions ul li').removeclass('selected'); jquery(this).parent().addclass('active'); jquery(this).parent().addclass('selected'); var currenttab = jquery(this).attr('href'); jquery('#questions > div').hide(); jquery(currenttab).show(); return false; }); }); now problem under 1 of tabs have delete line call: <div id ="questions"> <ul> <li class="selected"><a href="#tab-1"></a></li> <...

visualsvn - Integrating SVNServer and Redmine -

can me integrate visual svnserver , redmine on windows server 2003? want same actions redmine can tortoise connected visual svn server. tried follow web articles without success. in advance, jorge i have been successful in integrating redmine, visual svnserver, subversion , tortoisesvn in windows environment. however, need specific on "actions" want integrate. here's level of integration i've been able implement: when user commits subversion repository proper comments, revision links issues(s) when user commits subversion repository proper comments, issues(s) status change when user commits subversion repository proper comments, issues(s) % done changes redmine browses subversion repository redmine performs diffs some other goodies might forgetting list want achieve , have been able go far , i'll able more.

inheritance - Determining Django Model Instance Types after a Query on a Base-class -

is there way determine 'real' class of django database object is, after has been returned query on base class? for instance, if have these models... class animal(models.model): name= models.charfield(max_length=128) class person(animal): pants_size = models.integerfield(null=true) class dog(animal): panting_rate = models.integerfield(null=true) and create these instances... person(name='dave').save() dog(name='mr. rufflesworth').save() if query animal.objects.all() , end 2 animal instances, not instance of person , instance of dog . there way determine instance of type? fyi: tried doing this... isinstance(animal.objects.get(name='dave'),person) # <-- returns false! but doesn't seem work. i had similar problem in past , found satisfactory solution this answer . by implementing abstract class stores real class , have inherited parent class, once can cast each parent class instance actual type. (the ...