Posts

Showing posts from March, 2015

c# - Get assembly reference without reflection or a known type -

in current framework's design, peruse types of specific assemblies , work based on types found. assemblies searches through determined application bootstrapper/initializer. assemblies compiled in, can referenced via: typeof(sometypeintheassembly).assembly . nice because bootstrapper code has strong reference type in assembly , there's no fumbling qualified names inline strings need manually kept up-to-date if assembly qualified name changes. didn't referencing unrelated type in assembly , being dependant on type being there. (what if moves assembly? if deprecate/delete type? change namespace?) in code, looks bit weird too: frameworkassemblyreader.read(typeof(someassemblynamespace.subnamespace.graphingcalculator).assembly); now in bootstrapping code, have direct dependency (although pretty trivial dependency) on graphingcalculator has nothing bootstrapping stage (and graphingcalculator, has nothing obtaining assembly references). avoid this, in each assembly...

JOINS in sql scenario -

i newbie sql joins. have 2 tables version vid, vname, isactive 1 v1 1 2 v2 0 3 v3 1 sub-version svid,vid, vname 1 1 0.1 2 1 0.2 3 2 0.1 in above tables each version has many sub-version's . i need fetch results above tables output should this. vid, vname, isactive, subversionexists(bit) 1 v1 1 1 2 v2 0 1 3 v3 1 0 in above result set column name " subversionexists " represents if version has subversion records in sub-version table. hope explains problem scenario well. thanks in advance. here version without joins, using exists (select ... ) returns boolean value: http://sqlfiddle.com/#!5/712bd/9 select version.vid, version.vname, version.isactive, exists ( select null subversion subversion.vid = version.vid ) subversionexists version; or, if sql engine doesn't convert booleans 0/1, can use case : select version.vid, versio...

collectd - RRDtool force the step parameter when xporting data -

i'm using javascript library visualize rrdtool data , using rrdtool xport retreive data rrd files. today noticed following: when viewing data now-1day: there datapoint of 100 when viewing data now-31day, datapoint of 100 seen... how can make sure datapoints within specified time when using xport? i'm using --step 10, didn't make difference. no matter --step set doesn't used. read because ignored if it's less 1 pixel, what's suggested solution problem? additional info: i'm using collectdtool default rrdtool plugin options: http://collectd.org/documentation/manpages/collectd.conf.5.shtml#plugin_rrdtool edit: seems essence of rrdtool have several archives 1 month, 1 day, 1 year etc, makes sense can't every single datapoint archive 1 month? the number of data points depends on available data ... if high-resolution rra covers 30 days (for example) data lower resolution rra once request data more 30 days.

r - aggregate/sum with ggplot -

Image
is there way sum data ggplot2 ? i want bubble map size depending of sum of z. currently i'm doing dd <- ddply(d, .(x,y), transform, z=sum(z)) qplot(x,y, data=dd, size=z) but feel i'm writing same thing twice, able write something qplot(x,y, data=dd, size=sum(z)) i had @ stat_sum , stat_summmary i'm not sure appropriate either. is possible ggplot2 ? if not, best way write 2 lines. it can done using stat_sum within ggplot2. default, dot size represents proportions. dot size represent counts, use size = ..n.. aesthetic. counts (and proportions) third variable can obtained weighting third variable ( weight = cost ) aesthetic. examples, first, data. library(ggplot2) set.seed = 321 # generate somme data df <- expand.grid(x = seq(1:5), y = seq(1:5), keep.out.attrs = false) df$count = sample(1:25, 25, replace = f) library(plyr) new <- dlply(df, .(count), function(data) matrix(rep(matrix(c(data$x, data$y), ncol = 2), data$count), byrow = ...

c# - calling a serverside method in a javascript function? -

