Posts

Showing posts from September, 2014

Rails/Rspec - testing a redirect in the controller -

so writing test controller in existing controller didnt have 1 before. want test redirect happens when not allowed edit vs allowed edit it. the controller action being edit def edit if !@scorecard.reviewed? || admin? @company = @scorecard.company @custom_css_include = "confirmation_page" else redirect_to :back end end so if scorecard has been reviewed admin can edit score. routes controller.. # scorecards resources :scorecards member 'report' end resources :inaccuracy_reports, :only => [:new, :create] end and test require 'spec_helper' describe scorecardscontroller describe "get edit" before(:each) @agency = factory(:agency) @va = factory(:va_user, :agency => @agency) @admin = factory(:admin) @company = factory(:company) @scorecard = factory(:scorecard, :level => 1, :company => @company, :agency => @agency, :reviewed => true)

Finding all pair combinations in strings with several comma separated instances in R -

i'm new r , trying solve a, me, challenging problem. i have .csv file containing 22.388 rows comma separated integers. want find possible combinations of pairs of integers each row separately , list them pair pair, i'll able make visual representation of them clusters. i've tried installing combinat package r can't seem solve problem. an example file be 2 13 2 8 6 which should listed in possible combinations of pairs this. 2, 13 2, 8 2, 6 8, 6 sample input - replace textconnection(...) csv filename. csv <- textconnection("2,13 2,8,6") this reads input list of values: input.lines <- readlines(csv) input.values <- strsplit(input.lines, ',') this creates nested list of pairs: pairs <- lapply(input.values, combn, 2, simplify = false) this puts in nice matrix of integers: pairs.mat <- matrix(as.integer(unlist(pairs)), ncol = 2, byrow = true) pairs.mat # [,1] [,2] # [1,] 2 13 # [2,]

WordPress: register_settings helper -

