Posts

Showing posts from September, 2010

user controls - WPF UserControl creating multiple layout choices -

Image
i have usercontrol have various properties defined, can customise each copy that's on screen. have path uses lineargradientbrush fill. @ present hard coded xaml. have width , visibility of path control dependency objects , can modify these: <path visibility="{templatebinding pathavisibility}" width="{templatebinding pathalength}"> <lineargradientbrush endpoint="0,0.5" mappingmode="relativetoboundingbox" startpoint="1,0.5"> <gradientstop color="#07ffffff" offset="0.812"/> <gradientstop color="red"/> <gradientstop color="#00000000" offset="0.993"/> <gradientstop color="#ff956666" offset="0.62"/> </lineargradientbrush>... what i'd create few gradients options can select properties in wpf xaml designer. "grada" red, "gradb"

google app engine - java.security.AccessControlException: File accessible thru browser but not within same server -

so not repeat myself much, please refer serve static image along side java google-enpoint api . as can see referenced link, able view image through url. however, when trying read filenames using similar code to public void listfilesforfolder(final file folder) { (final file fileentry : folder.listfiles()) { if (fileentry.isdirectory()) { listfilesforfolder(fileentry); } else { system.out.println(fileentry.getname()); } } } final file folder = new file("/home/you/desktop"); listfilesforfolder(folder); i security exception java.security.accesscontrolexception: access denied ("java.io.filepermission" "/myimages" "read") does know fix? how come call thru browser show image , yet call within server throws exception? find strange. if you've configured file "static" resource, it'll served separate pool of servers optimized serving static content. consequenc

JavaScript function arguments statements -

my problem is: (only example, must not make sense overall): // make function , pass part of statement argument function examplefunction( argument ) { document.getelementbyid('testid')[0].style.argument = '#f00'; } // later onload examplefunction( background ); i found out doesn't work way, can't find out how right. if correct example send me on way happy , thankful. firstly document.getelementbyid returns single element (or null if no element found), not [0] . secondly if want reference property dynamically use [] notation // make function , pass part of statement argument function examplefunction( argument ) { document.getelementbyid('testid').style[argument] = '#f00'; } // later onload examplefunction( 'background' ); http://jsfiddle.net/hm3mu/

pagination - Dynamic perPage Variable in Laravel vis Select -

i'm submitting form index() action of resource controller it' scaling store() method. here's code. http://paste.laravel.com/rru i'm trying dynamically change $perpage variable adjust pagination amount via select box submitted using jquery. ideas. as far know there no resource key available when opening form. index method on resource controller routed get request. because form opening post request default it's posting current uri results in request ending @ store method. if you're trying update pagination why don't send get , use query string (as paginator does).

actionscript 3 - Flash AS3 Drawing a line between two objects with different parents -

so have 2 objects different parents , want draw line between them, how do this? know need use localtoglobal not sure how make work this. need x , y coordinates of both objects relative 1 of them, how x , y coordinates of on object relative when have different parents? thanks. conceptually need (draw dashes, solid line) parent | \ child1--child2 [some code (typed not tested)] var start:point = parent.globaltolocal(child1.localtoglobal(new point())); var end:point = parent.globaltolocal(child2.localtoglobal(new point())); parent.graphics.linestyle(1); parent.graphics.moveto(child1.x,child1.y); parent.graphics.lineto(child2.x,child2.y); [another option] var start:point = child1.getrect(parent).topleft; var end:point = child2.getrect(parent).topleft; parent.graphics.linestyle(1); parent.graphics.moveto(child1.x,child1.y); parent.graphics.lineto(child2.x,child2.y); http://help.adobe.com/en_us/as2lcr/flash_10.0/help.html?content=00001308.html http://help.adobe.

objective c - Visual QuartzCore iOS -

Image
just simple question. there simple visual tool generate source code ios/quartzcore? for example, make cakeyframeanimation path , (ex. cgpathmovetopoint , cgpathaddcurvetopoint), there visual tool export source code? i didn't find , have written this: and exports source code this: cgpoint startcontrollerpoint = {219.5, 162.5}; cgpoint endcontrollerpoint = {118, 382}; cgpoint startposition = {55, 161.5}; cgpoint endposition = {273.5, 383.5}; cgmutablepathref path = cgpathcreatemutable(); cgpathmovetopoint(path, null, startposition.x, startposition.y); cgpathaddcurvetopoint(path, null, startposition.x + (164), startposition.y + (1), endposition.x + (-156), endposition.y + (-2), endposition.x, endposition.y); cgpathrelease(path); but isn't complete. i wouldn't reinvent wheel. thanks, sorry english. there isn't tool draw , animate ios. paintcode , opacity lets draw , export code, not animate. quartz composer creates complex compositions it&