here calling javascript function on button click , need call server side method inside javascript function after finishing execution. javascript function function exportcharts(exportformat) { initiateexport = true; (var chartref in fusioncharts.items) { if (fusioncharts.items[chartref].exportchart) { document.getelementbyid("linktoexportedfile").innerhtml = "exporting..."; fusioncharts.items[chartref].exportchart({ "exportformat": exportformat }); } else { document.getelementbyid("linktoexportedfile").innerhtml = "please wait till chart completes rendering..."; } } } server side method protected void imgbtnexportppt_click(object sender, imageclickeventargs e) { try { predictexporttoppt objoexporttoppt = new ...

haskell - Access environment in a function -

in main can read config file, , supply runreader (somefunc) myenv fine. somefunc doesn't need access myenv reader supplies, nor next couple in chain. function needs myenv tiny leaf function. how access environment in function without tagging intervening functions (reader env) ? can't right because otherwise you'd pass myenv around in first place. , passing unused parameters through multiple levels of functions ugly (isn't it?). there plenty of examples can find on net seem have 1 level between runreader , accessing environment. i'm accepting chris taylor's because it's thorough , can see being useful others. heatsink 1 attempted directly answer question. for test app in question i'll ditch reader altogether , pass environment around. doesn't buy me anything. i must i'm still puzzled idea providing static data function h changes not type signature of g calls , f calls g. though actual types , computations involved unchanged. se...

Visual C++: why watch view for derived class is not showing fields of base class? -

i have split class myclass 2 classes myclassbase , myclassderived example see attached images: myclassderived i seeing members myclassderived, no details on other base class members http://i46.tinypic.com/14ljwxs.jpg i need expand see more members of class myclass i see more members of class without expanding http://i45.tinypic.com/mwfbzt.jpg why doesnt watch shows more members, there option cause watch show more members??

c# - How to display a TimeSpan in MVC Razor -

so have duration in seconds of video , display duration in razor. currently using @timespan.fromseconds(item.duration).tostring() however rest of code using uses @html.displayfor(modelitem => item.description) is there way duration (currently int) display timespan? using @html.displayfor syntax. item.duration pulling form entity framework model held int in database. you can extend model class using partial class definition. public partial class my_class_that_has_been_created_by_ef { public string timespan { { return timespan.fromseconds(duration).tostring(); } } } then use in view with @html.displayfor(modelitem => item.timespan)

multithreading - Display a Dialog in a thread in python -

i trying display loader-dialog in thread because when start upload system of files can't see window until processing finished. i tried this: thread.start_new_thread(self.display_loader(),(self)) but didn't work. there special way run new window in thread? everything done python , pygtk when self.display_thread() , call display_thread function right there, , pass return value first argument thread.start_new_thread . that's not intended. that said, think you're better off doing other way around; let main thread own ui, , loading off in thread. remember gtk+ not thread-safe, it's absolutely best all interaction gtk+ single thread. update : actually, above perhaps over-simplifying bit, it's "common truth" i've understood (i've been using gtk+ ~15 years seldom threads). this article re-states in more forgiving way, not sure if makes life easier in case, though. wanted mention in completeness' sake.

c# - xUnit and Moq do not support async - await keywords -

