Posts

Showing posts from February, 2015

Import Google Spreadsheet into a Google Spreadsheet -

i'm trying import url query of google spreadsheet google spreadsheet. on webpage use url this: https://docs.google.com/a/chiseledimages.com/spreadsheet/tq?tqx=out:html&tq=select%20c,d,e,f,g,h,i%20where%20%28a%20contains%20301%29&key=0auoqku9htnwvdg5 create table referenceing specified doc , selecting columns column equals clients account number, in case 301. what want have spreadsheet automatically fill data url. tired =importdata(" https://docs.google.com/a/chiseledimages.com/spreadsheet/tq?tqx=out:html&tq=select%20c,d,e,f,g,h,i%20where%20%28a%20contains%20301%29&key=0auoqku9htnwvdg5 ") seemed import html , not fill sheet data. want able client can have google spreadsheet auto filled data @ times, while not having direct access original spreadsheet clients data. i'm not sure if you're looking for, typically use importrange pull data 1 sheet another. http://support.google.com/drive/bin/answer.py?hl=en&answer=155183

asp.net - How to store a value in a variable and maintain this value in another method in AJAX -

in application getting value sql stored procedure getting value in ajax method.now want pass value method in ajaxscript page.what want do.i have tried session ,but not working. if (str1.length > 0) { var bu = str1.split('|||') (var icount = 0; icount < $(sddlbusinessunit).options.length; icount++) { if ($(sddlbusinessunit).options[icount].value == maincondetails[3]) { $(sddlbusinessunit).options[icount].selected = true; $(sddlsite).length = 0; var siteid = maincondetails[4]; //$_session["id"] = siteid; if (($(sddlbusinessunit)).selectedindex > 0) { displayloadingimage(($(sddlbusinessunit))); var url = requesturl + '?mode=bu&bu=' + (($(sddlbusinessunit))).opt...

android - skip permission to connect to usb Accessory -

i don't want take permission connect usb accessory want connect specific usb accessory. possible . have read on android.com follows note: if application uses intent filter discover accessories they're connected, >automatically receives permission if user allows application handle intent. if not, >you must request permission explicitly in application before connecting accessory. so possible so. please help. thanks gaurav you can listen intent code: usbaccessory accessory = (usbaccessory) intent.getparcelableextra(usbmanager.extra_accessory); however there information must included in manifest: http://developer.android.com/guide/topics/connectivity/usb/accessory.html#manifest this allow filter devices based on number of attributes.

objective c - Issue with Facebook feed dialog -

i'm trying implement facebook dialog feed, doesn't show anything. have followed : post user's facebook wall iphone using latest fbconnect sdk and: http://developers.facebook.com/docs/reference/dialogs/feed/ here code: -(void) facebookpost{ nsstring *kappid = [[nsstring alloc] initwithstring:@"383032031757454"]; nsmutabledictionary* params = [nsmutabledictionary dictionarywithobjectsandkeys: kappid, @"app_id", @"http://developers.facebook.com/docs/reference/dialogs/", @"link", @"http://fbrell.com/f8.jpg", @"picture", @"facebook dialogs", @"name", @"reference documentation", @"caption", @"using dialogs interact users.", @"descripti...

android - Creating XML Layout file composed from other XML files? -

i know can seem weird question me handy if compose layout xml set of other xml files pointed main xml file. reason have list item views defined in xml , reuse in other places. possible or way coping , pasting it? you can include different layout files in single layout using 'include' tag <linearlayout> <include layout="@layout/toinclude1" /> <include layout="@layout/toinclude1" /> </linearlayout> another way viewstub. if want load asynchronously layout can have: <viewstub android:id="@+id/stub" android:inflatedid="@+id/subtree" android:layout="@layout/mysubtree" android:layout_width="120dip" android:layout_height="40dip" /> and in code when want can write: viewstub stub = (viewstub) findviewbyid(r.id.stub); view inflated = stub.inflate(); for reference: http://developer.android.com/reference/android/vi...

c++ - Mongoose Server callback loop -

after looking c library implemented web server, taught mongoose. have made work through several examples make call callback function treats incoming , outgoing data. using on windows, compiling , debugging visual studio 2008. i called session , follows: int chttpscom::session( void ) { struct mg_context *ctx; const char *options[] = { "listening_ports", "443s", #ifdef _debug "ssl_certificate", "c:\\temp\\cert.pem", #else "ssl_certificate", "cert.pem", #endif null }; ctx = mg_start( &callback, null, options ); if( !ctx ) return 1; //getchar(); // wait until user hits "enter" while ( leaveit == false ); sleep(3500);// without won't work mg_stop( ctx ); return 0; } 100% of examples have noticed examples use getchar synchronize end of session ending if callback execution. have leaveit flag set after post message. if don't use sleep above, deadlock i...

asp.net - When is the web.config file "executed"? -

is executed / read-by-the-server every time page on site loaded? the web.config loaded memory when application created. typically first request page/resource in application. iis (asp.net) monitors web.config changes , restart application if change made. if question "will web.config settings automatically update when file changed?" answer yes application restarted can result in unexpected behavior including session , data loss. some of above statements not true , recommend reading this: http://msdn.microsoft.com/en-us/library/ms178685.aspx

How can I deploy a application that requires static IP to Heroku? -

i have rails application hosted on heroku need integrate 3rd party payments provider. payment provider requires application have static ip incoming , outgoing https requests. want deploy proxy on linode vps can relay information proxy. relaying request service provider seems easy, use ip. can relay requests coming service provider heroku application? can relay request using url ( https://myapp.herokuapp.com ) ? what recommended proxy server use? it's better into: https://devcenter.heroku.com/articles/quotaguardstatic if have credit card , app has no traffic (250 request , 100mb of traffic bandwidth) quotaguard has free starter plan (to add heroku heroku addons:add quotaguardstatic:starter ). here plans: quota guard static plans

silverlight - How to restore original position after translation using TranslateTransform? (Windows Phone C#) -

i have image translating along x , drag gesture. handling dragdelta event translating image using translatetransform object this. translate.x += e.horizontalchange; want restore original position of image on dragcompleted event. noticed margin property not changed during translation. property (or possibly method) can use restore original position of image thank in advance transforms, such translate transform, happen on top of other layouting (such margins etc.) to reset position, restore translate transform whatever before started dragging. // _originalx , _originaly initialized in dragstart handler translate.x = _originalx; translate.y = _originaly

r - How to change warning setting? -

i trying debug function. display warnings when occur don't understand how change warning settings. set options(warn=1) read more in ?options

Android ScrollView scrollTo() method not working with TextView? -

for example, have layout this: <scrollview> <linearlayout> <linearlayout> ... </linearlayout> <linearlayout> ... </linearlayout> <linearlayout> <textview> </textview> </linearlayout> </linearlayout> </scrollview> my textview have long content. can scroll scrollview manually end of textview content. in code, write: scrview.scrollto(0, 800); , scrview scrollview. supposed scroll middle of textview content. when running, scrolled start of textview , can't scroll through textview content. does know causing problems? edit: found it. seems call scrollto soon. using scrview.post(new runnable() { public void run() { scrview.scrollto(0, 800); } }); instead , works. posted answer getting same problem. first of all, if linearlayouts have same orientation, why don't...

xml - Serialize and deserialize in Android -

i'm developing restful web services in java using jersey technology. have developed server side. the client side of project android application. have done communication between server , client (i can send information through android , receive in web service). problem i'm having problems serialization , deserialization problems in client side. the web service side using jersey automatically, didn't find client in android serialize , deserialze in xml. suggestion? do have manually (handling xml , deserializing whiles, , so..)?

model view controller - Spring MVC: how to download Excel from DB -

i have problem spring mvc , excel. store excel file in database lob. part of entity database postgresql @lob @column(name = "exel") private string exel; next db , user can download web page controller @requestmapping(value = "/downloadexeltemplate.xls", method = requestmethod.get) public void downloadexeltemplate(httpservletresponse response) throws ioexception { response.setcontenttype("application/x-msexcel"); exeldto exel = service.getexel(new long(1)); inputstream = new bytearrayinputstream(exel.getexel().getbytes()); bufferedwriter outex = new bufferedwriter(new filewriter("out.xls")); outex.write(exel.getexel()); outex.close(); servletoutputstream out = response.getoutputstream(); out.write(exel.getexel().getbytes()); is.close(); out.close(); } and not proper xls file bugs. please me. wrong? when file stream same effec...

html - Having trouble keeping hyperlink style specific to one class/ id -

i want apply different hyper link style following 2 things: any links within <p> tags in #currentpage_content div id. any links <h3> tags .profile class. it sounds pretty simple can't see right.. i've tried things like: #currentpage_content a:hover{...} and #currentpage_content p a:hover{...} but reason applied navigation bar links though they're outside #currentpage_content's div! i figured out ( think).. #currentpage_content a.p:hover{...} but link style aren't being applied @ when should be. could please @ bullet points above , tell me exact syntax/order of words need achieve 2 bullet points? to make response easier here's style i'm trying apply: a:link, a:visited, a:hover, a:active { font: inherit; color: grey; text-decoration: none; border-bottom: 2px solid #d4ffaa; } a:hover, a:active {background-color: #d4ffaa;} here fiddle solution trouble.

regex - MSBuild Community Taks RegexReplace remove trailing slash from path -

i trying use msbuild community tasks remove slash end of outputpath this have far. <regexreplace input="$(outputpath)" expression="\$" replacement="" count="1"> <output itemname="formattedoutputpath" taskparameter="output" /> </regexreplace> <message text="@(formattedoutputpath)"/> unfortunately message returns path still slash on end. path c:\mydirectory\ it looks expression incorrect can help? slash using escape character, in pattern have escape slash character slash: <regexreplace input="$(outputpath)" expression="\\$" replacement="" count="1"> <output itemname="formattedoutputpath" taskparameter="output" /> </regexreplace> <message text="@(formattedoutputpath)"/> to better understand escaping see following examples: $ represents end of line/string \$ represents ...

ios - Convert between UIImage and Base64 string -

does know how convert uiimage base64 string, , reverse it? i have below code; original image before encoding good, blank image after encode , decode it. nsdata *imagedata = uiimagepngrepresentation(viewimage); nsstring *b64encstr = [self encode: imagedata]; nsstring *base64string = [self encodebase64:imagedata]; swift first need have image's nsdata //use image name bundle create nsdata let image : uiimage = uiimage(named:"imagenamehere")! //now use image create nsdata format let imagedata:nsdata = uiimagepngrepresentation(image)! //or next possibility //use image's path create nsdata let url:nsurl = nsurl(string : "urlhere")! //now use image create nsdata format let imagedata:nsdata = nsdata.init(contentsofurl: url)! swift 2.0 > encoding let strbase64:string = imagedata.base64encodedstringwithoptions(.encoding64characterlinelength) swift 2.0 > decoding let datadecoded:nsdata = nsdata(base64encodedstring: strbase64, op...

java - Need help storing/retrieveing data -

a user has arraylist of numbers. numbers correspond applications have access to. applications have different entitlement numbers(ie- 3, 72, etc.). want store data in map when user logs in, can input numbers map , applications entitled to. however, applications require 2 3 entitlement numbers. example, 1 entry be: ("101 , 234", "application 1"). wondering if there ideal way of retrieving of values map that users entitlement numbers satisfies. how have it, program compares users data each application , confirms or denies access. seems inefficient. appreciated! note: reading applications , numbers in xml, can store them wish. if there large numbers of numbers required per application, best approach use set intersection. if numbers contiguous or @ least dense, can optimize bitset. 1 or 2 numbers though, i'd recommend testing each number individually, since it's faster full set operations.

How to write a drop-in replacements for fundamental type (float) that override operator== in C++? -

we can not compare binary floating point directly. writting drop-in replacements class float override bulti-in compare operators:: template<class u> class float { private: u val; public: float(u v = 0): val(v) {} operator u() const { return val; } friend bool operator<(float a, float b) { return a.val + 1e-6 < b.val; } friend bool operator==(float a, float b) { return !(a < b) && !(b < a); } friend float operator*(float a, float b) { return a.val * b.val; } template<class t> friend float operator*(t a, float b) { return * b.val; } template<class t> friend float operator*(float a, t b) { return a.val * b; } }; now can write this:: #include<assert.h> int main() { float<double> = 0.2, b = 0.02; assert(a * == 2 * b); } however, code show unexpected behavior:: #include<complex> int main() { std::complex< float<dou...

parsing XML with HTML content without CDATA section using java xml parsers -

the xml files need parse have html tags inside nodes, there no cdata sections existing html content. there there way parsing xml file gives text along html tags using java xml parsers. , should not edit xml files. following xml file trying parse using java xml parsers: <assessmentitem xsi:schemalocation="http://www.imsglobal.org/xsd/imsqti_v2p0 imsqti_v2p0.xsd" identifier="choice" adaptive="false" timedependent="false" title="200007" xmlns="http://www.imsglobal.org/xsd/imsqti_v2p0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"> <responsedeclaration identifier="response" cardinality="single" basetype="identifier"> <correctresponse> <value>c</value> </correctresponse> </responsedeclaration> <outcomedeclaration identifier="score" cardinality="single" basetype="int...

c# - factory pattern, need to know the actual implementation type? -

im trying write results sproc textfile. have 3 scenarios: sproc takes no parameters. sproc takes parameters. sproc takes parameters , there loop increments parameters. scenario 1 , 2's data stored in list since single row of results. scenario 3's data stored in data table. i thinking of using factory pattern this, 3 different classes each implementing specific interface, , factory determine of 3 required. the issue once method finished , completion event has been risen, need know scenario implemented (datatable vs list) issue? if so, please explain why + possible solution? note: clarify, not plea of, please write program. thanks time, appreciate it. whenever need know actual type behind interface, might have chosen wrong point introduce interface. looks here. it looks me want separate concern doing logic (which produces data) logic of logging results (in case text file, there might other targets, right?). why not introduce interface resultloggin...

Getting the CurrentUserID from Websecurity directly after login (C#/ASP.NET) -

i have website (c#/asp.net) form user can register account (it default template of vs11) , after filled in , user clicks register, creates account , logs in user (which works great). after step want userid assigned, doesn't work. i've put breakpoint there see values of both "currentuserid" , "websecurity.currentuserid" have -1 value. next step user gets redirected next page, , on page these functions work. thought able userid user has gotten logged in in first line of code provided here. so question is, why doesn't work here? noobish this, missing something. websecurity.login(username, password); int currentuserid = websecurity.currentuserid; // doesn't work, returns -1 <here wish update other tables need user id> response.redirect("~/welcome.cshtml"); thanks! you should use websecurity.getuserid(username) websecurity.login(username, password); int currentuserid = websecurity.getuserid(username); response.redire...

hyperlink - Get the full domain Url from a Asp.Net Web App in a Console App -

im doing console app has send scheduled emails. in 1 of emails have put url of page, this: var message = string.format("go our web site <a href=\"" + "http://" + request.url.authority + url.action("action", "controller", new { requestid = request.id }) + "\">click here</a>"); obviously request.url.authority work in asp.net mvc3 app have. i'm not sure if there way full route name in console app. maybe if reference web app in console app... dont know else do. a console app doesn't run in context of website, won't have access related website. you can configure ahead of time though in app.config file. <appsettings> <add key="url" value="http://www.yoursite.com/" /> </appsettings> and in code can value: configurationmanager.appsettings["url"]

c - Getting currently date on a variable -

i have variable: char date[11]; , , need put inside current date, example 29/06/2012 . so i'll like: printf ("%s\n", date); and output be: 29/06/2012 i found option print date in words, fri, june 2012 , not actual date in numbers. so how can print current date in numbers? you can reference function strftime . i'll let figure out how use :-) since claimed have searched it, i'll provide answer: // first of all, need include time.h #include<time.h> int main() { // you'll raw time low level "time" function time_t raw; time(&raw); // if notice, "strftime" takes "tm" structure. // that's we'll doing: convert "time_t" "tm" struct tm *time_ptr; time_ptr = localtime(&raw); // "tm", can format buffer char date[11]; strftime(date, 11, "%d/%m/%y", time_ptr); printf("today is: %s\n", date); }

ruby forms in div elements -

i'm having issue form generated ruby isn't included inside #content div, because form generated after html read browser (sorry if sound moron on this) -- edit update - view source -- the code below generates email box , submit button outside of content box <div id="content"> <!-- text here --> <form accept-charset="utf-8" action="/password_resets" method="post"> <div style="margin:0;padding:0;display:inline"> <input name="utf8" type="hidden" value="&#x2713;" /> <input name="authenticity_token" type="hidden" value="afmtpsac93w1umcnouhy9xmbvtm7fe1vnfvzknp0kms=" /> </div> <div class="field"> <input id="email" name="email" placeholder="email@website.com" type="text" /> </div> <div class="actions"> <input...

gcc - makefile for multiple .c files, same directory -

i need create makefile 4 files: q4.c, q3.c, q2.c, q1.c format of makefile these 4 like? know necessary flags all, preprocess, compile, assemble, , clean, format of file 4 programs? side notes: programs in same directory. thank help- dave l makefile comprehensive , flexible way of describing build process actions, dependencies etc. there lot of possible ways of writing , there never simple single answer question. sake of example, here how makefile simple case: bin = q1 q2 q3 q4 all: $(bin) clean: $(rm) $(bin) it if add , remove source files , each file should compiled standalone executable: src = $(wildcard *.c) bin = $(patsubst %.c,%,$(src)) all: $(bin) clean: $(rm) $(bin) and can more , more complex depending on size , requirements of project. i'd recommend start simple above example , read make documentation feeling of can do. also, make quite old, complicated technology. takes lot of time , practise master , gives little in response. the...

Visual Studio: Build several configurations in one step? -

i have several build configurations of project i'd run in 1 step. have manually build each configuration (debug, profile, release configs) , it's getting annoying. there command line feature can use? make "a little" easier because can tell script build each configuration regardless of 1 that's started (i'm doing end-of-build distribution of libs , headers). use build->batch build... menu. allow build/rebuild/clean subset of configurations, or of them.

With boost::gil, how do I get a gray8s view of a gray8 unsigned image or view -

using boost::gil how create view applies gray8 image or view , provides gray8s view? what i'd expect: for these 2 cases i'd expect each pixel value in view equal corresponding pixel value in source image minus 128 signed_gray8s_view_t some_gray8s_view = signed_view(some_gray8_image); signed_gray8sc_view_t some_gray8s_view = signed_view(some_gray8c_image); for these 2 cases i'd expect each pixel value in view equal corresponding pixel value in source image (ie, no effect, identity mapping) signed_gray8s_view_t some_gray8s_view = signed_view(some_gray8s_image); signed_gray8sc_view_t some_gray8s_view = signed_view(some_gray8sc_image);

javascript - How to resolve map zoom and page zoom conflict on mobile website? -

i have website displays mashup on google map. when try zoom map on mobile web browser, page gets zoom instead on occasions. there html, css or javascript method prevents page zooming while fingers touching map? i tried <meta name='viewport' content='user-scalable=no'> , prevents map zooming well. this can done using gesture events.you can call touchstart event, , call e.originalevent.preventdefault(); //if using jquery this prevent page zoom in.

dependency injection - Why inject dependencies? -

assuming i'm using ioc container, why must types have dependencies injected ? why can't every type assume container exists , retrieve dependencies needs itself? disadvantages latter approach? i'm aware of property injection don't want suggested answer though save on having long parameter list constructors in more complex types. , doesn't save on code need type/maintain. oh, , i'd prefer have dependencies readonly/final (personal preference). so here's typical example of constructor injection in c#: public class calculator { private readonly iadder _adder; private readonly isubtractor _subtractor; private readonly imultiplier _multiplier; private readonly idivider _divider; public calculator(iadder adder, isubtractor subtractor, imultiplier multiplier, idivider divider) { _adder = adder; _subtractor = subtractor; _multiplier = multiplier; _divider = divider; } } ...

getting namespace uri by giving prefix in xslt -

i using xsl 1.0. need namespace uri prefix. <soapenv:envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:a1="http://example.com/arthemetic/integers/a1"> <soapenv:header> </soapenv:header> <soapenv:body> <a1:add> </a1:add> </soapenv:body> </soapenv:envelope> i want namespace uri prefix a1 http://example.com/arthemetic/integers/v1 here code trying out, <xsl:template match="/"> <xsl:variable name="operationname"> <xsl:value-of select="name(/*[local-name()='envelope']/*[local-name()='body']/*[1])"></xsl:value-of> </xsl:variable> <xsl:variable name="prefix"> <xsl:value-of select="substring-before($operationname, ':')"></xsl:value-of> </xsl:variable> <xsl:variable name="ns-node" select="namespace::node()[.= $prefix]" /> dfadsfdfadsf ...

Where is Facebook's signed request going? google app engine python -

i confused, because documentation states when user registers website, using facebook registration form, supposed receive signed request. not know it. replies appreciated. using python in google app engine , want know signed request sent. when user sign-in on facebook complete, app post request. refer helpful blog posts like this , this

android - Retrieving the bound value of a spinner -

want selected value of spinner. first, created string-array in res/values/string <string-array name="location"> <item name="auh">abu dhabi</item> <item name="aan">al ain</item> <item name="dmm">dammam</item> </string-array> spinner definition in layout: <spinner android:id="@+id/spnorigin" android:layout_width="fill_parent" android:layout_height="wrap_content" android:entries="@array/location"/> now need complete button click body, if user selects abu dhabhi, should return auh. getselectitem returns abu dhabi, not value behind this. if try this, can approach allow me name attribute? string[] _location =getresources().getstringarray(r.array.location); button handler: bttprocess.setonclicklistener(new view.onclicklistener() { public void onclick(view v) { }); ...

python - Is it more pythonic to close a function with return or through indentation? -

if have function not need return variable, considered better coding practice close function this: def foo(): """code""" return # more code or this? def bar(): """code""" # more code i'd use bare return exit function. @ end of function leaves me wondering if meant return , forgot finish.

add class to links of active slides in jquery cycle plugin -

i want add class current slide's link. javascript code $(document).ready (function() { $('#slideshow').cycle({ fx: 'fade', speed: 500, timeout: 1000, pause: 1, cleartype: true, cleartypenobg: true, pager: '#forpager', pageranchorbuilder: function(idx, slide) { return '#forpager li:eq(' + (idx) + ')'; } }); $('#forpager ul li a').click(function(){ $('#forpager ul li a').removeclass("active"); $(this).addclass("active"); }); }); and html code slideshow is <div id="forslideshow"> <div id="slideshow"> <div class="image"> <center><img src="images/pic1.jpg" alt="renny"/></center> </div> <div class=...

javascript - Limiting framerate in Three.js to increase performance, requestAnimationFrame? -

i thinking projects 60fps not totally needed. figured have more objects , things ran @ 30fps if run smoothly @ framerate. figured if edited requestanimationframe shim inside of three.js limit 30 way. wondering if there better way using three.js provided. also, give me kind of performance increase thinking. able render twice many objects @ 30fps @ 60? know difference between running things @ 30 , 60, able run @ smooth constant 30fps? i use webglrenderer, , fall canvas if needed except projects targeting 1 specifically, , typically webgl shader projects. what this: function animate() { settimeout( function() { requestanimationframe( animate ); }, 1000 / 30 ); renderer.render(); }

java - Exclusion from general-purpose exception chaining facility in 'remote' exceptions -

consider of ' remote ' exceptions: javax.jms.jmsexception or java.rmi.remoteexception both exclude common pattern of exception chaining having detail or linked exception properties. when print stack trace containing 1 of exceptions you'll trimmed stack trace. full stack trace need additional dancing tambourines. what reason remote exceptions designed way? edit: i'm browsing sources of java 1.6.0_26. on 2 arguments constructor public remoteexception(string s, throwable cause) of java.rmi.remoteexception . can see next code initcause(null); // disallow subsequent initcause . seems intentional decision in java se 6 that. but acording common practice initcause() has it's grand purpose construct exceptions chain ! don't remember source i'm confident best practice of creating custom exception: 1. expose of constructors of super class 2. don't brake exceptions chain (call throwable.initcause() in other words). achived calling sup...

c# - Initializing OpenGL with depth buffer and depth testing -

i initialize opengl depth-buffer in platform independent manner without using glut. how remove hidden-surface in opengl scene using c# wrapper. i'm not using glut can't use glutinitdisplaymode. idea? for more details: i found these steps hidden-surface removal: request z-buffer via glutinitdisplaymode: // glut_depth request depth-buffer glutinitdisplaymode(glut_rgba | glut_double | glut_depth); enable z-buffer depth testing: glenable(gl_depth_test); clear z-buffer when clear color buffer: // clear color , depth buffers glclear(gl_color_buffer_bit | gl_depth_buffer_bit); as know, glutinitdisplaymode 1 of glut functions. can eliminate call without bad effect. if not, alternative pure opengl calls trick. i'm using c# wrapper written (colin p. fahey) glut not opengl! whatever glut does, c# wrapper offers well, , better. need depth buffer , enabling depth testing . update in reflection of question edit the exact steps taken depth b...

ruby on rails - error using rspec for devise -

i using rspec testing devise authentication. following code require 'spec_helper' describe user describe "user registration" "allows new users register email address , password" "/users/sign_up" fill_in "email", :with => "abc@example.com" fill_in "password", :with => "abc123" fill_in "password confirmation", :with => "abc123" click_button "sign up" response.should have_content("welcome! have signed successfully.") end end end i getting following error. "nomethoderror:undefined method `get' #" you using controller methods , integration test methods (capybara) in model spec. not work. a model spec (unit test) contain things like: test validators/relationships test scopes methods of model check out series of blog articles on testing rspec, should help: http://everydayrails.com/2012...

android - alarm takes n multiple times -

i trying make alarm application take ‘n’ number of times user , buzz @ times , stores difference in timing next user accesses application, stored difference default. here code of main activity: public void startalert(view view) { edittext texth = (edittext) findviewbyid(r.id.hours); int h = integer.parseint(texth.gettext().tostring()); edittext textm = (edittext) findviewbyid(r.id.minutes); int m = integer.parseint(textm.gettext().tostring()); edittext texts = (edittext) findviewbyid(r.id.seconds); int s = integer.parseint(texts.gettext().tostring()); calendar cal = calendar.getinstance(); cal.set(calendar.hour, h); cal.set(calendar.minute, m); cal.set(calendar.second, s); intent intent = new intent(this, alarmservice.class); pendingintent pendingintent = pendingintent.getactivity(this, 12345, intent, pendingintent.flag_cancel_current); alarmmanager alarmman...

focus - Jquery selecting multiple events -

$('.searchbox').blur(function() { $("#gohan").hide(); }); $('.dropdown').blur(function() { $("#gohan").hide(); }); hi, have searchbox when type in letters, dropdown (id=gohan) consisting of ul numerous li "search results" appears. want dropdown disappear whenever focus on dropdown or searchbox gone, ie click on that's not in searchbox/ul/li. 2 event handlers work fine separately, don't know how make them work together. tried string them like $('.dropdown, .searchbox').blur(function() { but resulted in catastrophic failure. idea on condition/selector fix this? i've try encapsulate both dropdown , searchbox 1 div containing them , selecting big container, didn't work either. if searchbox isn't out of focus, there must check see if dropdown isn't out of focus too. then, if both aren't in focus, hiding. right logic? it easier hide #gohan if watched document.body clicks , focus , insp...

ruby on rails - User Authorization with CanCan: NoMethodError -

im using cancan authorization in app. have of each users information stored @ /users/2 or users/3 or /users/4 , on. my problem when user logs in can amend url , see other users sensitive content. how can use cancan prevent user (say users/2) seeing (users/3) ? when add "load_and_authorize_resource" users controller following error: nomethoderror in userscontroller#show undefined method `user_id' #<user:0x007fee61e90b90> models class ability include cancan::ability def initialize(user) user ||= user.new # guest user (not logged in) if user.has_role? :admin can :manage, :all can :access, :rails_admin can :dashboard else can :manage, user, :user_id => user.id end controllers class applicationcontroller < actioncontroller::base protect_from_forgery rescue_from cancan::accessdenied |exception| redirect_to root_path, :alert => exception.message end class userscontrolle...

perl - multiple line tag content replacement if content matches -

i not proficient in perl, awk, or sed , have been searching web solution problem while now, wasn't successful. i replace <math> ... </math> with <math>\begin{align} ... \end{align}</math> if ... contains \\ . problem string between <math> tags can span multiple lines. managed replace tags within 1 line sed couldn't run multiple lines. any simple solution perl, awk, or sed welcome. lot. use separate expressions each tag , script immune multilinedness: sed -e 's,<math>,&\\begin{align},g' -e 's,</math>,&\\end{align},g' edit: multiline awk version: awk '/<math>/,/<\/math>/ { if (index($0, "<math>")) { a=$0 } else { b = b $0 } if (index($0, "</math>")) { if (index(b,"\\\\")) { sub("<math>","&\\begin{align}", a) sub("</math>","\\end{align}&...

html - Offset text without moving background -

is possible—without adding wrapper element—to offset position of text in html element without causing background shift? motivation: i have existing html markup (phpbb) , i'm styling links buttons visibly pushed down when :active (mouse button down). have half of working via background change, want offset text down , right 1 pixel. existing html markup (cannot changed): <a href="…"><span></span>hello world</a> fiddle showing effect , existing css (which can changed): http://jsfiddle.net/szxpz/1/ edit : can text move right text-indent:1px; margin-right:-1px , still leaves need move text down well. you should able achieve increasing padding-top , decreasing height 1.

contour - Image segmentation in presence of noisy background -

Image
attached image in bright white contour near green 1 contour of interest. green 1 approximate automatic initialization. gradient non existent in region near automatically initialized contour. hence, active contours , other gradient based methods fail without moving bit. along normal of initialized contour, searched maximum intensities (and reasonably close initialized contour). deleted outliers , smoothed detected curve detect smooth curve. there issues this. if can suggest different, if useful. the gradient non existent in region near automatically initialized contour. hence, active contours , other gradient based methods fail without moving bit. use gradient vector flow * external force function on active contours. uses diffusion process extend influence of high-gradient pixels. right parameters, work on shown initial curve. *if link ever dies, search snakes, shapes, , gradient vector flow chenyang xu , jerry l. prince.

Google Calendar API event insert always return 404 "not found" error -

i tried calendar insert example here : https://developers.google.com/google-apps/calendar/v3/reference/events/insert#examples no matter property use, 404 "not found" error. can shed light on this? many thanks!!! post https://www.googleapis.com/calendar/v3/calendars/test/events?sendnotifications=false&fields=start&key={your_api_key} content-type: application/json authorization: bearer ya29.ahes6zqat3-tj_bviway9xi3gdspubbctektidnzktxuwpi x-javascript-user-agent: google apis explorer { "end": { "date": "2012-07-11" }, "start": { "date": "2012-07-09" } } response: 404 not found { "error": { "errors": [ { "domain": "global", "reason": "notfound", "message": "not found" } ], "code": 404, "message": "not found" } } i believe it's telling ca...

c# - Show a link to all files in a folder with Razor code -

i want show link files in folder. how do in asp.net razor code in webmatrix. can show entries in database @foreach (var row in db.query(selectquerystring)) but i'm not sure how pulling files folder. directory.getfiles give list of files in given directory. note: beware of security issues exposing , accessing files in asp.net environment.

c - What is a clean way to modify arguments inside a function in java? -

i interested in doing c code in java: // sets n's ith bit right, starts 0 void setbit(int* n, int i){ *n = *n | (1 << i); } however, looks java can't pass addresses, clean approaches? i thought of 2 approaches, wondering if there better ways it? approach 1: using array // sets n[0]'s ith bit right, starts 0 public void setbit(int[] n, int i){ n[0] = n[0] | (1 << i); } approach 2: using class private class data{ int value; } // sets d.value's ith bit right, starts 0 public void setbit(data d, int i){ d.value = d.value | (1 << i); } nope, no better way it... unless you'd traditional java way, is d = setbit(d, i); public int setbit(int d, int i) { return d | (1 << i); } this in java "modifying arguments function" inherently unclean. clean way find alternative modifying arguments. (sometimes it'll inevitable, in case workarounds way go. said, if want write method modify(mydata)...

function - Actionscript 3 - Setting multiples of a number equal to a number -

Image
i writing program in actionscript 3 involves slider displays weeks , months on course of year slide right in format of "month 2 week 3" or "month 8 week 2". did months this: function monthhandler(){ var a:number = ((math.ceil(aslider.value/4))+1); monthlabel.text = "month" + string(a); } however same slider (aslider) i'd display weeks, 4, each month. know need set number threshold; values 1-4 display weeks: 1-4, values 5-8 have display weeks 1-4. i know using crapton of if() loops relatively new programming , assuming there more efficient way of doing this, , not know it. looked around web checking multiples of numbers, , setting number thresholds, nothing seems suited problem. the current code weeks is: function weekhandler(){ var b:number = ((math.ceil(aslider.value/12))+1); weeklabel.text = "week:" + string(b); } all display 1-4 slide slider across quarters of thing. said, know doesn't work don't know fix it. ...

forms - What's the name of those input boxes which allow multiple autocompleted inputs which then become "buttons" in the textbox when selected? -

Image
a perfect example of im asking is, when asking question in so, @ "tags" input box. can type "php" , select multitude of "php" tags, when select it, "php" becomes button "x". im curious technical term type of input can if jquery, extjs or various libraries im using have this.

Android login form using Post -

i trying create post request following api: consumer.api.mobdev.machies.com in order this, have written following code: httppost httppost = new httppost("http://consumer.api.mobdev.machies.com/v3/logins"); try { // add user name , password edittext uname = (edittext)findviewbyid(r.id.username); string username = uname.gettext().tostring(); edittext pword = (edittext)findviewbyid(r.id.password); string password = pword.gettext().tostring(); list<namevaluepair> namevaluepairs = new arraylist<namevaluepair>(3); namevaluepairs.add(new basicnamevaluepair("grant_type","password")); namevaluepairs.add(new basicnamevaluepair("username", username)); namevaluepairs.add(new basicnamevaluepair("password", password)); httppost.setheader("host","http://consumer.api.mobdev.machies.com"); httppost.setheader("content-type...

eclipse - -Duser.language=zh doesn't work in ecilpse JUNO -

i use ubuntu 12.04 64 bits locale en_us.utf-8 (i muse use english locale). default key binding content assist in ecilpse ctrl+spacebar. want change alt+/ because ctrl+spacebar used activate chinese input method. in previous eclipse version, add "-duser.language=zh" in bottom of eclipse.ini, , ecilpse change content assist key shortcuts alt+/. however, in latest eclipse (4.2 juno), takes no effects. any idea? thanks. instead of using -duser.language=zh in eclipse.ini, before --launcher argument add following options: -nl zh_cn

verification - Test suite for automatic bug finding -

for many kinds of hard computational problems e.g. propositional satisfiability, theorem proving, traveling salesman etc., there exists extensive test suite can used evaluating performance of program attempts solve problem. does such thing exist automatic bug finding, i.e. collection of programs or code fragments containing known bugs of kind automatically detected? assume e.g. coverity must have such thing internal use, google search doesn't seem show publicly available. i don't think such suite exists. glaring question "standard" suite is, language written in? for c, can @ safecode 's test suite, here . safecode meant detect these bugs @ runtime, "perfect" static analysis tool should able detect them statically. a more comprehensive, , more importantly, static analysis tool, frama-c . see paper entitled " test-driving static analysis tools in search of c code vulnerabilities ". paper describes need test suite ask for. links...

documentation generation - Sphinx: List of supported languages for highlighting? -

i'm using sphinx code documentation , use several languages within code, setup highlighting of code. sphinx briefly mentions few of languages supports ( on page ), , mentions uses pygments lexical analysis , highlighting. sifting through documentation both sphinx , pygments yielded me no clue on how highlight objective-c code. pygments mention list of languages supports, here , doesn't tell me exact syntax must use within sphinx (.rst files) tell code block highlight specific language. example, highlight c++ code simple use before code block: .. highlight:: c++ however after trying these cannot seem highlight objective-c code: .. highlight:: objective-c .. highlight:: objective-c .. highlight:: obj-c .. highlight:: obj-c can supply me list of languages (as refer them within documentation)? as far can tell, list in file pygments/lexers/_mapping.py , in (autogenerated) dictionary lexers . in copy, see line 'objectiveclexer': ('pygments.lexers...

In Eclipse, is there a generic Provider for all kinds of content? -

in eclipse, enumerate content every registered provider. there such interface? at least in installation not search files @ all. instead same old "ctrl-3" quick access allows access ui elements typing name. try "pack" see listing package explorer , similar things. for locating files should use ctrl-r (open resource) instead or use normal file search.

Django - Anonymous user group -

i need allow administrators manage permissions models on site. groups, users, , permissions doing great job of right now. however, need allow administrators manage permissions of non-authenticated users - anonymous users. docs anonymous user's group empty, how can allow administration of permissions? it strange add permissions anonymous users. docs say: django's permission framework not have place store permissions anonymous users. however, has foundation allows custom authentication backends specify authorization anonymous users. useful authors of re-usable apps, can delegate questions of authorization auth backend, rather needing settings, example, control anonymous access. so can set permissions anon yuser, custom auth backend. better use declarative permission check, using decorators on views needed permissions, like: @permission_required('somemodel.can_add') def add_model(request): or leave unrestricted everyone(incl. anonymou...

Cost functional calculation for global optimization in CUDA -

i trying optimize function (say find minimum) n parameters ( xn ). xi 's bound range (for example -200 200 ) , if parameter leaves range, function goes infinity fast. however, n can large (from 20 60-70 ) , computing it's value takes long time. i don't think details about function of big relevance, here some: consists of weighted sum of 20-30 smaller functions (all different), on part consist of sums of dot products under sign of inverse sinusoidal function ( arcsin , arccos , arctan , etc). arcsin(x1 . x2) + arcsin(x4 . x7) + ... . the function has many local minima in general, approaches such (naive) conjugated gradients or quasi-newton useless. searching entire domain brute force slow. my initial idea use sort of massive parallelization in combination genetic algorithm, performs many searches on different spots in domain of function, , @ regular intervals checks whether of searches reached local minima. if yes, compares them , discards results smallest o...

Pipes between Python and C++ don't get closed -

i spawning process in python using subprocess , want read output program using pipes. c++ program not seem close pipe though, when explicitly telling close. #include <cstdlib> #include <ext/stdio_filebuf.h> #include <iostream> int main(int argc, char **argv) { int fd = atoi(argv[1]); __gnu_cxx::stdio_filebuf<char> buffer(fd, std::ios::out); std::ostream stream(&buffer); stream << "hello world" << std::endl; buffer.close(); return 0; } i invoke small program python snippet: import os import subprocess read, write = os.pipe() proc = subprocess.popen(["./dummy", str(write)]) data = os.fdopen(read, "r").read...

Filter strings with jQuery/Javascript -

im trying use $.get load pages without reloading page. <script> $('#top_links a').click(function (e) { e.preventdefault(); var link = $(this).attr('href'); $('#content').empty(); $.get(link, { }, function(data) { $('#content').empty().append(data); } ) }); </script> this works entire requested page getting stuffed #content . instead of detecting ajax request , filtering data on server-side, client-side. there way use javascript filter string divs? content want preserve contained inside of div called #content ( im trying swap current page's #content requested page's #content ). try load method loading of page fragments approach: $("#content").load(link + " #content > *");​​​​​​​​​​​ here can use > * in order include inner html of #content block without surrounding <div id="content"></div> (check more information...

what is the most optimize makefile rules to a create an object needing a lot of intermidate and (mostly) useless files -

i have prerequisites: a, b, , c , want build f (final) i can write make rules ( create , update different each command) f : b c create a1 create a2 a1 create a3 a2 create b1 b create f c update f b1 update f a3 or f : c b1 a3 create f c update f b1 update f a3 b1 : b create b1 b a3 : a2 create a3 a2 a2 : a1 create a2 a1 a1 : create a1 any idea reliable, fast ? more granularity in makefile desirable. if 1 of jobs in pipeline fails, can correct error , pick make died. additionally, rules easier read. the form single rule , many commands faster in execution because fewer timestamps checked , fewer rules need evaluated; however, time difference inconsequential.

vim - Nerdtree - save state of opened directories -

a typical workflow me opening vim (macvim precise), doing: :nerdtree <bookmark> then manually opening various subdirectories want use. it's same set of directories had open when last working on project. i'm aware of o recursive-open command if it's large tree have go , close load of them clear screen up. is there way of saving ones open / general 'state'? unfortunately, there no way in nerdtree - yet. if feel feature deserves attention, however, can add yourself or submit request it on github, , available soon. edit: took liberty of submitting feature request myself; you can track status here .

orchardcms - Orchard custom page renders default widgets? -

still getting know orchard, i've managed create custom default page using module , routing rules. although orchard shows page, renders 3 seem default widgets, headings "first leader aside", "second leader aside", "third leader aside". ok apparantly need overwite default behaviour or that, can't figure out how. so there wrong / missing module, or need provide setting or that? if widget in default layer, appear on every single page in site. see http://docs.orchardproject.net/documentation/managing-widgets you need put these widgets in different layer defined rule fits want.

smarty3 - shorten smarty if statements -

i have smarty if statement follows: <{if $page->geturlname() eq 'big-issues' or $page->geturlname() eq 'polls' or $page->geturlname() eq 'what-we-do' or $action eq 'events' or $action eq 'blogs' or $action eq 'news'}> i have compare same statements several time in template. , tedious ugly repeat statements several times. know can cache statements , reuse many times looking if possible this: <{if $page->geturlname() eq 'big-issues' or 'polls' or 'what-we-do' or 'events' or $action eq 'blogs' or 'news'}> like in php do: $url = array ("big-issues","polls","what-we-do"); $needle = $page->geturlname(); if(in_array($needle, $centered)) { //do } please note dont have access php code template can use smarty. suggestion highly appreciated. cheers. actually solution came with. note: in template have use <{}...

Mysql have suddenly started regularly opening unsuccesful sockets -

i've desperately tried figure out what's happened here, haven't seen particular problem anywhere. i've 'inherited' (as in, not built of myself) management of database server (remote, in data warehouse, accessed ssh) php daemons running on linux server acting data crawlers, inserting , processing information in relatively steady stream mysql. a couple of days ago, server crashed , came on again. logged in restarted mysql server , crawlers, thinking no more of it. day , half later, mysql server stopped working, , couldn't diagnose since couldn't log it, nor did respond "/etc/init.d/mysql stop" or varieties thereof. according log file, kept throwing errors regularly (once every 4 minutes , 16 seconds) , said had many file handlers open. when shut down crawlers, however, log in again, mysql kept throwing errors. checked lsof , showed lot of open sockets "can't identify protocol" error. mysqld 28843 mysql 1990u sock ...

objective c - When are categories bad/dangerous? -

i'm using categories core data. of tutorials i've read , lectures i've listened categories considered "bad" practice. because objective-c dynamic seems okay define methods somewhere else, because public properties of class can used. pitfalls should looking out when using categories? or there reason categories bad practice? reason i'm using them core data don't have rewrite add-on methods every time regenerate subclasses. the "danger" can think of when use them replace methods in original class rather subclassing. when doing lose ability access original implementation, which, since private method overriding, have unforeseen effects. using categories add extra methods object of particular class great, , precisely for. using them core data, doing, fine because allow change model , regenerate "vanilla" object without destroying code. tip of hat @codafi bit of documentation apple: although objective-c language allows...

android - How to get actionbar views objects? -

is there way can actionbar views object references. instance overflow view in order know coordinates on screen. have manage ugly solution is. menu item id overflowview =((viewgroup)parent.findviewbyid(r.id.menu_id).getparent()).getchildat(2); is there way can actionbar views object references. only ones create yourself, via android:actionlayout , kin. for instance overflow view in order know coordinates on screen. your solution unlikely remain stable across android versions. may or may not work on actionbarsherlock. recommend find other solution whatever perceive problem not involve messing around internals of actionbar implementation.