c++ - Compiler error: std::basic_ios<_Elem, _Traits>::basic_ios(const std::basic_ios<_Elem, _Traits>::_Myt &) -

anyone come across error before? i'm @ loss precisely causing this: 1>...include\sstream(640): error : "std::basic_ios<_elem, _traits>::basic_ios(const std::basic_ios<_elem, _traits>::_myt &) [with _elem=char, _traits=std::char_traits<char>]" 1>...include\istream(922): error : "std::basic_ios<_elem, _traits>::basic_ios(const std::basic_ios<_elem, _traits>::_myt &) [with _elem=char, _traits=std::char_traits<char>]" 1>...include\istream(18): error : "std::basic_ios<_elem, _traits>::basic_ios(const std::basic_ios<_elem, _traits>::_myt &) [with _elem=char, _traits=std::char_traits<char>]" 1>...include\ostream(37): error : "std::basic_ios<_elem, _traits>::basic_ios(const std::basic_ios<_elem, _traits>::_myt &) [with _elem=char, _traits=std::char_traits<char>]" it doesn't give indication of in source code have caused this, , have no idea

class - How to use winform listbox to list declared objects in C#? -

i trying make listbox in winform use list of declared objects content source. choosing object should list properties in nearby text box reads properties of object. object list looks this: public form1() { element gold = new element(); gold.property = "soft"; gold.metal = true; gold.name = "gold"; initializecomponent(); } i told putting in main form way go this. have attempted far giving name string listbox use name object user select, , other 2 properties (gold.property = "soft"; , gold.metal = true; meant go in nearby textbox when item selected in listbox). don't know how this, sort of appreciated. @ base, knowing how listbox find object made , list it, great. also, yes, assignment. things have outlined need done in way...there more assignment itself, stuck here. use list<element> elements store element, loop on each element , add name listbox. add event handler listbox selected index changed, code shou

python - Pyserial string to byte encoding to write to microcontroller -

i'm trying communicate between pc , microcontroller (mc). microcontroller read using getchar() until 4 characters have been read or bumps characters '\0' , '\' , or '\r' . the communication works fine hyper-terminal. however, python script doesn't seem sending '\0' , '\' , or '\r' when encoding input string , concatenating 1 special characters it. command = input("enter command: ") port.write(bytes(command + '\n', 'utf-8')) so if entered command x should send 'x' and '\n' , mc should stop waiting more characters read because of new line. however, if enter x , mc wait 4 more characters read. how convert string special characters bytes? thanks. the mc code is: buffer[ii] = getchar(); while(buffer[ii] != '\0' && buffer[ii] != '\n' && buffer[ii] != '\r' && ii < 4 - 1) { buffer[++ii] = getchar(); } you can conv

sql - How to make child as parent in xml tree -