i trying discover how apply async , await keywords xunit tests. using xunit 1.9 , async ctp 1.3. here test case i have interface specifies 1 asynchronous method call public interface idostuffasync { task anasyncmethod(string value); } i have class consumes interface , calls async method public class useanasyncthing { private readonly idostuffasync _dostuffasync; public useanasyncthing(idostuffasync dostuffasync) { _dostuffasync = dostuffasync; } public async task dothatasyncoperation(string thevalue) { await _dostuffasync.anasyncmethod(thevalue); } } in tests wish check method dothatasyncoperation calling method correct value mock interface , use moq verify call [fact] public async void the_test_will_pass_even_though_it_should_fail() { var mock = new mock<idostuffasync>(); var sut = new useanasyncthing(mock.object); mock.setup(x => x.anasyncmethod(it.isany<string>()));...

iOS - How to locate all files on my IPad/IPhone through Objective-C -

i writing app allow users browse through files of extension (say pdf, xls) on iphone/ipad. app upload file server. the app should able locate files not located in sandbox directories. how can done in objective-c? thanks lot. you can enable users open documents other applications application , send them server. in application, must specify type of documents want open (uti).

list - Covariance and Scala Collections -

i'm trying head around covariance of scala's collections. have following: abstract class mediaformat{ def name:string def status:string } case class h264_high(status:string="on") extends mediaformat { def name = "h264_high" } case class h264_med(status:string="on") extends mediaformat { def name = "h264_med" } case class h264_low(status:string="on") extends mediaformat { def name = "h264_low" } case class h264_syndication(status:string="off") extends mediaformat { def name = "h264_syndication" } what wanted have set of of these formats because need collection each format occurs once, tried: object mediaformat { val allformats:set[mediaformat] = set(h264_high,h264_low) } this gave me compile time exception because, understand, set invariant. so think, guess i'll have use list , manage repeated values myself but try this: object mediaformat { val...

iText HTML Worker issue -

i using itext java api convert html pdf using htmlworker class. need add html link in table cell, giving following error. java.lang.classcastexception: com.itextpdf.text.html.simpleparser.cellwrapper incompatible com.itextpdf.text.paragraph <tr> <td width="45%">name:test123</td> <td width="25%">date: july 2012</td> <td width="30%"><a href="google.com">link</a></td> </tr> any idea how fix or alternatives? if can, suggest dump htmlworker, since has been discontinued in favor of xml worker: the project : http://sourceforge.net/projects/xmlworker/ the demo : http://demo.itextsupport.com/xmlworker/ the documentation : http://demo.itextsupport.com/xmlworker/itextdoc/index.html

wpf - BInding from Template within a Style -

i'm trying work out controltemplate.triggers in style below, , haven't figured out how find named ellipse , path properties. for example, when ismouseover, change background of ellipse. way find ellipse can set fill property way have set style? there better way lay out? cheers, berryl <style x:key="closecrosstogglebuttonstyle" targettype="{x:type togglebutton}"> <setter property="contenttemplate"> <setter.value> <datatemplate> <grid background="transparent"> <!-- background of button, ellipse. --> <ellipse x:name="theellipse" /> <!-- path renders cross. --> <path x:name="thecross"... </grid> </datatemplate> </setter.value> </setter> <setter property="template"> <setter.value> <co...

Cropping an image with PHP or Javascript -

i have image called 'progressbar.png'. there way crop image, php or javascript, each time page loads image crop depending on progress percentage , loaded page. example, if image 200px wide, @ 25% progress image cropped 50px wide. make div, set background of div image, , manipulate div's width whatever want. html: <div id="progressbar"></div> css: #progressbar{ background:url(progressbar.png) top left; height:progressbarheightpx; } javascript: document.getelementbyid('progressbar').style.width='50px' or done in php printing out width directly div: <div id="progressbar" width="<?php echo $percent_done*200;?>px"></div>

objective c - uibutton hide and dropdown text -

i have signup button switches screens signup form. i'd hide button , drop down text boxes beneath when button tapped (instead of switching screens). possible? have in .h file... @property (nonatomic, strong) iboutlet uibutton *emailsignup; - (ibaction)hidebutton:(id)sender; and in .m file method follows - (ibaction)hidebutton:(id)sender { [self.emailsignup sethidden:yes]; } however seems crashing whenever try test. advice? thank guys in advance. know there long way go, feel first step. it sounds haven't connected button created in interface builder portion of xcode emailsignup iboutlet. can going interface builder, selecting file's owner , connection navigator (in right side panel, designated arrow icon in tab bar). then, drag outlet button.

java - Maven IDEA plugin (or eclipse plugin) -

from have understood, not best way open project built maven in intellij using idea plug-in, calling: mvn idea:idea but open directly pom file (intellij has default plug-in maven); same thing, eclipse. could provide arguments on why better approach? this applies equally intellij , maven: changing pom.xml file not reflected in ide, must rebuild project (possibly losing configuration (?)) every time. moreover, if team member modifies pom.xml , have remember rebulding project (which require closing , reopening it). additional step required when opening new project ides have other maven features, e.g. both of aforementioned environemnts can show dependency graphs use mvn plugin last resort when ide goes crazy , cannot figure out maven configuration correctly.

python - Facebook publish HTTP Error 400 : bad request -

hey trying publish score facebook through python's urllib2 library. import urllib2,urllib url = "https://graph.facebook.com/user_id/scores" data = {} data['score']=score data['access_token']='app_access_token' data_encode = urllib.urlencode(data) request = urllib2.request(url, data_encode) response = urllib2.urlopen(request) responseasstring = response.read() i getting error: response = urllib2.urlopen(request) file "/system/library/frameworks/python.framework/versions/2.6/lib/python2.6/urllib2.py", line 124, in urlopen return _opener.open(url, data, timeout) file "/system/library/frameworks/python.framework/versions/2.6/lib/python2.6/urllib2.py", line 389, in open response = meth(req, response) file "/system/library/frameworks/python.framework/versions/2.6/lib/python2.6/urllib2.py", line 502, in http_response 'http', request, response, code, msg, hdrs) file "/system/libra...

makefile - Preprocessors directives have no effect -

i experiencing technical difficulties preprocessor directives : #ifdef, #define i have program built makefile, , have 2 options 2 build : standalone or embedded. did : #ifdef _mdimode_ //code embedded #else //code standalone (default) #endif and in main file when compile in embedded purpose wrote : #define _mdimode_ but seems g++ not recognize or understand it. go in else , never compile code embedded version. infos: gnu make 3.82 g++ (gcc) 4.6.1 20110908 (red hat 4.6.1-9) file suffix : .c this bit of guess without more information. assume code in different file main file. if #define doesn't propagate part of project. have set in file contains code, or in header #include d in it. you can choose set #define in options of compilation command: g++ -c -d_mdimode_ mycode.c

JSF, ajax and commandLink, don't redirect? -

i'm wonking on jsf application, want use commandlink execute ana action on managed bean, there server call, dont want reload page, i've tried commandbutton , attribut update works? how can make commandlink ? i resolved problem using commadlink of primefaces 3.2 :) just return null or void action method. <h:commandlink value="submit" action="#{bean.submit}"> <f:ajax /> </h:commandlink> with public void submit() { // ... } you can use <f:ajax listener> attribute instead. <h:commandlink value="submit"> <f:ajax listener="#{bean.submit}" /> </h:commandlink>

c++ - Error correcting codes -

i need use error correcting technique on short messages (between 100 , 200 bits). space available add redundant bits constrained 20-50%. i have implement coding , decoding in c/c++. needs either open sourced or sufficiently easy program. (i have had experience in past decoding algorithms - dreadful!) can advise of suitable error code use (with relevant parameters) ? take @ reed solomon error correction. sample implementation in c++ available here . for different option here - see item #11 edit: if want commercial library - http://www.schifra.com/faq.html

Preferred 3d model format of THREE.JS -

what preferred 3d model format of three.js used 3d modelling softwares (can export format). ask this, because have 3d models in own unique format, , use them in three.js. while write own loader, think it's better convert them standard format. we have our own json geometry format . you can use these: editor (drag object window, select , select file/export geometry ) blender exporter python script obj json

How to combine Solr Term Frequency and Field Boosting -

for search module want combine solr term frequency , field boosting. example: a search "house" result in list of documents entries boosted title field , term frequency of term "house" throught other fields. it works: used omitnorms , ^ operator use term frequency , field boosting. what want know : what best "boost value" use term , approach search results want ?

performance - is it possible to overload a php script or to overload server via requesting a php script too much? -

seems long question. couple of opinions based on general experience. i use php script perform several tasks on server. wondering whether make difference if used, say, 3 different scripts 3 different tasks or if not matter @ all? take account count on 2-3k users @ time (evening time, pretty rare) , still can't afford server 300 bucks month using seperate scripts identify issues each one. error messages , pointers in logs exact files. also helps see 1 runs long(est) , if 1 script crashes doesn't affect others. can more monitor scripts need optimizing. just make sure not depending on each other.

amazon web services - AWS SQS practical code PHP -

i had question here i'm still missing point understanding how use sqs, out code please. question: 1 place inside sqs? i've read through amazons tutorial , concept seems lovely im missing practical side of things. instance, diagram great: http://awsmedia.s3.amazonaws.com/catalog/images/159-for-madhu.png go inside sqs? understand how upload s3, still grey sqs part require_once('sdk-1.5.6.2/sdk.class.php'); //random strings $aws_key = "my_access_key"; $aws_secret_key = "my_secret_key"; //create new sqs queue , grab queue url $sqs = new amazonsqs(array( "key" => $aws_key, "secret" => $aws_secret_key )); $response = $sqs->create_queue('test-topic-queue'); $queue_url = (string) $response->body->createqueueresult->queueurl; $queue_arn = 'arn:aws:sqs:us-east-1:encq8gqracxv:test-topic-queue'; $queue_arn = 'arn:aws:sqs:us-east-1:encq8gqracxv:test-topic-queue'; $topic_arn = 'arn...

Javascript createElement and appendchild in one step -

i want create element , append other elements in 1 step. var header = document.createelement("thead").appendchild(document.createelement("tr")); why code outputs tr , not thead? when use code correct (thead + tr there) var header = ch.createelement("thead"); header.appendchild(ch.createelement("tr")); because node.appendchild() returns the appended child ... var appendedchild = element.appendchild(child); .. can reference child's parentnode ( sample fiddle ): var header = document.createelement("thead") .appendchild(document.createelement("tr")) .parentnode; // row's parentnode, i.e.: thead

jquery - How to remove div without inner elements -

i remove 1 div element, without children. example, let's have 1 div id wrapper, , inside 5 paragraphs. i want remove wrapper div, leave paragraphs alive. have tried both remove() , detach(), both clean out inner elements. any advice? http://api.jquery.com/unwrap/ should it: the .unwrap() method removes element's parent. inverse of .wrap() method. matched elements (and siblings, if any) replace parents within dom structure...

java - GXT 3 change tab style (add css) -

gxt 3 has function, adds tab tabpanel tabpanel.add(html, new tabitemconfig(title, true)); i have change style of name of tab , contents. these have no effect: tabpanel.setstylename("tab-title", true); html.setstylename("tab-title", true); tabitemconfig has no method change style. how achieve?... i see you've found solution, leave here, because it's quite simple , may save somebody's time: class stylabletabpanel extends tabpanel { public void applytabstyles(widget widget, string styles) { finditem(getwidgetindex(widget)).applystyles(styles); } } then: tabpanel = new stylabletabpanel(); html shorttext = new html("lorem ipsum..."); tabpanel.add(shorttext, "short text"); html longtext = new html("<b>lorem ipsum dolor sit amet...</b>"); tabpanel.add(longtext, "long text"); tabpanel.applytabstyles(longtext, "margin-left: 300px;")...

64bit - msvcr100.dll Error - WinXP x64 -

i attempting run program created in vs2010, on xp 64bit system. has run fine on xp-sp3 32bit windows 7 versions. when running on xp 64bit crashes when trying load displaying error referencing: modname: msvcr100.dll modver: 10.0.30319.1 offset:00000000000760d9 i realise file references 2010 vcredist, installed program , after checking had latest versions found ones installing required xp-sp3 (which doesn't exist 64bit xp). have tried installing latest 2010-sp1 redistributable (which doesn't requires xp-sp3) yet same error still applies. has had error when trying run program on xp 64bit? possibly looking in wrong direction in thinking caused vcredists? or impossible run program requires 2010 vcredists on xp os hasn't got sp3? this problem solved, old code made part of splash screen on our program , nothing seemingly vcredists. program seems run fine on xp sp2 evidently possible :)

html - How to fill 100% of webpage with a colour -

can please help? have page has header, main content box , footer. here’s link page in development my test page . problem i’m having have called “background box” (the box in pink dark brown top border). need auto-fill whole screen, right past footer, @ moment fills screen fold of screen, if scroll down doesn’t fill entire screen. have tried height: auto; , height: 100%; none of these give desired effect. does have suggestions can fix issue? if code can post here, should able view code through browser. if want sure background box serve background other elements, have tried nesting other elements background box? instance: <div id="backgroundbox"> background box <div id="contentbox">...</div> <div id="footer">...</div> </div> you use css tricks (a negative margin-top , example) raise #contentbox above #backgroundbox starts.

arrays - How to initialise a complex C struct in one line? -

i have structure: typedef struct stock { const char* key1p2; // stock code const char* key2p2; // short desc const char* desc1; // description const char* prod_grp; // product group const char dp_inqty; // decimal places in quantity const long salprc_u; // vat excl price const long salprc_e; // vat includive price const long b_each; // quantity in stock const long b_alloc; // allocated qty const char* smsgr_id; // subgroup const char** barcodes; // barcodes } stock_t; and want initialise arrays of instances of structure, in 1 line of code per stock struct. i have tried: stock_t data_stock[] = { { "0001", "soup", "tomato soup", "71", 0, 100, 120, 10, 0, "", {"12345", "23456", null} }, { "0002", "melon", "melon , ham", "71", 0, 200, 240, 10, 0, "", {"34567", "45678", null} ...

php - Only show link if conditional equals true -

i want link appear when $data['block'] equals 1, 3 or 4. not if equals 2 or 5. <td style="font-size:18px;color:#f0cb01;"> <a href="kickcodes.php?id='.$data["block"].'">reason codes</a> </td> edit while ($data = mysql_fetch_array($query)) { echo ' <tr style="background-color:#576c11;"> <td style="font-size:18px; color:#f0cb01;">'.$data["keyword"].'</td> <td style="font-size:18px;color:#f0cb01;">'.$data["block"].'</td> <td style="font-size:18px;color:#f0cb01;">'.$data["phone"].'</td> <td style="font-size:18px;color:#f0cb01;">'.$data["reason"].'</td> <td style="font-size:18px;color:#f0cb01;"><a href="kickcodes.php?id='.$data ["block"].'">kickcodes</a>...

oop - Is it possible to override a constructor in C#? -

is possible override constructor of base class in derived class? if so, how can accomplished , in use case practical? if not, why not? no, can't override constructors. concept makes no sense in c#, because constructors aren't invoked polymorphically. state class you're trying construct, , arguments constructor. constructors aren't inherited @ - constructors derived class must chain either constructor in same class, or 1 of constructors in base class. if don't explicitly, compiler implicitly chains parameterless constructor of base class (and error occurs if constructor doesn't exist or inaccessible).

php - Cakephp call an component method inside a helper -

i use cakephp 2.1 , need call component method witch resides in plugin, view helper: the component here: /app/plugin/abc/controller/component/abccomponent.php the helper here: /app/view/helper/simplehelper.php i tried inside helper: app::import('component', 'abc.abc'); $this->abc = new abc(); or $this->abc = new abccomponent; or $this->abc = $this->components->load('abc.abc'); inside controllers component works no problem. know isn't recommended (mvc design etc.) if don't use way need duplicate lot of code. need make like: myhelper extends helper{ $simplevar = component->get_data(); } i use cakephp 2.4 this how call component helper: app::uses('aclcomponent', 'controller/component'); class myhelper extends apphelper { public function myfunction() { $collection = new componentcollection(); $acl = new aclcomponent($collection); // here can use acl...

Override next parameter django-social-auth to track facebook logins and new users in Google Analytics -

i have been working django few months , modifying django code base made developer. i trying find way track facebook registrations , logins in google analytics , way thought of doing adding parameter url user redirected after connecting through facebook. at moment using 'next' parameter this: <a href="{% url socialauth_begin 'facebook' %}?next={{ request.path }}"> i want able override next param in order add: {{request.path}}?new_facebook_user or {{request.path}}?facebook_login if user registered. where think best place of doing is? think valid approach track fb logins , new users in google analytics? that approach won't work, @ least won't able determine if user new or not when create link. app provides social_auth_new_user_redirect_url setting define different url redirect newly created accounts. setting takes precedence on ?next= parameter, lost if defined.

c# - choosing to hide or show tooltips based on bool -

so figured i'm making stupid mistake here. in first of many controls, need either show balloon tooltip when bool true or not show them when bool false. know showalways not need modify , i've tried various solutions already. spot problem? bool set checked dropdown item in menu strip item. it open application correct display, check option show it, shows there after. public void changeballoonproperties(bool boolset) { tooltip helpdeskinfobuttontooltip = new tooltip(); if (boolset) { helpdeskinfobuttontooltip.tooltiptitle = "helpdesk information button"; helpdeskinfobuttontooltip.usefading = true; helpdeskinfobuttontooltip.useanimation = true; helpdeskinfobuttontooltip.isballoon = true; helpdeskinfobuttontooltip.showalways = true; helpdeskinfobuttontooltip.autopopdelay = 5000; helpdeskinfobuttontooltip.ini...

c# - linq beginner, foreach statement without declaration? -

i'm reading linq dummies stuff , got question. here code: private void btntest_click(object sender, eventargs e) { // create array data source. string[] querystring = { “one”, “two”, “three”, “four”, “five” }; // define query. var thisquery = stringvalue in querystring stringvalue.length > 3 select stringvalue + “\r\n”; // display result. foreach (var thisvalue in thisquery) txtresult.text = txtresult.text + thisvalue; } what txtresult, work without declaration? txtresult value of name property of used textbox control in code. need add textbox in application , assign name property value 'txtresult' code work.

How to remove a key from a python dictionary? -

when trying delete key dictionary, write: if 'key' in mydict: del mydict['key'] is there 1 line way of doing this? use dict.pop() : my_dict.pop('key', none) this return my_dict[key] if key exists in dictionary, , none otherwise. if second parameter not specified (ie. my_dict.pop('key') ) , key not exist, keyerror raised.

php - Return reference to static variable from __callStatic? -

i'm trying find workaround static variables not being copied on extending classes (which doesn't play nicely late static binding), here thought might work, gives me "php fatal error: can't use function return value in write context" : <?php class person { protected static $tlsb_names = ['name']; protected static $tlsb_vars = []; public static function & __callstatic($method,$args) { echo "call static " . $method . " on " . get_called_class() . "\n"; if(in_array($method,static::$tlsb_names)) { if(!array_key_exists(get_called_class(),static::$tlsb_vars)) { static::$tlsb_vars[get_called_class()] = []; } if(!array_key_exists($method, static::$tlsb_vars[get_called_class()])) { echo "set var $method " . get_called_class() . "\n"; static::$tlsb_vars[ge...

html - Loading an external .htm file to a div with javascript -

possible duplicate: loading external .htm javascript div loading external .htm file div javascript this entire code: <html> <head> </head> <body> <script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript"> $(function(){ $('.ajax') .click(function(e){ e.preventdefault() $('#content').load( 'file.htm' ) }) }) </script> <div id="content"> <p>random text</p> </div> <div><a href="#" class="ajax">link</a></div> </body> </html> the code works fine loading external file div in firefox, nothing happens in chrome , ie, when click link. advice ? while it's not cause of problem, it's practice use semicolons: $(function(){ $('.ajax') .click(function(e){ e.preventdefault(); $(...

ruby on rails - after_create achievement notification from model -

i building achievement system , final part notifying user. once achievement created in model class achievement < activerecord::base def self.check_conditions_for(user) if user.month_views >= 30 , !user.views_awarded?(self) user.award(self) end end end i need flash custom notice user can close. best way initiate model? know can call flash messages controller need workaround in instance. similar how stack overflow displays badges. ok if user views video -- presumably hitting url, should call achievement.check_conditions_for(user) in associated action. achievement.check_conditions_for(user) can return value - maybe notice message - can send normal flash message. no need workaround here if executed when action called. for example, if have controller videos , you're calling action watch : def watch @video = video.find(params[:id]) @notice = achievement.check_conditions_for(current_user) respond_to |format| format.js end en...

How to make non-clickable App Icon on Action Bar like YouTube App in android -

i want add non clickable app icon on action bar youtube app have app icon on top-left of screen.currently app icon on action behave button. please see know app icon: http://developer.android.com/design/patterns/actionbar.html i think looking getsupportactionbar().sethomebuttonenabled(false); appcompat. if aren't using appcompat, getactionbar().sethomebuttonenabled(false) assuming activity extending actionbaractivity .

iphone - UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath -

i have search @ https://stackoverflow.com/search?q=uitableview+datasource+must+return+a+cell+from+tableview%3acellforrowatindexpath ,but know need check if cell nil,but cell custom,and not use xib,i use storyboard.i choice class customplacetableviewcell @ storyboard.as http://i.stack.imgur.com/g0rro.png code: - (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath { customplacetableviewcell *cell = [tableview dequeuereusablecellwithidentifier:cellidentifier]; //if ([cell iskindofclass:[customplacetableviewcell class]]) { cell = (customplacetableviewcell *)cell; } //retrieve place info place *place = [self.placedatacontroller objectinplacelistatindex:indexpath.row]; //set cell place info if (place.name) { cell.namelabel.text =place.name; } else { cell.namelabel.text = @"portaura"; } if (place.distance) { cell.distancelabel.text = place.distance; } else { cell.distancelabel.text = @"port...

javascript - Partials template in underscore (just like in handlebars)? -

i have backbone model this var peoplemodel = backbone.model.extend({ defaults: { "people": [ { "username": "alan", "firstname": "alan", "lastname": "johnson", "phone": "1111", "email": "alan@test.com" }, { "username": "allison", firstname: "allison", "lastname": "house", "phone": "2222", "email": "allison@test.com" }, { "username": "ryan", "firstname": "ryan", "lastname": "carson", "phone": "3333", "email": "ryan@test.com" }, { "username": "ed", "firstname": "edward", "lastname": "feild", "phone": "4444", "email": "ed@test.com" },...

routing - Zend Framework wildcard subdomain route for variable domains -

i busy developing engine zend framework makes able run couple of websites (all same kind). now work wildcard subdomain these websites, problem can't figure out how write route in application.ini 'head' domain variable. what need route: domain 1: *.site1.com domain 2: *.site2.com (etc.) what have routes.subdomain.type = "zend_controller_router_route_hostname" routes.subdomain.route = ":subdomain.:domain" routes.subdomain.defaults.module = "default" routes.subdomain.chains.index.type = "zend_controller_router_route" routes.subdomain.chains.index.route = ":controller/:action/" routes.subdomain.chains.index.defaults.controller = "data" routes.subdomain.chains.index.defaults.action = "index" thanks in advance! nick

android - executor service + view.post(Runnable) -

i want start several threads, retrive data net, perform actions , change ui regarding data. i'm using executor service executorservice = executors.newfixedthreadpool(3); all data get, when try invoke imageview.post returns true body of regarding runnable not executed: log.v("imageloader", "before post + " + imageview); imageview.post(new runnable() { @override public void run() { log.v("imageloader", "in post - " + bmptoshow.tostring() + "/" + imageview); if (imageview.gettag().equals(url)) { imageview.setimagebitmap(bmptoshow); } } }); if execute 10 runnables in executor service in log can find 10 "before post" messages, ntasks (depends on how many task allow in "executors.newfixedthreadpool(ntasks)") "in post" messages i can't figure out how ntasks connects number of view.post runs. ps. happens first start of app (i...

Should I use XML for this situation? -

i building program has different inputs , ouputs depending on "vehicle" loaded. want people able load different vehicles need type of file keeps track of information. is xml going best way this? there option should consider? thank you! xml commonly used situation described , there plenty of tools out there automatically creating , parsing xml it's solid choice.

php - Issues accessing GET variables in CodeIgniter -

is there way retrieve parameters in url inside html page use $_get in codeigniter? for instance, if in view , had url: http://www.mysite.com/controller/function/var1/var2 then how able access var1 , var2 were? like this: $var1 = $this->uri->segment(3); $var2 = $this->uri->segment(4); read more here .

android - Having a dialog with a scrollview and persistent buttons at the bottom -

i having trouble creating layout dialog want display dialog scrollview buttons showing @ bottom when scrollview gets big pushes buttons @ bottom off screen. i can desired effect if align buttons @ bottom of parent true if scrollview has little content in there big dialog lot of empty space. here have <?xml version="1.0" encoding="utf-8"?> <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <scrollview android:id="@+id/scrollview1" android:layout_width="match_parent" android:layout_height="wrap_content"> <linearlayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" > <textview ...

ios - Hide in-app purchase while being reviewed by Apple -

i have iphone app in-app purchase , want able release app independently (the in-app purchase). in other words, there times in-app purchase "waiting review" state , shouldn't displayed app. if understand correctly, in situation, skproductsresponse object (returned apple app store in response request information list of products) have particular product listed under invalidproductidentifiers array. thus, before displaying in-app purchase, inspect array check existence of product. should still allow apple test in-app purchase released version of app since assume testing done in sandbox in-app purchases valid. is correct? should follow different approach? you describe proper workflow displaying iap content user. put modal dialog or uiactivityindicator telling customer iap content being downloaded. use productidentifiers returned populate store gui. i discourage hard coding in specific view specific in app purchase, , attempting populate view. can if you...

postgresql - playframework-1.x heroku postgres -

i tried deployed play 1.2.4 app heroku. app works great locally, on heroku got strange errors, try save data. 2012-07-02t21:26:04+00:00 app[web.1]: internal server error (500) request post /players/save 2012-07-02t21:26:04+00:00 app[web.1]: 2012-07-02t21:26:04+00:00 app[web.1]: oops: unexpectedexception 2012-07-02t21:26:04+00:00 app[web.1]: unexpected error occured caused exception unexpectedexception: unexpected error 2012-07-02t21:26:04+00:00 app[web.1]: 2012-07-02t21:26:04+00:00 app[web.1]: play.exceptions.unexpectedexception: unexpected error 2012-07-02t21:26:04+00:00 app[web.1]: @ play.data.validation.validationplugin.beforeactioninvocation(validationplugin.java:59) 2012-07-02t21:26:04+00:00 app[web.1]: @ play.plugins.plugincollection.beforeactioninvocation(plugincollection.java:594) 2012-07-02t21:26:04+00:00 app[web.1]: @ play.mvc.actioninvoker.invoke(actioninvoker.java:134) 2012-07-02t21:26:04+00:00 app[web.1]: @ invocation.http request(play!) 2012-07-02t21:26:04...