Posts

Showing posts from 2012

java - Get application path with JAX-RS service -

i have jax-rs service want know application context path. before, using httpservletrequest application url, using these methods: public static string getapplicationbaseurl(httpservletrequest request) { return string.format("%s://%s:%s%s", request.getscheme(), request.getservername(), request.getserverport(), request.getcontextpath()); } i saw @context in jax-rs, returns paths beginning jax resource. can retrieve application path? i found answer. using @context javax.ws.rs.core.uriinfo class, but, can inject httpservletrequest too. so, can use getapplicationbaseurl method wrote.

Why does Automator show 1 result on "Set Value Of Variable" but 2 results in "Get Value Of Variable"? -

Image
see screenshot. why happening? want 1 result, not 2. you have value of variable @ end of "set value of variable". why trying again? try putting "view results" item in place of "get value of variable". think you'll find have need.

css - Stop a single table cell from determining table width -

a b b x b i've got table inside containing block has set width of 400px. when browser width less 421px containing block width switches 95%. cells of type "a" , "b" contain simple text. there single cell contains link white-space:nowrap applied. i need table self determine dimensions (so no table-layout:fixed-width ), not take in account cell "x" when determining width of second column. ok hide content of cell "x" doesn't fit. i have tried applying width:100% overflow hidden on manner of different elements, no avail. html <table> <tr> <th style="vertical-align:bottom;"> <figure> <div class="minical-mo">month</div> <div class="minical-da">date</div> </figure> </th> <td style="vertical-align:bottom;"><h2>summary</h2

ios - Why does this NSArray in an NSNotification block (apparently) never get released in an ARC environment? -

i have view controller that's subscribing notifications broadcast elsewhere. part of large object graph has cleanup needs done when children dealloc'd. dealloc never being called in 1 of children (arc environment), (if understand) means somewhere still retained, causing arc never dealloc when vc dismissed. i've traced offending code following 2 lines. first version causes vc , children never dealloc'd. in second version, things work fine , gets dealloc'd when vc dismissed. my question why? arc can't understand why additional nsarray not released. hopefully enough code. can post more if need be. here's version leads vc (and children, etc) never being dealloc'd: // subscribe notifications number of trackables has changed [[nsnotificationcenter defaultcenter] addobserverforname:kupdatednumberoftrackables object:nil queue:[nsoperationqueue mainqueue] usingblock:^(nsnotification *note) { if ([note.object iskindofclass:[nsarray class]]) {

Django: Order AdminModel by Custom Property -