i working on message broker. query doing simple , can answered db guy . here query code read xml , getting xml output set outputroot.xmlnsc.root.row[rowcnt].product_info = (select the(select c.*:codes.*:code tyrepatterncd t.*:classification[] c c.(xmlnsc.attribute)type = 'brand') product itemmaster.*:itemmasterheader[] t ); this gives xml output <root name="product"> <row> <product_info> <product> <tyrepatterncd>002</tyrepatterncd> </product> </row> </root> how can make <root name="product"> <row> <product_info> <tyrepatterncd>002</tyrepatterncd> </row> </root> if remove as product in query makes column tag in tree. how can make child parent? use select item omit 'product' element, , directly assign result. set outputroot.xmlnsc.root.row[

metaclass - How to get attributes in the order they are declared in a Python class? -

as described in pep435 , enum can defined way: class color(enum): red = 1 green = 2 blue = 3 and resulting enum members of color can iterated in definition order: color.red, color.green, color.blue . this reminds me of form in django , in fields can rendered in order declared in form subclass. implemented maintaining field counter, every time new field instantiated counter value incremented. but in definition of color , don't have formfield , how can implement this? in python 3, can customize namespace class declared in metaclass. example, can use ordereddict : from collections import ordereddict class enummeta(type): def __new__(mcls, cls, bases, d): print(d) return type.__new__(mcls, cls, bases, d) @classmethod def __prepare__(mcls, cls, bases): return ordereddict() class color(metaclass=enummeta): red = 1 green = 2 blue = 3 this prints ordereddict([('__module__', '__main_

php - Page is not loading after some multiple loops -

i working on flight portal. lets assume there 2 pages (search.php, result.php). in search page select source,destination,date of journey..etc.(now click on search button) after clicking on search button page redirect result.php , there display results. here before displaying results on page trying insert result in database below. $q=0; foreach($array_data['availresponse']['origindestinationoptions']['origindestinationoption'] $main) { $f1=$basefare[$q]=$array_data['availresponse']['origindestinationoptions']['origindestinationoption'][$q]['faredetails']['actualbasefare']; $f10=$octax[$q]=$array_data['availresponse']['origindestinationoptions']['origindestinationoption'][$q]['faredetails']['octax']; $f11=$pcom[$q]=$array_data['availresponse']['origindestinationoptions']['origindestinationoption'][$q]['faredet

startup - Add GUI control to splash screen of linux -

i want add button, textbox,... splash screen when starting linux , handle signal of these controls. how can do? please give me keywords solution. configure or enhance display manager lightdm (or perhaps window manager ) maybe want enhance grub boot loader.

Replacing "." with "%2E" in Rails route -

i have rails controller action functions shown: def rand if !params.has_key?(:name) rand_mymodel = mymodel.offset(rand(mymodel.count)).first redirect_to "/crawl/" + rand_mymodel.name end @model = mymodel.where("name = ?", params[:name])[0] end with route: get "crawl/:name" => "mymodel#rand" "crawl/" => "mymodel#rand" how can allow . appear in :name attribute replace %2e in route/url (similar how space replaced %20 ) i want allow . appear in :name did check respective guide ? by default :id parameter doesn’t accept dots – because dot used separator formatted routes. if need use dot within :id add constraint overrides – example :id => /[^/]+/ allows except slash. the same true name : get "crawl/:name" => "mymodel#rand", name: /[^\/]+/

vb.net - Generate "aa", "Aa", "aA", "AA", etc In order -

how generate combinations of 2 lowercase/upercase letters/numbers in order? sub main() dim looper boolean = true while looper = true 'string = "aa", "aa", "aa", "aa" 'webclient.downloadstring("link.com/" & string") end while end sub like this, generate combination string you loop on string , manipulate upper , lower case required: sub main() dim results list(of string) = new list(of string)() each c char in "abcdefghijklmnopqrstuvwxyz".tochararray() results.add(c.tostring().tolower() & c.tostring().tolower()) results.add(c.tostring() & c.tostring().tolower()) results.add(c.tostring().tolower() & c.tostring()) results.add(c.tostring() & c.tostring()) next end sub

Scripting.Dictionary keys to Listbox VBA Excel -

i have been working vba in excel , began working scripting.dictionary object. hadn't run across major problems until today. basically trying populate listbox key values of dictionary, add 1 more value listbox. results in value not being added listbox, dictionary key. have attempted copy values dict.keys() array separate array, still have same issue. assume byref problem have yet figure out solution. if has ideas awesome. private sub setup_settinglst() 'set settings listbox items 'on error goto errorexit dim list_ary() variant dim tmp variant dim integer settinglst.clear settinglst.value = "-select setting-" = 0 tmp = tmp_dict.keys() if tmp_dict.count > 1 redim list_ary(0 tmp_dict.count) = 0 ubound(tmp) list_ary(i) = tmp(i) next list_ary(tmp_dict.count) = "back" else redim list_ary(0 tmp_dict.count - 1) = 0 ubound(tmp) list_ary(i) =

html - Form submission without parameter name -

<form action="/foo"> <input type="text" name="q"> <input type="submit" > </form> in previous html, if user types in 'bar' , clicks button submit example.com/foo?q=bar . how can make go example.com/foo/bar ? can js i'm trying stick html. there no way in html, need programming language. have on server process form issue http 301 response location header. you enhance use form's submit event prevent default action , set location in js.

java - Correct way of thinking about primitive assignment -

in example, int x = 5; int y = x; x = 4; y remain 5 because x being reassigned , not manipulating object used refer in anyway. question is, said correct way of thinking it? or there duplication of memory stored in 'x' , duplication put in 'y'. primitives, unlike objects, stored directly inside variable. is, variable of primitive type not storing reference primitive, stores primitive's value directly. when 1 primitive variable assigned primitive variable, copies value. when do int x = 5; int y = x; x = 4; x sets value inside of 4, , y still has value 5 because value separate. the way 1 variable changed change variable, if both variables references 'mutable' object, , object mutated - since both looking @ same object, rather own copies, both observe same change. (note example strings, being immutable, never 'suddenly change', arrays , collections can)

sharepoint - Call Javascript method from code behind c# -

please me solve challenge:( have below code: label lblvideoassessment = new label(); lblvideoassessment.text = "<a href='../sitepages/assessment.aspx?cat=" + cat + "' height='300px' width='300px' target='_blank' cssclass='icondisplaycss'><img src='~/_layouts/images/assessment.png' border='none'/></a><br/>" + cat; i want replace above code dialogue box instead of opening new page "Ässessment.aspx". have tried this: lblvideoassessment.text = "<a cssclass='icondisplaycss' width='300px' height='300px' onclick='javascript:opendialog('../sitepages/assessment.aspx?cat='+cat+);return false;'><img border='none' src='~/_layouts/images/assessment.png'></a>"; however doesnot work. think issue '' (quotation have placed ) or need use page.clientscript.registerstartu

CSS3: reverse animation on mouse out after hover -

so, possible have reverse animation on mouse out such as: .class{ transform: rotate(0deg); } .class:hover{ transform: rotate(360deg); } but, when using @keyframes animation, couldn't work, e.g: .class{ animation-name: out; animation-duration:2s; } .class:hover{ animation-name: in; animation-duration:5s; animation-iteration-count:infinite; } @keyframe in{ {transform: rotate(360deg);} } @keyframe out{ {transform: rotate(0deg);} } so optimal solution, knowing i'd need iterations , animation itself... thanks http://jsfiddle.net/khalednabil/ewzbm/ i think if have to , must use from . think of : @keyframe in { from: transform: rotate(0deg); to: transform: rotate(360deg); } @keyframe out { from: transform: rotate(360deg); to: transform: rotate(0deg); } of course must have checked already, found strange use transform property since css3 not implemented everywhere. maybe work better following considerations

javascript - Does Angular $location service support multiple parameters? -

using angular's $location.search() method, possible create url parameter, this: http://mysite.com/page?param=myparam is possible create multiple url parameters, this? http://mysite.com/page?param=myparam&param2=myparam2&... i've tried adding multiple object parameters function call (ex. $location.search({ key1: value, key2: value }) ), i'm receiving 1 key/value in url. thanks! it work in fiddle: http://jsfiddle.net/phnlb/42/ $scope.changetarget = function(name) { $location.search({target : 'hi', new : 'else'}); } (angular 1.1.4, html5 mode = true) which version of angular using?

php - Multidimensional array, how do I solve this? -

i've been trying solve this, keep getting "gained" output instead of user. array(2) { ["skill"]=> array(2) { [0]=> array(2) { ["user"]=> string(7) "username" ["gained"]=> int(15) } [1]=> array(2) { ["user"]=> string(6) "username" ["gained"]=> int(8) } [2]=> array(2) { ["user"]=> string(6) "username" ["gained"]=> int(3) } ["skill2"]=> array(2) { [0]=> array(2) { ["user"]=> string(7) "username" ["gained"]=> int(10) } [1]=> array(2) { ["user"]=> string(6) "username" ["gained"]=> int(7) } [2]=> array(2) {

javascript - OnUnload Alert Error "NS_ERROR_NOT_AVAILABLE" -

<html> <body> <button type="button" onclick="clickme()">click me</button> <script> var test = 0; function clickme() { test = 1; console.log(test); } window.onunload = function() { alert("test"); } </script> </body> </html> i'm using simple code test things onunload , onbeforeunload. reason whenever refresh/leave page , cause onunload event no alert , error in firebug console. if use onbeforeunload works , no error, hear onbeforeunload isn't cross-browser. ns_error_not_available: component returned failure code: 0x80040111 (ns_error_not_available) [nsidomwindow.alert] alert("test"); i not trying alert test variable, text "test" before tries point out. if want work, have in onbeforeunload event, instead of creating alert/confirm pop-up, onbeforeunload event has built in pop-up. have return string , pop-up appear when user tries navigate away page.

iphone - Compress Large UIImage -

so im doing compressing image repeatedly until fits within size frame. it takes many attempts, give , later tell user image large. my issue after image size has been reduced, size goes way again when changed uiimage. here code reducing image size: double compressionratio = 1; int resizeattempts = 5; nsdata * imgdata = uiimagejpegrepresentation([info objectforkey:@"uiimagepickercontrolleroriginalimage"],compressionratio); nslog(@"starting size: %i", [imgdata length]); //trying push below around 0.4 meg while ([imgdata length] > 400000 && resizeattempts > 0) { resizeattempts -= 1; nslog(@"image bigger 400000 bytes. resizing."); nslog(@"%i attempts remaining",resizeattempts); //increase compression amount compressionratio = compressionratio*0.5; //test size before compression nslog(@"current size: %i",[imgdata length]); img

ruby on rails - 406 when uploading image from RestKit to RoR backend -

i'm having serious problem , searched many hours without finding solution. i have backend server using ruby of rails , paperclip image saving. the image upload works fine browser, posting /pictures but when try upload /pictures.json using multipart request restkit (ios), 406. when image (picture object) created server-side, reward (reward object) associated it. reward object i'm expecting json response. here objective-c code: nsmutableurlrequest* uploadrequest = [self.objectmanager multipartformrequestwithobject:nil method:rkrequestmethodpost path:@"/pictures.json" parameters:nil constructingbodywithblock:^(id<afmultipartformdata> formdata) { [formdata appendpartwithfiledata:uiimagepngrepresentation(socialreward.image) name:@"picture[pict]" filename:imagename mimetype:@"image/png"]; }]; here controller: @picture = picture.create( params[:picture] ) respond_to |format|

excel - Type Mismatch, yet functional code -

this macro designed identify string "%" in cell and, if present, identify colouring yellow. interestingly work, keep getting type mismatch error afterword on line: if instr(rngcell.value, "%") > 0 this full code below: public sub markerrorvalues() dim iwarncolor integer dim rng range dim rngcell variant dim lr long dim vval dim trow lr = cells(rows.count, "b").end(xlup).row set rng = range("c1:c" & lr) iwarncolor = xlthemecoloraccent2 each rngcell in rng.cells trow = rngcell.row if instr(rngcell.value, "%") > 0 rngcell.interior.colorindex = iwarncolor else rngcell.interior.pattern = xlnone end if next end sub any appreciated! probably have cells error values (eg #ref! , #div/0! etc) to filter these out, wrap troublesome code inside not iserror conditional: if not iserror(rngcell.value) if instr(rngcell.value, "%") > 0 rngcell.interior.

Gridview onScroll method gets called always, without user scroll -

i have customized gridview i'm checking onscroll method find end of list. if scroll reaches end of list, again add few elements in list. gridview.setonscrolllistener(new onscrolllistener() { @override public void onscrollstatechanged(abslistview arg0, int arg1) { } @override public void onscroll(abslistview arg0, int firstvisibleitem, int visibleitemcount, int totalitemcount) { // todo auto-generated method stub int lastinscreen = firstvisibleitem + visibleitemcount; //is bottom item visible & not loading more ? load more ! if((lastinscreen == totalitemcount) && (!loadingmore)) { new loaddatatask().execute(); } } }); and asynchronous task class.. private class loaddatatask extends asynctask<void, void, void> { @override protected void doinbackground(void... params) { if (iscancel

postgresql - Indexing column for full text search -

i have column col data type character varying i need index column gin index. if trying directly set gin index column, returned error: data type character varying has no default operator class access method "gin" hint: must specify operator class index or define default operator class data type if trying: create index col_vector on mytable using gin (to_tsvector(col)) i got error: functions in index expression must marked immutable how create gin index character varying column ? p.s. need full text search try code: create index "name " on "tablename" using gin(to_tsvector('english', "columnname"));

php - Symfony2 - Security authentication -

- { path: ^/event, roles: is_authenticated_anonymously } - { path: ^/, roles: is_authenticated_anonymously } - { path: ^/, roles: role_member } in security.yml , authenticate /xxx except / , /event , there way so? did above not work. way work add individual pages everytime create one. - { path: ^/event, roles: is_authenticated_anonymously } - { path: ^/, roles: role_member } i cannot add is_authenticated_anonymously on root in 3rd line because wrong. you have in access_control: - { path: ^/event, roles: is_authenticated_anonymously } - { path: ^/$, roles: is_authenticated_anonymously } - { path: ^/, roles: role_member }

substring javascript and html -

<script> function myfunction(){ //example passed in 31-02-2013 //var timedate = document.getelementbyid('date').text; <--this wont work! //this basic example only. badly formatted user entry cause //sorts of problems. var timedate = document.getelementbyid('date').value; //get first 2 characters var first2 = timedate.substring(0,2); console.log(first2); var datearray = timedate.split("-"); console.log(datearray[0]); var date = parseint(datearray[0], 10) ;//make sure use radix otherwise leading 0 hurt console.log(date); if( date < 1 || date > 30 ) alert( "invalid date" ); var month2 = timedate.substring(3,5); console.log( month2 ); var montharray = timedate.split( "-" ); console.log( montharray[1] ); var month = parseint( montharray[1],10 ); console.log( month ); if( month < 1 || month > 12 ) alert( "invalid month" ); } </script> my function working, want correction if user input -2

java - Setup web dav with tomcat -

i m looking setup webdav tomcat. m new concept. want war file downloaded. how set wabdav in tomcat. program java thanks in advance tomcat comes servlet enables webdav. add following code web.xml: <servlet> <servlet-name>webdav</servlet-name> <servlet-class>org.apache.catalina.servlets.webdavservlet</servlet-class> <init-param> <param-name>debug</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>listings</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>readonly</param-name> <param-value>false</param-value> </init-param> <init-param> <param-name>allowspecialpaths</param-name> <param-value>true</param-value> </init-param> </servlet&

Why does my php form keep yielding empty rows in mysql? -

so trying create form puts data in table, , got work, when goes table, creates empty rows. here code, please me out. form.php <form action="tableinsert.php" method="post"> first name:<input type="text" name="fname"> <br/> last name:<input type="text" name="lname"><br/> username:<input type="text" name="uname"><br/> password:<input type="text" name="password"><br/> email:<input type="text" name="email"><br/> </form> tableinsert.php <?php $sc = mysqli_connect ("localhost" , "dbname" , "password"); if (mysqli_errno($sc)) { echo "sorry, couldn't connect database. if keep getting error, please email webmaster @ natashaharrell@hotmail.com " . mysql_error; } $si = "insert sdb_users (fname, lname, uname, password, em

iphone - How to use the Facebook SLComposeViewController in a UIView instead of a UIViewController -

i'm having problem using facebook slcomposeviewcontroller in uiview. problem i'm having because have uiview , not uiviewcontroller i'm inheriting from. i've imported: #import <social/social.h> #import <accounts/accounts.h> and trying present facebook sharing using: slcomposeviewcontroller *controllerslc = [slcomposeviewcontroller composeviewcontrollerforservicetype:slservicetypefacebook]; [controllerslc setinitialtext:@"first post iphone app"]; [controllerslc addurl:[nsurl urlwithstring:@"http://www.test.com"]]; [controllerslc addimage:[uiimage imagenamed:@"test.jpg"]]; [self presentviewcontroller:controllerslc animated:yes completion:nil]; it's last line won't present view because i'm inheriting uiview , not uiviewcontroller i'm not sure how fix this. want share image. thanks help. uiviews cannot present view controllers. you'll need set way call uiviewcontroller presenting uiview.

asp.net web api - Using a proxy with .NET 4.5 HttpClient -

i'm troubleshooting bug service call through .net's httpclient, trying route request through local proxy (fiddler), proxy settings seem not taking effect. here's how create client: private httpclient createhttpclient(commandcontext ctx, string sid) { var cookies = new cookiecontainer(); var handler = new httpclienthandler { cookiecontainer = cookies, usecookies = true, usedefaultcredentials = false, proxy = new webproxy("http://localhost:8888", false, new string[]{}), useproxy = true, }; // snip out irrelevant setting of authentication cookies var client = new httpclient(handler) { baseaddress = _prefserverbaseurl, }; client.defaultrequestheaders.accept.add( new mediatypewithqualityheadervalue("application/json")); return client; } then send request by: var response = createhttpclient(ctx, sid).postasjsonasync("api/prefs/", smp).result; re

python - How to set a custom attribute to a model which can be used in the template with ModelForm in Django? -

is possible write attributes model field can used later differentiate different fields in template? model.py from django.db import models class person(models.model): first_name = models.charfield("i label", max_length=30) last_name = models.charfield("i other label", max_length=30, customattr="custom") forms.py class personform(modelform): class meta: person template.html <form action="" method="post">{% csrf_token %} {% field in form %} {% ifequal field.customattr 'custom' %} # how work? <p>hello world.</p> {{ field }} {% else %} <p>this not custom</p> {{ field }} {% endifequal %} {% endfor %} <input type="submit" value="submit" /> </form> any hints? not possible; field in template code form field, not model field. shift presentation

visual c++ - Porting C++ w/ MFC to a Touch Screen -

looking gui framework use c++ "modernize" existing interface touchscreen. i'm novice programmer background in c++/java assigned project involves taking existing c++ program using mfc (3 data views, multiple text/radio controlled dialog boxes, etc.) , redesigning interface "touch-screen friendly" such larger button controls, sliders , whatnot. i've been given pretty free-reign instructions make "more modern looking interface" opposed typical bare-bones mfc i've been given. know have quite bit learn either way, suggestions helpful. so far options i've come are: mfc tweak existing controls accommodate touch input, keep crappy looking interface. managed c++ or c++/cli figure out how keep underlying c++ structure while being able design new interface wpf or windows forms. qt new me, seems promising alternative. really need find way make program wasn't written on 10 years ago, , far in teaching myself mfc, doesn't s

php - Create SQL query with more than one where clause -

i'm trying query 2 where clauses like: select * table1 `name` = 'paul' , `id` = 1 in laravel eloquent, don't know correct syntax. simple, use where model::where('name', '=', 'paul')->where('id', '=', 1); then may use get() or first() fetch row(s). if want use query builder(fluent) replace model:: db::table('table1')-> . note = optional here. here can use other operators. update from laravel 4.2 can use array: model::where([ 'name' => 'paul', 'id' => 1 ]);

Count NULL Values from multiple columns with SQL -

i have 3 columns let a, b, , c. need count null values in each column. for example: | b | c ------------- 1 |null| 1 1 | 1 | null null| 1 | 1 null|null| 1 should output: | b | c --------------- 2 | 2 | 1 i've tried count, sum, sub-queries nothing has worked me yet. input appreciated! select count(*)-count(a) a, count(*)-count(b) b, count(*)-count(c) c yourtable;

ssh - Python Fabric and password prompts -

i see there few questions regarding fabric , passwords. know if pass -i fabric password enter passed environmental variable "password." problem i'm prompted password when running ssh command on remote server remote server. but , don't want prompted password entry. prompted no matter try do. here's little snippet of code: elif "test" in run('hostname -d'): print(blue("gathering knife info")) run("ssh mychefserver knife node show `hostname`.test.dmz") it works fine when enter password. thing is, don't want have enter password. maybe because ssh connection initiated on remote host , fabric can't that. i have script disconnect remote host, run ssh command locally, reconnect remote host finish script... seems silly. suggestions? getpass info: python 2.6.6 (r266:84292, sep 11 2012, 08:34:23) [gcc 4.4.6 20120305 (red hat 4.4.6-4)] on linux2 type "help", "copyrigh

oop - In C++, should iterable types be non-polymorphic? -

a bit of background: i working on assignment oop course consists in designing , implementing phone book manager around various design patterns. in project there 3 classes around action happens: phonebook ; contact (the types stored in phone book); contactfield (fields stored in contact ). contactmanager must provide way iterate on contacts in 2 modes: unfiltered , filtered based on predicate; contact must provide way iterate on fields. how decided implement: all design patterns books came across recommend coding interface first thought extract interface each of above classes , make them implement it. now have create kind of polymorphic iterator things smooth adapted java iterator interface write forward iterators. the problems: the major setback design lose interoperability stl <algorithm> , syntactic sugar offered range based loops. another issue came across iterator<t>::remove() function. if want iterator can alter sequence iter

c# - .Net Regex performance issues -

Image
i have output richtextbox (could lot or litte, search results) , apply custom color coding. decided regex , while works, seems pretty slow (~20 seconds) 300 results. the output in same format: attribute1=value1 attribute2=(value2) attribute3="string value 3" attribute4= and on. so, have 4 cases: stuff=stuff, stuff=(stuff) stuff="string of stuff" , stuff= the following regex works fine (matches should), slow: (\s+)=("(?:[^"]|(?<open>")|(?<-open>"))+(?(open)(?!))")|(\s+)=(\((?:[^()]|(?<open>\()|(?<-open>\)))+(?(open)(?!))\))|(\s+)=(\s+)|(\s+)=\s do guys see in particular that's slowing down? i'm sure can tell, first section matches quotes, second section matches parentheses, ect ect. update kidding, doesn't return want... this: attribute1=value1 attribute2=(value2) attribute3="string value 3" attribute4= attribute5="another string" returns this: 5: attribute1 6:

python - Strange character in file breaks for loop silently -

i'm parsing file python , loop breaks on character in notepad++ looks this ©sub0 my loop simple for line in open('myfile.dat').readlines(): print line print x x+=1 there no error, py file quits. what should make skip character? is file binary file? if so, try doing open('myfile.dat', 'rb') open binary. if open text, end-of-file character can cause stop reading prematurely.

Node.js and MySQL "Too many connections" error -

i'm using node.js run web-server web application. i'm using node-mysql module interface mysql server persistent database needs. whenever there critical error within node.js application crashes app's process email sent me. so, keep getting email error saying "too many connections". here's example of error: error: many connections @ function.client._packettouserobject (/apps/x/node_modules/mysql/lib/client.js:394:11) @ client._handlepacket (/apps/x/node_modules/mysql/lib/client.js:307:43) @ parser.eventemitter.emit (events.js:96:17) @ parser.write.emitpacket (/apps/x/node_modules/mysql/lib/parser.js:71:14) @ parser.write (/apps/x/node_modules/mysql/lib/parser.js:576:7) @ socket.eventemitter.emit (events.js:96:17) @ tcp.onread (net.js:396:14) as can see tells me error coming mysql module, doesn't tell me in application code issue occurring. my application opens db connection anytime need run 1 or more queries. close con

Is there a way to call Silverlight method from Asp.net MVC4 controllder? -

i need call silverlight method mvc4 application controller. i load silverlight using object tag, <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="50%" height="100%" style="border:1px solid #cdcdcd"> <param name="source" value="clientbin/helloworld.xap"/> <param name="onerror" value="onsilverlighterror" /> <param name="background" value="white" /> <param name="minruntimeversion" value="5.0.61118.0" /> <param name="autoupgrade" value="true" /> <param name="onload" value="pluginloaded" /> <a href="http://go.microsoft.com/fwlink/?linkid=149156&v=5.0.61118.0" style="text-decoration:none"> <img src="http://go.micro

sql server - TSQL - UNPIVOT from Excel imported data -

i have excel spreadsheet imports table so: +-------------------------------------------------------------------------+ | col1 col2 col3 col4 col5 | +-------------------------------------------------------------------------+ | ref name 01-01-2013 02-01-2013 03-01-2013 | | 1 john 500 550 600 | | 2 fred 600 650 400 | | 3 paul 700 750 550 | | 4 steve 800 850 700 | +-------------------------------------------------------------------------+ my goal change this: +-------------------------------------------------------------------------+ | ref name date sales | +-------------------------------------------------------------------------+ | 1 joh

java - Unable to run Blackberry app in device 907 invalid cod file -

i develop blackberry application , want run in device. have been set code signing key.and install not able run on device,when run .jad file says invalid cod file. can now. using blackberry_java_plug-in_for_eclipse develop. in advanced.

ios - Tools for detecting where UDID is used -

this question has answer here: how detect 3rd sdk use udid? 4 answers i submitted update app itunesconnect discover 1 of third party libraries using udid. not picked when first submitted app , have made no changes third party libraries since then. there tool can use discover 1 using it. have looked manually through them, found nothing... try doing cmd+shift+f on project , search [[uidevice currentdevice] uniqueidentifier]

c# - How to make RedirectToAction with multiple parameters and route as UFL -

i'm having bit of trouble routing in .net. when i'm making redirecttoaction following code: return redirecttoaction("edit", "add", new { id = newid, someval = newsomeval }); and following maproute : context.maproute( "editstuff", "admin/{controller}/{action}/{id}/{someval}", new { controller = "edit", action = "add", id = @"\d+", someval = @"\d+" } ); i redirected url has someval parameter delimited ? instead of / , so: http://localhost:60733/admin/edit/add/43?someval=1 instead of http://localhost:60733/admin/edit/add/43/1 both links work if access them directly. can shine light on issue? many thanks!

php - limit amount of friends to 12 shown in a box? -

i have box displays friends of user, however, shows them , stretched off canvas of app. have them in table in box, there anyway limit amount shown 12 random friends? this code display friends: if ($user) { $user_profile = $facebook->api('/me'); $friends = $facebook->api('/me/friends'); echo '<table>'; foreach ($friends["data"] $value) { echo '<td>'; echo '<div class="pic">'; echo '<img src="https://graph.facebook.com/' . $value["id"] . '/picture"/>'; echo '</div>'; echo '<font color="white">','<div class="picname">'.$value["name"].'</div>','</font>'; echo '</td>'; } echo '</table>'; } ?> you could, instance, use break statement exit loop. use this: if ($user) { $user_profile = $faceboo

gcc - CUDA linking errors with g++ -

i have written makefile compiles multiple files , link them together. output of file: g++ -c -wall -u debug -u file -u highpriority -u onlycuda -u cuda -u thread_num -u size -u inputfilename -d size=32 -d thread_num=4 -d cuda \ ../src/lib/decomp/nt_fft_decomp.cpp -std=c++0x -o nt_fft_decomp.o g++ -c -wall -u debug -u file -u highpriority -u onlycuda -u cuda -u thread_num -u size -u inputfilename -d size=32 -d thread_num=4 -d cuda \ ../src/lib/decomp/t_fft_decomp.cpp -std=c++0x -lpthread -o t_fft_decomp.o g++ -c -wall -u debug -u file -u highpriority -u onlycuda -u cuda -u thread_num -u size -u inputfilename -d size=32 -d thread_num=4 -d cuda \ ../src/lib/comp/snt_fft_comp.cpp -std=c++0x -o snt_fft_comp.o g++ -c -wall -u debug -u file -u highpriority -u onlycuda -u cuda -u thread_num -u size -u inputfilename -d size=32 -d thread_num=4 -d cuda \ ../src/lib/comp/st_fft_comp.cpp -std=c++0x -lpthread -o st_fft_comp.o g++ -c -wall -u debug -u file -u highpriority -u onl

c# - Interpreting MethodBody.ExceptionHandlingClauses collection -

i using reflection analyse method's exception handling blocks [exceptionhandlingclauses] property of [methodbody] class. not figure out msdn documentation how collection behaves , how interpret it. let's want assert that: a method contains 1 try block. that single block contains 1 catch clause. that single block contains finally clause. please try not derive context out of following code complex explain here. illustrative code , may of bad design. consider following heirarchy: // tier 1. base class. namespace productname { // not abstract class. // these tier 1 class methods not have implementations or exception handling blocks. public class template: system.idisposable { public sealed void launch () { this.onlaunch(); } public sealed void simulate () { this.onsimulate(); } public sealed void test () { this.ontest(); } public sealed void submit () { this.onsubmit(); } public sealed void exit () { this.on