im trying make register_settings little bit cleaner plugin. looks way: add_action( 'admin_init', 'hpblogposts_register_settings' ); function hpblogposts_register_settings() { register_setting( 'hpblogposts_settings_options_group', 'linkid01' ); register_setting( 'hpblogposts_settings_options_group', 'linktext01' ); register_setting( 'hpblogposts_settings_options_group', 'linkalt01' ); register_setting( 'hpblogposts_settings_options_group', 'linkid02' ); register_setting( 'hpblogposts_settings_options_group', 'linktext02' ); register_setting( 'hpblogposts_settings_options_group', 'linkalt02' ); register_setting( 'hpblogposts_settings_options_group', 'linkid03' ); register_setting( 'hpblogposts_settings_options_group', 'linktext03' ); register_setting( 'hpblogposts_settings_options_group', 'li

ruby - rails default actions are missing params in routing -

excuse me lame question, i`m stuck. plain , simple in routes.rb file have: resource :books resource :reviews end running rake routes | grep reviews gives me: books_reviews post /books/reviews(.:format) reviews#create new_books_reviews /books/reviews/new(.:format) reviews#new edit_books_reviews /books/reviews/edit(.:format) reviews#edit /books/reviews(.:format) reviews#show put /books/reviews(.:format) reviews#update delete /books/reviews(.:format) reviews#destroy my question is: :id param in show , edit actions? according tutorial: http://guides.rubyonrails.org/routing.html there should "id" params in routing, this: new_books_reviews /books/:id/reviews/new(.:format) reviews#new edit_books_reviews /books/:id/reviews/edit(.:format) reviews#edit /books/:id/reviews(.:format) reviews#show on top of routes show, update , destroy a

r - Sort a data.frame by multiple columns whose names are contained in a single object? -

i want sort data.frame multiple columns, ideally using base r without external packages (though if necessary, it). having read how sort dataframe column(s)? , know can accomplish order() function long either: know explicit names of each of columns. have separate object representing each individual column sort. but if have 1 vector containing multiple column names, of length that's unknown in advance? say vector called sortnames . data[order(data[, sortnames]), ] won't work, because order() treats single sorting argument. data[order(data[, sortnames[1]], data[, sortnames[2]], ...), ] work if , if specify exact correct number of sortname values, won't know in advance. things i've looked @ not been totally happy with: eval(parse(text=paste("data[with(data, order(", paste(sortnames, collapse=","), ")), ]"))) . maybe fine, i've seen plenty of hate using eval() , asking alternatives seemed worthwhile. i may able us

how to create a macro in racket where a list becomes the args of said lambda? -

how go in doing define-syntax-rule accepts list arguments , list (or quote, in case single element) body of lambda? like: >(define (lambdarize '(x y z) '(+ x y z))) #<procedure> >(a 1 2 3) 6 >(define b (lambdarize '(x) 'x)) #<procedure> >(b 1) 1 i have played around define-syntax-rule , apply , since lambda seems macro , not procedure, have been stumped @ trying find it... oh... , solution not use eval , pernicious... update thanks answer, ryan... pretty did it! =) problem eval no @ catching current scope... way can stuff (let ([a 1]) (begin (defmethod add ((x integer?) (y integer?)) (+ x y a)) (add 1 2) ) which fail miserably eval... academic example, think test correctness. it's not possible create function formal parameters , body given run-time values (s-expressions) without using eval . but based on answer greg's comment, can chang

jquery - How to pass huge data through ajax call using XmlHttpRequest -

i need pass huge data controller. have used xmlhttprequest . have written code like: var xmlhttp; if (window.xmlhttprequest) { xmlhttp = new xmlhttprequest(); } else { xmlhttp = new activexobject("microsoft.xmlhttp"); } xmlhttp.onreadystatechange = function () { if (xmlhttp.readystate == 4 && xmlhttp.status == 200) { document.getelementbyid("mydiv").innerhtml = xmlhttp.responsetext; } } xmlhttp.open("post", "/home/content", true); xmlhttp.send("content=" + data); and actionresult like [httppost] public actionresult(string content) { return json("suc", jsonrequestbehavior.allowget); } the data like uklgripkaabxrujqvla4[...huge piece of data...]kxgtrtkkyke6xap+gyny93kj but not passing controller. showing data long. how can rid of this? send data in post body, passing argument send : xmlhttp.open("post", "/home/content", true); xmlhttp.send("c

org.eclipse.swt.*; The import org.eclipse cannot be resolved -

i trying write small program requires import statement import org.eclipse.swt.*; . (i'm practicing this tutorial). however, eclipse won't compile program , giving me error " the import org.eclipse cannot resolved " google hasn't been such a great friend @ finding answer time. this because haven't added swt library buildpath. follow steps of tutorial: download swt library. 3.1.2 version of eclipse, swt library available @ http://archive.eclipse.org/eclipse/downloads/drops/r-3.1.2-200601181600/index.php section titled swt binary , source. from main menu tool bar, select "file" followed "import". doing bring "import wizard" dialog. now select "existing projects workspace" , click on "next" button. click on "select archive file" followed "browse" button. locate swt archive downloaded in step 1. click finish button finish importing swt project workspace.

What is the most efficient way to format strings with rounding and thousand separator in C? -

so have inner loop situation buffer of floating point , integer values copied on buffer in string format. what alternatives round , insert thousand separator when formatting strings? whatever approach end using, has flexible enough in permitting different formats. also, because inner loop scenario, want optimize solution far possible. it seem locale.h 1 way it. in case, how can setup customized locales, , how use them? or there better alternative altogether? if noob question please point me in right direction. edit: here few examples clarify: 1000 gives 1,000 (if want use , thousand separator) 1000 gives 1 000 (if want use space thousand separator) 1000.123 gives 1,000.1 (if want round 1 digit , use , thousand separator) 0 gives `` (if want show 0 blank string) i on posix system btw... you can try set locale using setlocale , use printf ' flag , precision value rounding. whether work, depends on c library. see following program: #incl

uinavigationbar - ios UIBarButtonItem with UIBarButtonSystemItemCompose showing red button -

i trying add uibarbuttonitem style of uibarbuttonsystemitemcompose. according apple docs should display compose icon consists of square outline. when use following code displays red button. icon work if uibarbuttonitem if placed inside of uitoolbar , not navigation bar. self.navigationitem.rightbarbuttonitem = [[[uibarbuttonitem alloc] initwithtitle:nil style:uibarbuttonsystemitemcompose target:self action:@selector(tweetpressed:)] autorelease]; you creating button incorrectly. need use proper init... method. uibarbuttonitem *btn = [[uibarbuttonitem alloc] initwithbarbuttonsystemitem:uibarbuttonsystemitemcompose target:self action:@selector(tweetpressed:)]; self.navigationitem.rightbarbuttonitem = btn; [btn release]; look @ docs init... method used. @ type should passed style parameter , @ valid val

facebook - what is response in FB.getLoginStatus -

to detect facebook user online/offline status use method fb.getloginstatus method. but, paramater("response") mean , come in below code snippet parameter response mean in line " fb.getloginstatus(function(response) " fb.getloginstatus(function(response) { console.log(response); if (response.status === 'connected') { // user logged in , has authenticated // app, , response.authresponse supplies // user's id, valid access token, signed // request, , time access token // , signed request each expire var uid = response.authresponse.userid; var accesstoken = response.authresponse.accesstoken; console.log('user logged in , autenticated'); } else if (response.status === 'not_authorized') { // user logged in facebook, // ha

'Fatal: cherry-pick failed' with Git -

i working on branch x . made commit , pushed it. then wanted cherry-pick branch y . due unmerged files present, got following message: error: 'cherry-pick' not possible because have unmerged files. hint: fix them in work tree, hint: , use 'git add/rm <file>' hint: appropriate mark resolution , make commit, hint: or use 'git commit -a'. fatal: cherry-pick failed now, want delete branch y , re-create branch y , want manually edit file trying cherry-pick. currently, i'm unable delete branch working branch. cannot checkout other branch. i'm getting following error on trying change branch. mod/assign/locallib.php: needs merge error: need resolve current index first i need delete branch y , without losing on branch x . edit #1 i edited file mod/assign/locallib.php on doing git status , get: # on branch mdl-38267_24 # unmerged paths: # (use "git add/rm <file>..." appropriate mark resolution) # # both modified

database - PostgreSQL 8.2 unsupported version (1.11) in file header message to do backup restore -

i'm trying restore backup in postgresql pgadmin , following error message: c:\program files\postgresql\8.2\bin\pg_restore.exe -i -h localhost -p 5432 -u postgres -d gsan_comercial -v "c:\users\usr\desktop\gsan\data base\gsan_comercial_pmss.backup" pg_restore: [archiver] unsupported version (1.11) in file header process returned exit code 1. i can not find reason this. tks the version find in dump file header related version of tools used dump, i.e., pg_dump . possible dump 8.2 database using pg_dump later version (for example 1 8.4 distribution) because tools backward compatible in end you'll file can restored using new tools. i suppose happened , you're trying restore 8.2 dump done using 8.4 tools on pgadmin using 8.2 tools.

nginx proxy doesn't cache OCSP responses -

i want use nginx caching proxy in front of ocsp responder. 'an ocsp request using post method constructed follows: content-type header has value "application/ocsp-request" while body of message binary value of der encoding of ocsprequest.' (from rfc2560) hence, configured nginx follows: proxy_cache_path /tmp/nginx/cache levels=1:2 keys_zone=my-cache:8m max_size=1000m inactive=600m; server { # make site accessible http://localhost/ server_name localhost; location / { proxy_pass http://213.154.225.237:80; #ocsp.cacert.org proxy_cache my-cache; proxy_cache_methods post; proxy_cache_valid 200 302 60m; proxy_cache_valid 404 1m; proxy_cache_key "$uri$request_body"; expires off; proxy_set_header host $host; proxy_set_header x-real-ip $remote_

Ruby Checking to see if website exists -

ok checking see if server running. works long port correct. if cange port 1 know not excepted skips if routine. example below works fine. change port number 99 , skips if. think should fall else section. url = uri.parse("http://www.google.com/") url.port = 80 req = net::http.new(url.host, url.port) res = req.request_head(url.path) if res.code == "200" #do else #do else end you should provide timeout , rescue socketerror , timeout::error : require "net/http" def check_server(server, port) begin http = net::http.start(server, port, {open_timeout: 5, read_timeout: 5}) begin response = http.head("/") if response.code == "200" # fine else # unexpected status code end rescue timeout::error # timeout reading server end rescue timeout::error # timeout connecting server rescue socketerror # unknown server end end if want check if server up

amazon web services - Scoping AWS S3 objects to Rails Users -

i have rails app setup devise, aws s3 , highcharts. currently users can log in , upload text files s3. rails requests data directly aws , passes highcharts processing – spitting out nice , pretty graph. however, users can see every piece of data that's been uploaded. i’m not sure how setup relationship between users , respective uploaded objects. best way ‘scope’ data within s3 users can see data have uploaded? assuming done through aws acl? the s3 bucket acls designed control bucket access aws accounts , anonymous requests whole, documented here . such, don't think acls work use case. a better solution iam policies . idea, here, create new iam user every account registered in app. can done both , programmatically. then, fracture bucket's namespace along line, perhaps account_id: s3://mybucket/account1/ s3://mybucket/account2/ s3://mybucket/account3/ ... on account creation, construct iam policy grants rw access just account's folder. i haven&#

.net - Prepend a URL segment to a relative / relative to server URL -

Image
i have requirement prepend url segment relative, or relative-to-server urls within html document (eg href or src attributes) on server-side application i'm working in .net environment, , unfortunately there no base class libraries loading html string dom , manipulating (i not have luxury of being able introduce third-party library @ point), seems candidate regex replace, i'm little weak on i need regex can handle these 2 cases: relative server url: href="/controller/action" -> href="/mypathsegment/controller/action" relative url: href="image/logo.gif" -> href="/mypathsegments/image/logo.gif" don't worry mypathsegment ..i have logic elsewhere can figure out levels of path segments relative urls, want focus on regex problem i figure need regex can match on src="..." or href="/..." pattern , insert string @ beginning after first opening double quote not experienced enough regexs figure ou

spring web-services transform namespace before endpoint-selection -

is possible transform request-body in spring-ws interceptor before endpoint-selection takes place. client calls uses different xml-namespace (but same schema, don't ask why facepalm ) the payload-interceptor described here http://static.springsource.org/spring-ws/sites/2.0/reference/html/server.html#server-endpoint-interceptor can applied after endpoint selected. since our endpoint mapped @payloadroot , namespace , localpart messagedispatcher cannot find applicable endpoint , rejects further processing i think need take @ payloadtransforminginterceptor . can used transform incoming message. using can support multiple versions of wsdl instance.

java - Loop through array of objects inside the class -

i having trouble looping through array objects, inside class. wrote little demo here can follow: tank tanks[] = new tank[2]; tanks[0] = new tank(); tanks[1] = new tank(); tanks[0].dostuff(tanks); dostuff(tank[] tanks) { (int = 0; < tanks.length; i++) { if (tanks[i].equals(this)) continue; // stuff } } so, have array type tank. call method dostuff inside tank class. method takes array , loops through it. , want stuff every tank not current instance of class. hope can make sense out of code , description. the problem nullpointerexception if (tanks[i].equals(this)) what doing wrong here? that means tanks[i] null. (or overridden equals() method has bug) you need check that.

java - JOptionPane showInputDialog cancel button NullPointerException -

i trying unsuccessfully trap user entering filename. i'm using input dialog because path , extension predetermined, , need append filename after user enters it. title says nullpointerexception time user clicks cancel button. since input dialog has no way remove cancel button i've resorted method: while (filename.equals(null) || filename.equals("")) { filename=joptionpane.showinputdialog(this, "please enter filename."); if (filename.equals(null)) filename=""; } i wouldn't have filename.equals(null) in 2 places that, tried both separately , out of frustration tried too. nullpointerexception still occurs on line: if (filename.equals(null)) filename=""; is there way trap cancel button (null) or prevent it? filename.equals(null) // compare object should like filename == null // compare object references

wpf - Why does publish fail to publish System.Net.Http.dll? -

i have wpf application written in c# failing publish system.net.http.dll , system.net.http.webrequest.dll. when user launches application receive error: could not load file or assembly 'system.net.http, version=2.0.0.0, culture=neutral, publickeytoken=b03f5f7f11d50a3a' or 1 of dependencies. system cannot find file specified. to replicate issue: open vs2012 file -> new -> project -> visual c# -> wpf application right-click references -> manage nuget packages... add microsoft asp.net web api client libraries searching microsoft.aspnet.webapi.client right-click project -> properties click publish tab uncheck automatically increment revision each publish click publish now button note in publish\application files\wpfapplication1_1_0_0_0 folder see system.net.http.formatting.dll.deploy won't see other 2 files, system.net.http.dll.deploy or system.net.http.webrequest.dll.deploy . work-around for now, i've includ

build script - How to define repositories for all subprojects in Gradle -

i writing gradle scripts build lot of projects. using same repositories define repositories of sub-projects instead of defining in each of them. try move repositories definition build.gradle in individual project build.gradle in parent folder. subprojects{ repositories{ mavencentral() flatdir{ name 'uploadrepository' dirs '../../sharedlib' } } } however, sub-projects can't find repository definition @ all. moving other configurations in subprojects closure work. i've tried dependencies , properties configuration. work no problem. don't know why repositories work differently. when googling, can't find example of putting repositories inside subprojects, suspect doing wrong way. please tell me what's wrong. thanks! i figured out problem was. originally, missed settings.gradle in parent folder. (i don't know why dependencies configuration works without file) after put in, su

javascript for loop not executing function until end of loop, then iterating function n number of times -

i attempting load div's google map images loop adds 1 value of document.get. problem getlocation() call comes @ final iteration of loop, iterates loops n number of times. for(var = 1; < length; i++){ var longitude = 1.8612393999999999; var latitude = 50.7263312; document.getelementbyid("longinput").value = longitude; document.getelementbyid("latinput").value = latitude; var mapholder = "mapholderm"+i; document.getelementbyid("mapholdervalue").value = mapholder; themapholder=document.getelementbyid(mapholder); getlocation(); } getlocation() uses longinput , latinput values lat , lon variables, , themapholder place put target div image. maps able co ordinates , explaned below on final, or end of loop themapholder value. i think not issue getlocation(), , more how attempting use it. adding alert in getlocation() call , viewing elements on screen know elements populated though loop , change, location called n number of times aft

excel vba - Could not find installable ISAM error in VBA for .accdb file -

i trying connect ms excel vba program ms access database. while trying access *.mdb files working in both local drive , share drive. while accessing *.accdb file able connect in local drive. while trying connect .accdb file in shared drive getting error "could not find installable isam". here code trying, strdbpath = "\\shared drive path\database.accdb" set objconnection = new connection objconnection .connectionstring = "provider=microsoft.ace.oledb.12.0;" & _ "data source=" & strdbpath & ";" & _ "persist security info=false" & ";" & _ "pwd=" & pass .open end please provide resolution query. regards, susanta kumar patra

javascript - How to get chrome to autofill with asynchronous post -

i have form because being submitted asynchronously <input id="idfield" type="text" placeholder="enter id" /> <input type="button" value="submit id" id="submitbtn" /> $(document).ready(function () { $("body").on("click", "#submitbtn", function () { var id = $("idfield").val(); $.ajax({ type: "post", url: "post.php", data: { "id": id }, success: function () { alert("done"); } }); }); }); because of this, seems ( https://stackoverflow.com/a/11746358/1252748 ) google refusing autofill data i've entered in past. best way around this? something this? <form method="post"> <input id="idfield" type="text" placeholder="enter id" /> <input

still getting <Cordova/CDVViewController.h> file not found error in xcode -

i new in phonegap, making app via xcode; found error regarding cdvviewcontroller.h . however, file physically exists there. using xcode 4.6 , cordova 2.2.0. man, there lot of red herring answers question out there. worked me, , in documentation both phonegap 2.5 , 3.0 (see here: phonegap docs ios (look under "missing headers") , using xcode 4.6. in xcode, go preferences... > locations, click on advanced... button. make sure build location radio button set "unique". close out preferences , rebuild.

mysql - Select different values from one table based on another table -

so, 2 tables in question: userinfo: id(pk), users_id(fk users table), name, surname doctorpatient: id(pk), doctor_id(fk users table), patient_id(fk users table) the idea each doctor assigned few patients via doctorpatient table. want return array of arrays, each of inner arrays contains this: users_id(doctor), name(doctor), surname(doctor), users_id(patient), name(patient), surname(patient) can done using purely sql? tried this: select userinfo.users_id, userinfo.name, userinfo.surname, u2.users_id, u2.name, u2.surname doctorpatient right outer join userinfo on doctorpatient.doctor_id = userinfo.users_id left outer join userinfo u2 on doctorpatient.patient_id = u2.users_id but no matter combination of joins try, never comes out right. tried getting data in 3 separate queries , somehow result need using php, got that. edit: want this: array( subarray1(patient_id1,

sql - Sqlite query returns no value Android -

i have sql query not returning value, has data returned. following query code cursor cursor = db.query(crimedb.nome_tabela, crimedb.colunas, crimedb.id_cidade + "=" + idcidade + "" + " , " + crimedb.time + " >= datetime('" + datainicioformatada + "') , " + crimedb.time + " <= datetime('" + datafimformatada + "')" + " , " + crimedb.grupo_crime + "=" + idcategoria + "", null, null, null, null); read cursor if (cursor.movetofirst()) { { crime = new crime(); crime.setlastupadatetoken(ultimotokenvalido .getultimotokenatualizado()); listcrime.add(itemcrime); } while (cursor.movetonext()); } the query result is: select grupo_crime_id_grupo_crime, id_crime,

Moving first item with nested regions using Semantic Merge -

in rearrange file tool moving item first item within region moves #region line. these moves intended rearrange items within region. there seems odd things happening intermittently when using nested regions (such regions becoming out of line or opening region tags being removed.) how can avoid problems? need change configuration? i'm afraid behavior of tool @ moment, due regions considered comments parser. for example, #region member considered comment of method1 . so, if move method1 , comment, part of method1 , moved it. #region members public void method1() { ... } public void method2() { ... } #endregion we have noticed behavior , included in known issues list. work on it.

indesign - How to detect right-click on script UI button? -

using adobe indesign's extendscript (javascript language), how can add onclick function both left , right click events? adding left-click event easy. how add right-click event? [post answer update (much josh voights finding that)] if interested, wanted use in such way apply handler button this, works perfectly: whatbutton.addeventlistener("click", function(p){ if(!p.shiftkey){ if (p.button ==2) { alert("right click"); }else{ alert("left click"); } }else{ if (p.button ==2) { alert("shift right click"); }else{ alert("shift left click"); } } here's code sample kahrel.plus.com/indesign/scriptui.html includes watching right click. credit @fabiantheblind in this stackoverflow answer. var w =new window ("dialog"); var b = w.add ("button", undefined, "qwerty"); b.addevent

c# - How can I manage my SQLite DB versions in Monotouch? -

if release app, , in 2 weeks release new update, , need change database, whats solution?. example in android i´ve sqlite library override void check database version. thanks. there's lots of ways of doing this, here's system i've used in similar situations. keep schema (and non-transactional data) baseline, , keep version number in database. then, whenever update program, change schema , save change sql in own file. name files number files sequentially e.g. ( 000001addtablex.sql , 000002removecolumnx.sql , etc). write chunk of code checks folder changesets saved. then, if changeset number in filename greater current version stored in db, run changeset against database. this has following benefits if you're using source control, schema changesets saved , associated (presumably) related changes in code when check in code. your change set code well-tested because it'll exact code used during development. no matter how many updates end user has sk

data structures - How to Find a middle element in a link list without traversing the entire list? -

how find middle element in link list without traversing entire list . ? ...and @ maximum can use 2 pointers...how ? .... , length of list not given. i don't see how without traversing entire list unless know length. i'm guessing answer wants 1 pointer traversing 1 element @ time, while second pointer moves 2 elements @ time. way when second pointer reaches end, first pointer @ middle.

oracle - SQL to Find Number of Weeks an Employee Was Active Between Two Dates -

i have table list of dates employee became active/inactive , want count weeks employee active within date range. so table (ps_job) have values this: emplid effdt hr_status ------ ----- ------ 1000 01-jul-11 1000 01-sep-11 1000 01-jan-12 1000 01-mar-12 1000 01-sep-12 the query need show me number of weeks emplid active 01-jul-11 31-dec-12. the desired result set be: emplid weeks_active ------ ------------ 1000 35 i got number 35 adding results sqls below: select (next_day('01-sep-11','sunday') - next_day('01-jul-11','sunday'))/7 weeks_active dual; select (next_day('01-mar-12','sunday') - next_day('01-jan-12','sunday'))/7 weeks_active dual; select (next_day('31-dec-12','sunday') - next_day('01-sep-12','sunday'))/7 weeks_active dual; the problem can't seem figure out how create single query state

ruby on rails - Testing if an instance of a class receives a message when a class method that sends the message to all instances is called -

though correct, title needs explanation :) i have class: class character include datamapper::resource def self.tick_all all.collect &:tick end def tick # stuff end end as can see when character.tick_all called instances should receive tick invocation. works exptected: when fire console stuff in tick gets done. can't tests pass: describe ".tick_all" let(:instance) { factorygirl.create(:character) } "invokes #tick every instance" character.tick_all instance.should_receive(:tick) end end failed example: failure/error: instance.should_receive(:tick) (#<character:0x00000002fa4e28>).tick(any args) expected: 1 time received: 0 times the expectation should set before method call: describe ".tick_all" let(:instance) { factorygirl.create(:character) } "invokes #tick every instance" instance.should_receive(:tick) character.tick_all end end upd : cod

php - trouble with getting my mod_rewrite rules to run -

i have been trying several variations server redirect - seem fail. :( this url: "meaty-monster-bikes.zz-reviews.com/monster-bikes/p1c9.html" now data want collect in variables portion after "meaty-monster-bikes.zz-reviews.com/" so in case want "monster-bikes" , "p1c9" then using collected variables server can redirect to: "zz-reviews.com/index.php?p=1&c=9&k=monster-bikes" i have thried in .htaccess file: options +symlinksifownermatch rewriteengine on rewriterule ^[\.0-9-a-z]+/([-a-z]+)/p([0-9]+)pg([0-9]+)\.html$ index.php?p=$2&c=$3&k=$1 [nc,qsa,l] i tried : rewritecond %{http_host} ^[.+].zz-reviews.com/([-a-z]+)/[.+]$ [nc] rewriterule ^[\.0-9,:\/-a-z]+p([0-9]+)c([0-9]+)\.html$ index.php?p=$1&c=$2&k=%1 [nc,qsa,l] as far can see, both should work, neither do. this webpage: http://zz-reviews.com/index.php?p=1&c=9&k=monster-bikes if click on category "monster bike

ruby - RVM use list[0] -

is there "rvm use 1" or "rvm use list[0]" instead of typing entire version number. @ time , see list of may 5 or more rubies , can type single digit number instead of x.x.x. rvm gemset too. this possible in rvm 2.0 => https://docs.google.com/document/d/1xw9geeplowpcdddg_hopvk4oelxjmu3q5ficnt7ntac/edit?usp=sharing - link can comment

angularjs - $routeProvider not working in angular -

this app.js var cricketapp = angular.module('cricketapp', ['ngcookies']). config(['$routeprovider', function($routeprovider, $httpprovider, $cookies){ $routeprovider. when('/', { templateurl: '/partials/games-pending-entry.html', controller: homectrl }). when('game/:gameid',{ templateurl: 'partials/shortlist.html', controller: shortlistctrl }). otherwise({redirectto: '/'}); //$httpprovider.defaults.headers.post['x-csrftoken'] = $cookies.csrftoken; }]); and controllers.js function homectrl($scope, $http){ $http.get('/api/games-pending-entry').success(function(data){ $scope.games_pending_entry = data; }); } function shortlistctrl($scope, $http, $routeparams){ $scope.gameid = $routeparams.gameid; $http.get('api/get-players'

asp.net - How to access informations of the membership users with MVC4 -

i have website member section. there's admin manage users. want admin sees informations of other users, username , email. for now, registration page asks users username, password , email following this tutorial . memorises in db find, in userprofile table. problem access them. knew how mvc3 membership.getallusers().cast<membershipuser>() , where specify request. but, in mvc4, membership.getallusers() not permitted understand. have tried lot of different ways found on web, none solve problem. best i've found username, found in post : var model = roles.getusersinrole("statuswaiting").select(membership.getuser).tolist(); where "statuswaiting" role of users in db. but, (and others same result), have emailid appears in model, empty. does know how achieve this? i'm still looking haven't found yet. edit : if there's way achieve i'm mind opened edit2 : line above, membershipuser fields : comment, creationdate,email,isap

javascript - Selecting element with id attribute data bound via Knockout -

why element undefined when try select element using jquery : <ul data-bind="attr: {id: panelid}"></ul> panelid defined property in knockoutjs viewmodel: var vm = function () { var self = this, date = new date(); self.panelid = "panel-" + date.gettime(); $("#"+self.panelid).dosomthing(); // element undefined } inspecting page in chrome developer tool, can see id assigned <ul data-bind ... id="panel-1368039734501"</ul> the panelid property doesn't have observable . tried make observable same result. anyone? the issue id attribute applied in ko.applybindings call, try find element id before that. to avoid that, this: var vm = function () { var self = this, date = new date(); self.panelid = "panel-" + date.gettime(); } var vm = new vm(); ko.applybindings(vm); // adds id attribute $("#"+vm.panelid).dosomething

cannot resolve class 'jdbc' - Hibernate -

i starting out hibernate , have been trying wire h2. my hibernate.cfg.xml file looks this: <?xml version='1.0' encoding='utf-8'?> <!doctype hibernate-configuration public "-//hibernate/hibernate configuration dtd//en" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="connection.url">org.h2.driver</property> <property name="connection.driver_class">jdbc:h2:mem:test</property> <property name="connection.username">sa</property> <property name="connection.password"/> <!-- db schema updated if needed --> <!-- <property name="hbm2ddl.auto">update</property> --> <!-- sql dialect --> <property name="dialect">org.hibernate.dialect.h2dia

scala - What's the idiomatic way to map producing 0 or 1 results per entry? -

what's idiomatic way call map on collection producing 0 or 1 result per entry? suppose have: val data = array("a", "x:y", "d:e") what i'd result is: val target = array(("x", "y"), ("d", "e")) (drop without colon, split on colon , return tuples) so in theory think want like: val attempt1 = data.map( arg => { arg.split(":", 2) match { case array(l,r) => (l, r) case _ => (none, none) } }).filter( _._1 != none ) what i'd avoid need any-case , rid of filter . i pre-filtering (but have test regex twice): val attempt2 = data.filter( arg.contains(":") ).map( arg => { val array(l,r) = arg.split(":", 2) (l,r) }) last, use some/none , flatmap...which rid of need filter , scala programmers expect? val attempt3 = data.flatmap( arg => { arg.split(":", 2) match { case array(l,r) => some

testing - How to run test in parallel using Selenium(LiveServerTestCase) in django project? -

here problem: i have class inherited liveservertestcase. class imitate users(client) work - go site, filling fields, add files. need imitate multi users work need run class(function) in parallel. is there ways that, using standard python's things threads, processes , selenium-2? if not, please write simple example of suggestion. thanks! personally, distinguish functional (system) django tests , performance/load/multi-user tests based on tools multi-mechanize or locust . here's can try though. nose can run tests in parallel (see django_nose ). but, may have several problems this: as far every liveservertestcase opens browser on localhost:port , should give list of ports use in order avoid this port in use errors: ./manage.py test --liveserver=localhost:8082,8090-8100,9000-9200,7041 probably, creating , truncating database tables liveservertestcases cause tests fail (the behavior can changed though) also see: how emulate parallel multi-us

python - newbie Django smart/chained menu trouble -

i trying make chained select menu, have model: from django.db import models class health_plan(models.model): name = models.charfield(max_length=15) class doctors_list(models.model): name = models.charfield(max_length=30) specialty = models.charfield(max_length=15) health_plans = models.manytomanyfield(health_plan, related_name="doctors") location = models.charfield(max_length=15) def __unicode__(self): return self.name and forms.py : class specform(modelform): = doctors_list.objects.values_list('specialty', flat=true) unique = [('---------------','---------------')] + [(i,i) in set(a)] specialty = forms.choicefield(choices=unique) class meta: model = doctors_list class healthform(modelform): hplan = chainedforeignkey( health_plan, chained_field="specialty", chained_model_field="specialty", show_all=false, auto_choose=

SQL server convert entire table to a script? -

Image
i want create entire table script - columns, constraints, rows etc. script in sql server management studio. how do ? right click on database in object explorer. go tasks > generate scripts. choose "select specified objects" , expand tables , select table want. on "set script options" page, click advanced , make sure have table related stuff set true. there field in advanced called "types of data script" - set "schema , data" include insert statements. note: i'm referencing management studio 2012 sql standard. assume it's same 2008, wrong...

RavenDB Periodic Backups: How can I "clear the ledger" and force a full backup every so often? -

when enable ravendb's 'period backups' bundle , ravendb following: backs entire database. at every interval (or 'n' minutes), ravendb makes incremental backup (or delta backup) of changes occurred since last interval. i'm comfortable configuration 1 caveat. every week, i'd "clear ledger" , force ravendb backup entire database , resume making incremental backups new starting point. how can in automated fashion? from raven.backup utility documentation : incremental - optional. when specified, backup process incremental when done folder previous backup lies. if dest empty folder, or not exist, full backup created. incremental backups work, configuration option raven/esent/circularlog has set false. so solution problem is: every week, delete dest directory. this force ravendb create full backup.

python - Function that takes a string as input and counts the number of times the vowel occurs in the string -

so new python , in process of learning basics. trying create function counts number of vowels in string , returns how many times each vowel occurs in string. example if gave input, print out. >>>countvowels('le tour de france') a, e, i, o, , u appear, respectively, 1,3,0,1,1 times. i made helper function use, i'm not sure how use it. def find_vowels(sentence): count = 0 vowels = "aeiuoaeiou" letter in sentence: if letter in vowels: count += 1 print count and thought maybe use formatting them in write places, not sure notation used example, 1 of lines function be: 'a, , i, o, , u appear, respectively, {(count1)}, {(count2)}, {(count3)}, {(count4)}, {(count5)} times' i not sure how able fit above in function. you'd need use dictionary store values, since if directly add counts lose information vowel counting. def countvowels(s): s = s.lower() #so don't have worry upper , lower cases

c# - Where/How to instaniate an object to handle null reference exception -

hey guys kind of simple question, i'm not sure where/how initialize new object instance don't error. have class object(contact) has class object(contactinfo) , user decides not input(instantiate) contactinfo object. later when try search via contact.contactinfo, error. below have line of code error , have 2 classes: foreach (var contact in contacts) { if (string.equals(contact._contactinfo.city.tolower(), city, stringcomparison.currentculture)) { contactsbycity.add(contact); } } and 2 classes: public class contact : person { private contactinfo info; private contactinfoloader loader; public contactinfo _contactinfo { get; set; } public contact() { } public contact(contactinfo _info) { info = _info; } public contactinfo getcontactinfo() { loader = new contactinfoloader(this); return loader.gathercontactinfo(); } } public class contactinfo { public string pho

objective c - Reading Multiple Dragged-n-Dropped Files -

i have small window inside main xib (mainmenu.xib) nsimageview control os x application. view control has nsimageview subclass supposed accept files user brings (drag n drop). since have no experience in developing mac application objective-c, i've searched around, checking out sample projects apple, , got idea. well, make story short, i've copied code posted here . works. great... following concise version. - (nsdragoperation)draggingentered:(id <nsdragginginfo>)sender{ return nsdragoperationcopy; } - (nsdragoperation)draggingupdated:(id <nsdragginginfo>)sender{ } - (void)draggingexited:(id <nsdragginginfo>)sender{ } - (bool)preparefordragoperation:(id <nsdragginginfo>)sender{ return yes; } - (bool)performdragoperation:(id<nsdragginginfo>)sender { nspasteboard *pboard = [sender draggingpasteboard]; if ([[pboard types] containsobject:nsurlpboardtype]) { nsurl *fileurl = [nsurl urlfrompasteboard:pboard];

continued trouble with classes in python 3.2 -

in below code, working @ first when want tell me card number dealer has returning sort encrypted stuff don't understand. [<__main__.card object @ 0x025a4e50>] how return corresponding card number? also said may need use __eq__ when comparing things opposed way explain why, , how use __eq__ ? below code program trying work, blackjack game. from random import* class card(object): def __init__(self,suit,number): self.suit=suit self.number=number class deckofcards(object): def __init__(self,deck): self.deck=deck self.shuffledeck=self.shuffle() #print(self.shuffledeck) def shuffle(self): #print('this shuffle function') b=[] count=0 while count<len(self.deck): a=randrange(0,len(self.deck)) if not in b: b.append(self.deck[a]) count+=1 return(b) def deal(self): if len(self.shuffledeck)>0:

actionscript 3 - Adobe Flex/Air Project Importing an .as Class -

i've started looking @ basic adobe air apps, feel im stuck @ first hurdle. i've found action script library use http://charlesbihis.github.io/actionscript-notification-engine/ however i'm struggling figure out how library flash builder 4.7 i've exported project can download , see errors http://www.mediafire.com/?pu4cm1pndlaxo20 if share light/knock project file uses demo code library's webpage @ see hell going on appreciated. many thanks owen the simple answer package name library used com.charlesbihis.engine.notification put in notification meanwhile when writing code inside mxml, consider putting inside <![cdata[ ... ]]> blocks, this: <fx:script> <![cdata[ // code goes here ]]> </fx:script>

What is the proper way to serve mp4 files through rails to an Ipad? -

we're having trouble serving mp4s play on ipad using default rails 3 app. mp4 served correctly when viewing route in chrome , other browsers on desktop. here our code: file_path = file.join(rails.root, 'test.mp4') send_file(file_path, :disposition => "inline", :type => "video/mp4") we hit 0.0.0.0:3000/video/test.mp4 view video , presented cannot play icon on ipad. we've tried modifying various headers "content-length", "content-range", etc don't seem affect end result. we've tried using send_data extent i.e. file.open(file_path, "r") |f| send_data f.read, :type => "video/mp4" end the same video serves fine public folder when viewed on ipad. what proper way serve mp4 files through rails ipad? the problem seems rails doesn't handle http-range requests ios needs streaming mp4s. this our solution development, (using thin our server): if(request.headers[&

sum - SQL script to check a value then if found increment a field by a value of 1 -

im trying write script pull information table called 'bookings', contains column gives length of each booking called 'hours'. values in column shown 1.0 60 minutes, 0.75 45 minutes, 0.5 30 minutes example. script needs count amount of bookings of particular length , return value, example using sum , case statment each... sum(case when hours = 1 1 else 0 end) '60 mins', sum(case when hours = 0.75 1 else 0 end) '45 mins', sum(case when hours = 0.5 1 else 0 end) '30 mins', sum(case when hours = 0.25 1 else 0 end) '15 mins' my problem need record bookings on 60 minutes , split them 1 of these 4 groups, example 1.5 hours need add value of +1 60 minute case statement , +1 count 30 minute case statement value, the way think of doing create temporary table columns 60, 45, 30 , 15 count values update table +1 if result found, 1.25 update #temptable column(60) +1 , column(15)+1. not sure how this, appreciated. thanks simon