i have model property i'd have adminmodel ordered by. class storeadmin(admin.modeladmin): list_display = ('user', 'total',) admin.site.register(store, storeadmin) model: class store(models.model): user = models.foreignkey(user, related_name="store") @property def total(self): num = 0 x in coins.objects.all(): num += x.value return num how order modeladmin total since property? in advance help! give link shot, may have answer. https://stackoverflow.com/a/8478586/1011998 in short, since property you're trying order doesn't exist in sql, sql has return results , order them property in python instead. can imagine, slower. i'd suggest looking storing field "total" field in database denormalized field (int) , update whenever user object updated overriding save() method. way benefit both speed of not having , dynamically recalculate totals on fly (that'll bec

How to extend a lightweight provider in Chef -

i creating bunch of different chef providers deploy different types of applications. chef's documentation extend lightweight provider suggests possible doesn't do. page suggests perhaps call mixin needed, don't know structure code should have in file under /libraries or how include code in under /providers . here examples of want do. in base class under /libraries : repository "http://my.svn.server/#{deployment[:project]}/branches/#{node[:chef_environment]}/" user "deploy" scm_provider chef::provider::subversion svn_username "svn_user" svn_password "password" in provider torquebox rails app deployments: deploy_revision "/my/deployment/directory/#{deployment[:project]}" # magically mixin code libraries environment "rails_env" => node[:chef_environment] restart_command "rake torquebox:deploy" end and of course other types of providers different types of applications. can point

xamarin.ios - struggling testing IOS in app purchase with xamarin -

for last couple of days have been struggling trying set enviroment test in app purchase in xamarin. docs page not clear on needs done, @ least me. for have researched, need sign contract apple, requires me give apple information bank account, taxes, etc. information going take little while, maybe week. without contract, can test in sandbox mode in app purchase? so far, have created development provisioning profile, app id , bundle id well, products going sell within app, , test users. tried getting product info device, did not work, no error, or app crash. missing here causes behavior. i read in page need install provisioning profile , configure xcode sign app profile. how do in xamarin studio? also, need tell xcode whats application bundle id, again, how do this? i read in-app purchase programming guide , gave me overall understanding architecture needed implement in app purchases, failing on little details. any appreciated. thank much. craigd's answer

java - Implement a subclass Square that extends the Rectangle class -

//implement subclass square extends rectangle class. in constructor, accept x- , y-positions of center , side length of square. call setlocation , setsize methods of rectangle class. these methods in documentation rectangle class. supply method getarea computes , returns area of square. write sample program asks center , side length, prints out square (using tostring method inherit rectangle) , area of square. //ok... last minute, don't understand wrong code giving me error square cannot resolved type... here class: import java.awt.rectangle; public class squares22 extends rectangle { public squares22(int x, int y, int length) { setlocation(x - length / 2, y - length / 2); setsize(length, length); } public int getarea() { return (int) (getwidth() * getheight()); } public string tostring() { int x = (int) getx(); int y = (int) gety(); int w = (int) getwidth(); int h = (int) getheight(); return "square[x=" + x + &quo

linux - How to SSH into a server from a node.js application? -

var exec = require('child_process').exec; exec('ssh my_ip',function(err,stdout,stderr){ console.log(err,stdout,stderr); }); this freezes - guess, because ssh my_ip asks password, interactive, etc. how correctly? there's node.js module written perform tasks in ssh using node called ssh2 mscdex. can found here. example you're wanting (from readme) be: var connection = require('ssh2'); var c = new connection(); c.on('connect', function() { console.log('connection :: connect'); }); c.on('ready', function() { console.log('connection :: ready'); c.exec('uptime', function(err, stream) { if (err) throw err; stream.on('data', function(data, extended) { console.log((extended === 'stderr' ? 'stderr: ' : 'stdout: ') + data); }); stream.on('end', function() { console.log('stream :: eof'); }); stre

To multiplications using parseFloat jQuery -

adding additional cost output this taking total shipping costs, splitting individual packages , outputting total of combined packages. works (in addition too) add 20% output. var adjusted_total = parsefloat(rate[1]) * custom_packages; try var adjusted_total = parsefloat(rate[1]) * custom_packages; //if adjusted_total = 100 adjusted_total *= 1.2 // give 120

html5 - Trying to display data from a database in HTML tags using Javascript -

i'm trying call function in home page change content of article in html placeholders info database before page loads. keep getting error saying i'm missing formal parameter. have done wrong? the html: <article id="article1"> <img src="images/sadface.png" alt="the image didn't load, sorry" id="img0"> <h4 id="heading0">not working</h4> <p id="p0">this item hasn't loaded, sorry</p> <script> window.onload = function splashfunction(0); </script> </article> and javascript: function splashfunction(x){ document.getelementbyid("img" + x).src="images/cart2.jpg"; document.getelementbyid("heading" + x).innerhtml="cart"; document.getelementbyid("p" + x).innerhtml="cart"; }; in order change dom call database have use ajax , hope know that. as code, defining

android - Issue with ViewHolder pattern -

so i'm using known viewholder pattern in app. viewholder: protected static class viewholder{ final imageview itemimage; final textview txtname; final textview txttitle; final webview webview; public viewholder (final imageview itemimage, final textview txtname, final textview txttitle, final webview webview){ this.itemimage = itemimage; this.txtname = txtname; this.txttitle = txttitle; this.webview = webview; } public viewholder (view convertview){ itemimage = (imageview) convertview.findviewbyid(r.id.fav_item_icon); txtname = (textview) convertview.findviewbyid(r.id.fav_item_name); txttitle = (textview) convertview.findviewbyid(r.id.fav_item_title); webview = (webview) convertview.findviewbyid(r.id.fav_webview); } } so works fine if use 1st constructor like: ... public view getview(final int position, view convertview, final viewgroup parent) {

message - How to receive Texts from phones for your webserver, and use the content of the text -

today i'm trying find out how when person texts number (i want number website) when text it, content of text goes database. issue is, can able receive text messages? know possible because facebook it. ideas? know doesn't belong here confused. thanks in advance. a simple way twilio number , use api receive sms.

c# - What is the point of this sleeping thread -

i going through code right not mine. in code there thread following code: while (true) { thread.sleep(int.maxvalue); } it catches interruptedexception , goes right loop, loop can't interrupted. does know why thread exist, purpose is? edit: full code, little bit more context: using ikvm.attributes; using java.lang; using system; using system.runtime.compilerservices; namespace applicationnamespace { internal sealed class dedicatedserversleepthread : thread { internal dedicatedserver thedecitatedserver; [methodimpl(methodimploptions.noinlining)] internal dedicatedserversleepthread(dedicatedserver dedicatedserver) { this.thedecitatedserver = dedicatedserver; base.setdaemon(true); this.start(); } [methodimpl(methodimploptions.noinlining)] public override void run() { while (true) { try { while (true) { system.threading.t

c# - EntityFramework 6 Connection Closed -

i did upgrade ef 6 , when query showing error: executereader requires open , available connection. connection's current state closed. code: var db = new entity2entities(); db.configuration.lazyloadingenabled = true; var ids = db.personbase.sqlquery(utils.query(param, "personbase")) .select(x => x.id); var result = db.employee.where(x => ids.contains(x.id)); ef 6 in alpha state, things can change in future. didnt try maybe have do db.database.connection.open(); before executing sqlquery method.

javascript - Selecting the individuals from a group of jQuery elements -

if use jquery select text inputs: var inputs = $('#form input[type="text"]'); they wrapped in jquery. can whatever want them. inputs.css('height', '1000px'); //muhahaha! as group abide. seem missing something. know can see each 1 individually if array of objects. console.log(inputs[0]); // <input type="text" /> but above output html; when it's no longer jquery object :( inputs[0].css('font-size', '100px'); // uncaught typeerror: object #<htmlinputelement> has no method 'css' how continue use jquery's methods on individual without having wrap each element again, or not possible strange, dark, inexplicable reason? didn't know begin searching one, , jquery journey has not lead me answer far. thanks! have @ page: jquery filtering inputs.eq(0).css('font-size', '100px'); should trick in case

php - Random number insert mySQL not working -

hey created 2 random numbers so: $firstlink = intval(mt_rand(100, 999) . mt_rand(100, 999) . mt_rand(1, 9) . mt_rand(100, 999)); // 10 digit $secondlink = intval(mt_rand(1000, 999) . mt_rand(1, 999) . mt_rand(10, 99) . mt_rand(100, 999)); and insert code: $result = mysql_query("insert useraccount (category,fname,lname,firstlink,secondlink,accdate) values ( '" . $cat . "', '" . $fname . "', '" . $lname . "', " . $firstlink . ", " . $secondlink . ", '" . date('y-m-d g:i:s',time()). "');"); it has no errrs , places data mysql database. however, same number both firstlink , secondlink no matter add database , have no idea why doing it! the datatype both rows i

javascript - Dynamicly Added Input is not updating on the screen -

i new javascript bear me here. i have code below checks text input fields value, if matches fire off custom dialog object/function shows dialog modal window. now goal clear out text input fired dialog open if cancel button clicked i have callback function named cancelcallback can pass dialog function. in example can see have cached input field selector hostnameselector , passed callback. below can see print out object console. console shows new value text field not update on screen. this possibly because text input filed dynamicly added screen/dom? any ideas on how can working? able use latest jquery if needed help // show notice if hostname matches domain name $(document).on('change','div.hostname > input',function() { // cached input selector var hostnameselector = $(this); var hostname = $(this).val(); var domainname = $("#domainname").val(); var pattern = new regexp(domainname + "$","g"

c# - One datagrid per row of ItemsSource binding -

currently have single datagrid defined in xaml file binds (itemsource) collection of data (called view) , displays in 1 big table (as expected , working perfectly). however need create datagrid per row, ending many datagrids containing single row of data. the thing can think of is: - dynamically create datagrids in-code (somehow) , remove xaml - populate itemsource of each of these dynamically created datagrids specific row of data, example (pseudo-code): for each row of view create new datagrid assign row itemsource binding does have better suggestions? can done way proposing it? there better/simpler way? the reason - customer wants print each row on seperate page create many datagrids , pass each 1 printvisual independantly achieve this. code: // datasource, want show 1 recipe per printed page (so per datagrid) list<viewrecipe> view xaml: <datagrid itemssource="{binding view}" autogeneratecolumns="fals

objective c - UILabel: adding 1 to a number when button pressed? -

i new this, on how change uilabel add 1 previous number, everytime button pressed. i.e want when press button uilabel turns 0 1, , if press again turns 1 2. appreciated. in advanced. know have create button, don't know code put in their? do this //header @property (nonatomic) int i; - (ibaction)buttonclicked:(uibutton *)sender; //implementation - (void)viewwillappear{ self.i = 0; } - (ibaction)buttonclicked:(uibutton *)sender{ self.i++; [self.textfield settext:[nsstring stringwithformat:@"%d", self.i]]; } self.textfield whatever text area want display number in. also, have make connection buttonclicked action button in interface builder, if you're using it.

Perl: What is the meaning of ;\$ inside the arg list of a sub declaration? -

here part of program generated s2p, program builds perl script performs particular sed command. # getsargv: read input line argument (default: $_). # move on next input file, , reset eof flag $iseof. sub getsargv(;\$){ $argref = @_ ? shift() : \$_; while( $iseof || ! defined( $$argref = <arg> ) ){ close( arg ); return 0 unless @argv; $file = shift( @argv ); open( arg, "<$file" ) || die( "$0: can't open $file reading ($!)\n" ); $iseof = 0; } 1; } i couldn't find explains sub signature on perlsub. the code work quite well, too. it's prototype . particular prototype forces parser accept usages getsargv() and getsargv($scalar) and causes them compiled as &getsargv() and &getsargv(\$scalar)

ruby - Rails - Show which category a tutorial belongs to in the tutorial index view -

i have tutorial model , tutorial_category model. have linked 2 using has_many belongs_to relationship. in tutorials index view, looping through tutorials so: <% @tutorials.each |tutorial| %> . inside loop, wanting display category each tutorial belongs to. i'm trying <%= tutorial.tutorial_categories.title %> (title attr in tutorial_category model , have :tutorial_id attribute in tutorial_category model. , :tutorial_category_id attr in tutorial model, matter). here index action in tutorials controller: def index @tutorials = tutorial.all @tutorial = tutorial.new @tutorial_categories = tutorialcategory.select("distinct title, id") respond_to |format| format.html # index.html.erb format.json { render :json => @tutorials } end end i can't figure out i'm doing wrong here. experience, should work correctly, although it's been few months since i've written ruby code i'm missing stupid here. appreciated!

javascript - XMLHttpRequest cannot load file. Origin null is not allowed by Access-Control-Allow-Origin -

$.getjson('test1.json', function(data) { (i in data.conferences) { var item = data.conferences[i]; array1.push({ cid:item.id, confname: item.cname, confstart:item.start }); } }); i use function getting values java jquery. in chrome , opera shows same error, works on ie , mozilla. give me solution please. xmlhttprequest cannot load file:///c:/users/winnova1/desktop/tree/conferences/test1.json. origin null not allowed access-control-allow-origin. uncaught typeerror: cannot read property 'conferences' of null for security reasons, on chrome , opera cannot use xmlhttprequest load local files. must run on web server, if web server running on localhost .

django - Can not iterate a ChoiceField with Select as widget -

i have issues iterating on choicefield , building own html values , labels. when specifying "widget" parameter select , field not longer iterable. however, works fine if specify radioselect . the form: class myformcreate( form ) : quotes = ( (34, "hi, patrick. wait, i'm patrick!"), (21, "i pie."), (76, "no, patrick!"), ) patrick = choicefield(choices = quotes, widget = select) and template: <select name="{{form.patrick.name}}"> {% option in form.patrick %} <option value="{{option.choice_value}}">{{option.choice_label}}</option> {% endfor %} </select> what doing wrong? (python 2.7.3 , django 1.4.5) would you're looking for? <select name="{{ form.patrick.name }}"> {% value, text in form.patrick.field.choices %} <option value="{{ value }}">{{ text }}</option>

c - what is wrong with the logic of my program? -

what's wrong logic of program. reason, when alternate turns among player, moment hits 2nd turn, skip it, , game seems dragged 1 less step. array change, when declared above main function? placement tictactoe game 1 |2 | 3 4 | 5 | 6 6 | 8 | 9 code #include <stdio.h> int check(char player); void move(char player); void outprint(void); char board[3][3] ; int main(void) { int first; char player1, player2; printf("player 1: choose symbol: \n"); player1 = getchar(); getchar(); printf("player 2: choose symbol: \n"); player2 = getchar(); getchar(); int i=0; int win; char turn; while(win == 0) { if((i%2) == 0){ turn = player1; move(player1); win = check(player1); outprint();} else { turn = player2; move(player2); win = check(player2); outprint();}

javascript - Showing nav dropdown when menu item is clicked -

i twitter bootstrap, don't need features. in though drop down function i'm trying replicate. this html: <nav class="navigation" role="navigation"> <ul class="a"> <li><a class="" href="">page 1</a></li> <li><a class="" href="">page 2</a></li> <li> <a class="" href="">page 3</a> <ul class="drop_down"> <li><a href="#">list 1</a></li> <li><a href="#">list 2</a></li> <li class="nav_divider"></li> <li><a href="#">list 3</a></li> <li><a href="#">list 4</a></li> <li><a href="#"

Android App fails on Rooted SAMSUNG SIII (d2can/d2vzw/d2spr) -

i have published android application incorporates audio processing, e.g. recording/playback of raw format. recording code raw files based on rehersal assistant app urban stew, , app works fine on non rooted samsungs. there seems issue rooted samsung siii devices. of 1 star reviews samsung galaxy siii (d2can/d2vzw/d2spr) users. why "rooting" affect audio procesing? how amend application work seamlessly on rooted phones? possible detect when device has been rooted?

Exact meaning of weights in SOLR ranking -

i have been trying different weights on solr dismax , edismax ranking , got wonder these weights mean? example, can specify qf parameter this: qf:title^2.0 body^1.0 ... what these weights mean? multiplication of each field's text score? or addition? also how pf parameter? pf:title^2.0 body^0.5 is multiplication or addition? if shed light, great. qf -> query fields measures score individual terms. boost multiplies weight individual match score field e.g. qf:title^2.0 body^1.0 document match on title field have double score document match on boby (given other factors same) pf -> phrase query measures score phrase terms e.g. query internet banking , configuration qf:title^2.0 body^1.0 , pf:title^2.0 body^0.5 should result in query :- title:internet^2 title:banking^2 body:internet^1 body:banking^1 title:"internet banking"^2 body:"internet banking"^0.5

Find error (line of error) in sql server managment studio message window -

i have on 5000 insert query want execute in sql server mangement studio(ssms) when these insert query execute no problem in message window show query executed successfully problem when of them of these query has error message query completed error , in message window difficult find between (1 row(s) affected) (1 row(s) affected) (1 row(s) affected) (1 row(s) affected) (1 row(s) affected) (1 row(s) affected) msg 2627, level 14, state 1, line 1... * my error detail .... * (1 row(s) affected) (1 row(s) affected) (1 row(s) affected) is there way sql server show error in message window? a way found open quick find window edit menu , search "msg" found error way.

java - how to separate [String] by "-" and make multiple column on android? -

i'm working on searchable dictionary. raw database separated "-" like columna(key_word) columnb(key_defination) apple - 1 kind of fruit mango - 1 fruit but want make 3 column, (column c key_details) columna columnb columnc (key_details) apple - 1 kind of fruit - round shape mango - 1 fruit - found in bangladesh when people search a, application show column b , c. reason why splited string want show coumn b , c on different window. how that? here source- /** * contains logic return specific words dictionary, , * load dictionary table when needs created. */ public class dictionarydatabase { private static final string tag = "dictionarydatabase"; //the columns we'll include in dictionary table public static final string key_word = searchmanager.suggest_column_text_1; public static final string key_definition = searchmanager.suggest_column

dymamic - Copying dynamic array in C++ -

if have like: int **arr=new int *[3]; and want make this array double size, need make new array: int **temp=new int *[6] and copy arr temp, , copy temp arr. how this? you're on right track. need is: allocate array of size 6 (you did that). copy 3 elements of pointed arr 6-array. deallocate memory pointed arr . point arr 6-array. for 2, use for loop. 3, use delete[] . 4, use pointer assignment. i'm giving hints instead of code, it's still work in end. purpose of homework learning, after all.

android - OnScrollListener in gridview in a homescreen widget, is it possible? -

i have homescreen widget (android > 4.0) gridview , show pictures within. , want make additional views (imageview icons or else) visible on scrolling grid. so if user scolls through grid, little icons within every picture gonna visible. possible? i searched setonscrolllistener on remoteviews, didn't find nor getparent access grid within griditem. thanks in advance!!! you not need onscrolllistener this. gridview knows how scroll , knows how populate additional cells in grid based upon scrolling. provide data gridview (in case, via remoteviewsfactory ).

regex - What's a good regular expression for real numbers in Java? -

what's regular expression real numbers in java? i created regex ([-]?[\\d]*\\.[\\d]*) , tested against following expected outputs: in out works? -------------------------------------- qwerty34.34abcd 34.34 yes qwe-34.34.34abcd -34.34 no +17.-9abc 17.0 yes -.abc0 0.0 no i have out column(out). please provide regex passes of these tests. try following: ((\+|-)?([0-9]+)(\.[0-9]+)?)|((\+|-)?\.?[0-9]+) this match real numbers, including integers, or without sign (and or without number before decimal point).

android - How to center Google maps driving directions between destination and source -

i using google maps url commands draw driving directions source destination using following commands: string geouristring = "http://maps.google.com/maps?" + "saddr=" + latitude + "," + longitude + "&daddr=" + destlat+ "," + destlong; then intent mapcall = new intent(intent.action_view, uri.parse(geouristring)); startactivity(mapcall); this opens list of options, when choose google maps, shows me driving directions source destination. i have question: how can zoom map out fit drawn path source destination? (because zoomed in much, full path not shown @ once) **var mapoptions = { zoom: 4, center: new google.maps.latlng(18.49866955, 73.8957357166667), maptypeid: google.maps.maptypeid.roadmap }; var map = new google.maps.map(document.getelementbyid('map_canvas'), mapoptions);**

sql - How can I display all results? -

my table bellow consist of different colour teams of have played colour , received points . create table colours (c_id varchar2 (4) not null, hc varchar2 (4), ac varchar2 (4), total number (2), scores number (2)); insert colours values ('c1', 'red', 'blue',8,''); insert colours values ('c2', 'red', 'blue', 9,''); insert colours values ('c3','blue', 'red', 10,''); insert colours values ('c4','blue', 'red', 11,''); next have created function calculates total points teams: create or replace function total (i_hc colours.hc%type) return number v_colours_total colours.total%type; begin select sum (total) v_colours_total colours hc = i_hc; if v_colours_total null v_colours_total:=0; end if; return v_

html - Menu items break on Chrome/Safari (Mac) but not on Firefox and Chrome for Win -

i ran weird situation when building following menu . on chrome/safari (mac) last menu item breaks when add padding-left: 7px; <ul> that's way able display menu centered on firefox , chrome windows. i tried centering menu display: block; margin: 0 auto; didn't work well. think i've ran out of possible solutions. looking forward replies, cheers! this because chrome rendering fonts differently , there few pixels difference (about 4 or 5px on screen width in case). here's little trick picked while ago center nav without padding , such: .site-header .site-nav ul { display: table; margin: 0 auto; } .site-header .site-nav li { display: block; float: left; } notice there's no other margins or padding on ul apart auto left , right. you'll need clear ul clearfix because li's floated. or if don't using display:table can same display:inline-block on ul, set text-align:center on .site-nav

python - Cherrypy index dispatcher not like defined -

this first outing cherrypy forgive stupidity. i'm trying write restful api in part deals adding/removing people. want able get/put/delete example.com/people/. the dispatcher seems behaving totally differently index method vs defined function: class people: """this class cherrypy deals crud on people""" @cherrypy.expose def index(self, name): return name @cherrypy.expose def who(self, name): return name root = webroot() root.people = people() cherrypy.quickstart(root) if call example.com/people/tom, 404, if call example.com/people/who/tom 'tom' returned. can see i'm doing wrong? there way can pass /xxx index? indexes bit different when comes url arguments. the index method has special role in cherrypy: handles intermediate uri’s end in slash; example, uri /orders/items/ might map root.orders.items.index. index method can take additional keyword arguments if request includes

how to create an empty queryset and to add objects manually in django -

i need create queryset , add manually objects i've got different queries results in order display in table. uses xx=set() doesn't job. you can in 1 of following ways: from itertools import chain #compute list dynamically here: my_obj_list = list(obj1, obj2, ...) #and none_qs = mymodel.objects.none() qs = list(chain(none_qs, my_obj_list)) you do: none_qs = mymodel.objects.none() qs = none_qs | sub_qs_1 | sub_qs_2 however, not work sliced querysets

css - Border on a side of a DIV -

i want border on right hand side of div. i do: <div class="span6" style="border-right: 2px solid #727272;"> the things i'd border not run top , bottom of div. maybe 5px top , 5px bottom. or 90% of height of div. how do this? thanks you can use pseudo element hold border. following make "border" 90% of height of parent element: http://cssdeck.com/labs/kyrvt8hf div { position: relative; } div:after { display: block; content: ''; position: absolute; top: 5%; bottom: 5%; right: 0; border-right: 2px solid red; }

uiimage - Image IO memory keeps growing -

Image
i ran app in instruments vm tracker discovered growing image io memory consumption. effectively, app did quite bit of reading images disk initwithcontentsoffile: . read once method spawn of satan, replaced following: nsdata *data = [nsdata datawithcontentsoffile:path]; uiimage *image = [uiimage imagewithdata:data]; this reduced virtual memory (about 60%), shown below: but, why image io virtual memory keep growing on time, when there aren't leaks , app using 15mb of live memory? is there can make sure image io memory released? basically, image reading disk done this: dispatch_async(dispatch_get_global_queue(dispatch_queue_priority_default, 0ul), ^(void) { nsdata *data = [nsdata datawithcontentsoffile:path]; uiimage *image = [uiimage imagewithdata:data]; dispatch_async(dispatch_get_main_queue(), ^{ imageview.image = image; }); }); i tried following without significant changes: use [nsdata datawithcontentsoffile:path options:nsdatarea

sum - Many decimal places required in python calculations -

i need accurately sum long list of decimal numbers precision of @ least 50 decimal places. need able print sums. need unlimited decimal places. i have no idea how this. floating numbers supposed converted strings , printed out decimal module right? have no success in understanding module or limitations. if me problem and/or maybe hint me of instructive article decimal module or floating point numbers in python, me , others. my attempt was: from __future__ import division decimal import * getcontext().prec = 160 summan = 0 lista = [1/4,1/3,1/5,1/6,1/7,1/9,1/10,1/11] x in lista: summan += x print decimal(str(summan)) have at documentation ... fraction divisions high precision can like: from decimal import * getcontext().prec = 160 summan = 0 lista = ['1/4','1/3','1/5','1/6','1/7','1/9','1/10','1/11'] x in lista: den, num = x.split('/') print decimal(den) / decimal(num)

SELECT DISTINCT in Scala slick -

i using slick 1, , have able apply filter in query lookup entities match condition in related table. this example using slick documentation shows trying (this contrived example close situation). here, want coffees provided suppliers on west coast. want coffee only, interested in navigating suppliers apply filter: val westcoast = seq("ca", "or", "wa") val implicitinnerjoin = { c <- coffees s <- suppliers if c.supid === s.id && s.state inset westcoast } yield c this works ok, duplicate coffees if there more 1 match in suppliers table. the obvious workaround in normal sql select distinct; however, cannot find way here. you in theory a: query.list.distinct after results returned; however, have implemented paging support, wouldn't want process results once come database. here paging support: query.drop(offset).take(limit).list so, in nutshell, need way specify select distinct in query goes out. anyone have idea

php - query_posts( $args) exclude a category -

i trying exclude category shortcode shows latest posts. have searched while solution cant seem different options work. this code, (unfortunately didn't write need edit it): function blogcuts_homepage_sc($atts, $content = null) { $blogh = ''; $last = ''; $counter = 1; $args = array( 'post_type' => 'post', 'order' => 'desc', 'posts_per_page' => 4 ); query_posts( $args ); if ( have_posts() ) : while ( have_posts() ) : the_post(); if ($counter == $args['posts_per_page']) { $last = ' last-column'; } $img_array = wp_get_attachment_image_src(get_post_thumbnail_id(), 'small'); $comments = get_comments_number(); $custom = get_post_custom(); $blogh.= '<article class="blog-excerpt'.$last.'">'; $blogh.= '<h3><a class="bg-transition" href="'

java - Scanner only accepting input once -

recently, i've been working on noughts , crosses game, i've stumbled upon problem can't seem able fix. whenever type in first time, works , prints out board, however, point onward, stops checking , printing out board. while(inf){ string temp = input.next(); if(playerturn == 1){ if(amountp1 <= 3){ if(temp.equalsignorecase("00")){ if(board[0][0] == 0){ board[0][0] = 1; showboard(board); playerturn = 2; amountp1++; } else{ system.out.println("this space occupied!"); } } else if(temp.equalsignorecase("01")){ if(board[0][1] == 0){ board[0][1] = 1; showboard(board); play

Parallel computing in R (Windows): changing code from foreach %do% to foreach %dopar% -

i have written code run several time-series rolling-regressions multiple securities. since number of securities more 10,000, , having more 200 rolling windows each security, runtime sequential set-up (using foreach %do%) 30min. i implement foreach %dopar% parallel computing instead, using "doparrallel" backend. changing %do% %dopar% in code doesn't trick. new parrallel computing method, , hope help. here foreach %do% code: sec = ncol(ret.zoo) num.factors = 2 rows = nrow(ret.zoo) - 60 + 1 beta.temp = matrix(nc = num.factors + 1, nr = sec*rows) gvkey.vec = matrix(nc = 1, nr = sec*rows) d = 1 foreach(i=1:sec) %do% { df = merge(ret.zoo[,i], data) names(df) <- c("return", names(data)) gvkey = substr(colnames(ret.zoo)[i],2,9) reg = function(z) { z.df = as.data.frame(z) ret = z.df[,which(names(z.df) == "return")] ret.no.na = ret[!is.na(ret)] if(length(ret.no.na) >= 30) {

java - Float division being silly when saved in variable - but not when "used directly" -

so problem trying position sprite in middle of screen. how simple calculations made during runtime wrong. have come conclusion floating points being messy in java. so, code have right now, works: float posx = ((1280f / 2f) - 128f); float posy = ((720f / 2f) - 112.5f); splash.setscale(1.5f); splash.setposition((posx), (posy)); but if replace divisions above these variables: private float screencenterw = (1280.0f / 2f); private float screencenterh = (720.0f / 2f); private float splashcenterw = (225.0f / 2f); private float splashcenterh = (256.0f / 2f); things not seem work anymore. seems me first part of posx , posy calculations result in 0.0 , sprite ends in upper left corner, half-visible. why if replace different calculations these variables, stops working? edit: so clarify: this how want code like: private float screencenterw = (1280.0f / 2f); private float screencenterh = (720.0f / 2f); private float splashcenterw = (225.0f / 2f); private float splashcenterh

qt - Get QString length in bytes (not characters) -

i need solve problem opposite this one . have qstring non-ascii symbols. example: schöne grüße how length of string in bytes utf8 case? should 15. have tried conversion bytearray , latin1 , ascii length same. you need use ::toutf8() , append qbytearray. can length using .size(). qstring s = "schöne grüße"; qbytearray bytes = s.toutf8(); int length = bytes.size(); //number of bytes http://harmattan-dev.nokia.com/docs/platform-api-reference/xml/daily-docs/libqt4/qbytearray.html#size

hadoop - Increasing io.sort.mb -

it highly appreciated if me find out went wrong in configuration. i wanted increase value of io.sort.mb , added property below in core-site.xml. io.sort.mb 350m the runtime information attaching below shows value of io.sort.mb, did not change rather default value io.sort.mb = 100 stayed. 13/08/15 16:43:34 info mapred.task: using resourcecalculatorplugin : org.apache.hadoop.util.linuxresourcecalculatorplugin@1e5e96c1 13/08/15 16:43:34 info mapred.maptask: numreducetasks: 1 13/08/15 16:43:34 info mapred.maptask: **io.sort.mb = 100** 13/08/15 16:43:34 info mapred.maptask: data buffer = 79691776/99614720 13/08/15 16:43:34 info mapred.maptask: record buffer = 262144/327680 13/08/15 16:43:34 info mapred.maptask: starting flush of map output 13/08/15 16:43:34 info mapred.maptask: finished spill 0 13/08/15 16:43:34 info mapred.task: task:attempt_local_0001_m_004609_0 done. , in process of commiting since not working, added property in mapred-site.xml s