Posts

Showing posts from June, 2011

Combine single and multi argument variables in a function call for Python -

i wrote following function return subset of dictionary want insist on having @ least 1 key provided in input arguments. def getproperty(self,x, *key): key = [k k in key] key.insert(0,x) return {k:self.__properties[k] k in key if k in self.__properties} the code works. i know insert not necessary since dictionary elements aren't ordered. wish rid of first for-loop creates list extracting elements multi-argument tuple. something like key = [x] + [key] but not work. this should need: def getproperty(self,x, *key): key = (x,)+key return {k:self.__properties[k] k in key if k in self.__properties}

Unable to setup a user adminstrator account in mongodb running on fedora -

i have setup mongodb downloading 64 bit legacy linux download on official mongodb website.i started mongod service, , installed mean stack following instructions on meanjs.org website. started server , default boilerplate of meanjs showed up. trying setup user adminstrator mongodb server. there no admin database default, tried following: use admin db.createuser({ user:”siteuseradmin”, pwd: “useradminpwd” roles: [{role: “useradminanydatabase”,db: “admin”}] }) i getting following error:e query syntaxerror: unexpected token illegal there mean-dev database following collections: sessions, system.indexes, users tried creating user adminstrator account in database , got same error.i need guidance setup user adminstrator account. you might want check mongod.conf , set auth=true after that, restart mongod . now need use mongo shell on server mongod running on. your statements correct, completeness: use admin db.createuser( { user: "siteuseradmin&quo

php - Pattern to abstract serialization\deserialization details from data classes -

in current php project have number of classes pure data-classes, similar called poco in c# world (i omit getters\setters now): class myentity { public $id; public $name; } i need serialize\deserialize such entities in different formats (for example, to/from json , xml) , keep serialization detailes out of classes itself. for deserialization builder pattern seems choice, i'm not sure serialization. suppose i'm missing obvious here. sounds strategy pattern me. define common interface , implement various serialization strategies. invoke based on context.

concurrency - omp parallel doesn't give any performance increase for matrix multiplication -

i'm using following 2 code blocks compute matrix multiplication serially , parallel. serial - double** ary1 = new double*[in]; double** ary2 = new double*[in]; double** result = new double*[in]; (int i=0;i<in;i++){ (int j=0;j<in;j++){ result[i][j] = 0; for(int k = 0;k<in; k++){ result[i][j] += ary1[i][k]*ary2[k][j]; } } } parallel - double** ary1 = new double*[in]; double** ary2 = new double*[in]; double** resultsp = new double*[in]; #pragma omp parallel for(int i=0;i<size;i++){ int raw = i/in; int column = i%in; double sum =0; for(int k = 0; k < in; k++){ resultsp[raw][column] += ary1[raw][k]*ary2[k][column]; } resultsp[raw][column] = sum; } i ran both in quad-core computer, same results. why don't performance increased running parrellely? accessing ary1, ary2, resultsp shared arrays inside parellel loop cause them run serially? this has happened since '-fopenmp' flag

angularjs - Using $cookies in controller generates TypeError: undefined is not a function -

update: issue resolved turns out not aware ngcookies separate service not part of standard angular.js. bower.json file referencing angular 1.4beta angular-cookies still loading 1.3. changed 1.4beta , working expected. i using $cookies in controller in angular 1.4 project getting following error when reference $cookies: typeerror: undefined not function @ object.<anonymous> (http://localhost:9000/bower_components/angular-cookies/angular-cookies.js:60:16) @ object.invoke (http://localhost:9000/bower_components/angular/angular.js:4371:17) @ object.enforcedreturnvalue [as $get] (http://localhost:9000/bower_components/angular/angular.js:4224:37) @ object.invoke (http://localhost:9000/bower_components/angular/angular.js:4371:17) @ http://localhost:9000/bower_components/angular/angular.js:4189:37 @ getservice (http://localhost:9000/bower_components/angular/angular.js:4330:39) @ invoke (http://localhost:9000/bower_components/angular/angular.js:4362:1

JSP hot/auto deploy not working in JBoss ES 6.2 w/ Liferay 6.2 -

i working on project using liferay 6.2 on jboss es 6.2 (jboss 7.x, have read). using liferay created ant scripts deploys, strange reason jsp file changes not picked up. everytime make change jsp have shut down jboss, nuke files under standalone/tmp, restart jboss. java changes seem deploy fine. instance, if add log message portlet code , update html text in jsp , deploy portlet project, see log entry page text change not there. needless say, having restart whole app server every ui change/tweak diminishing productivity. i don't know information needed help. check if have timezone issues when deploy project:: if timestamps on jsps 1 hour old (because of bad timezone) , previous deployment/test 10 minutes ago, jsp might have been compiled 10 minutes ago - that's still 50 min after (updated) jsp's date, no need recompile. i hope timezone-explanation wasn't messy , understandable.

java - Spring request scope in HttpRequestHandlerServlet does not work -

i can't understand why configuration not work. i make spring web applcation without mvc , use httprequesthandlerservlet class. need beans use 1 connection in 1 request. , set request scope in connection bean when run it: illegalstateexception: no thread-bound request found: referring request attributes outside of actual web request, or processing request outside of receiving thread? if operating within web request , still receive message, code running outside of dispatcherservlet/dispatcherportlet: in case, use requestcontextlistener or requestcontextfilter expose current request. my web.app is: <web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"> <listener> <listener-class> org.springframework.web.context.contextloade

C# winforms cast childform as of it's own type -

i have mdi project. i'm using form activeform = this.activemdichild; however, instead of form , i'm like: forms.lookup.grade activeform = (forms.lookup.grade) this.activemdichild; forms.lookup.product activeform = (forms.lookup.product) this.activemdichild; ...etc so if forms.lookup.grade active want return activeform forms.lookup.grade how can cast active form of it's own type in generic way instead of using switch this.activemdichild.name ? thank mansi you can check type @ runtime: form activeform = this.activemdichild; if(activeform forms.lookup.grade) { forms.lookup.grade gradeform = activeform forms.lookup.grade; gradeform.somemethodofgrade(); .... }

android - SpannableString not working when using AppCompat theme -

Image
i'm unable spannablestring work when set apptheme theme.appcompat.light.darkactionbar. i have button , text set spannablestring. when use holo theme text renders expected, when switch appcompat theme span effects seam ignored. how can spannablestring work using appcompat theme? styles.xml - when switching between 2 themes different results... <resources> <style name="apptheme" parent="theme.appcompat.light.darkactionbar" /> <!--<style name="apptheme" parent="@android:style/theme.holo.light" />--> </resources> ... button uses spannablestring public static class placeholderfragment extends fragment { public placeholderfragment() { } @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view rootview = inflater.inflate(r.layout.fragment_main, container, false); button button =

c - Function to return a pointer to the largest number in an array -

as can tell title need write function returns pointer largest number in array, functions gets pointer double array , it's size. in addition need write main function use function. here code wrote: #include <stdio.h> #include <stdlib.h> void bigel(double* arr, double arrsize); void bigel(double* arr, double arrsize) { int i; double maximum, *x; maximum = arr[0]; (i = 1; < arrsize; i++) { if (arr[i]>maximum) { maximum = arr[i]; } } *x = maximum; } void main() { double myarr[10]; int i; printf("please insert 10 numbers array\n"); (i = 0; < 10; i++) { scanf("%d", &myarr[i]); } bigel(myarr, 10); } i error: error 1 error c4700: uninitialized local variable 'x' used i don't understand did wrong because did initialized x. kind of appreciated, in addition, tell me if idea of code right because im not sure if understo

java - spring 4 mvc app - application level exception handler -

i moving spring web app spring 3.2 4.1. in 3.2, following exception handler works catching exceptions entire applicaton. @controlleradvice public class restexceptionprocessor { @org.springframework.web.bind.annotation.exceptionhandler(appexception.class) @responsebody public errorinfo handleappexception(appexception ex, httpservletresponse response) { errorinfo ret = new errorinfo(ex.getmessage(), new date(), ex.getextras()); logger.error(ex.getmessage()); response.setstatus(ex.getcode().getstatuscode()); return ret; } } however when move 4.1, following exception stack trace: error failed invoke @exceptionhandler method: public com.momoe.handler.restexceptionprocessor$errorinfo com.momoe.handler.restexceptionprocessor.handleappexception(com.momoe.commons.appexception,javax.servlet.http.httpservletresponse) org.springframework.web.httpmediatypenotacceptableexception: not find acceptable representation @ org.springframework

How can I make a rectangle be on top of all other rectangles in javascript canvas? -

i have rectangle includes menu. need rectangle on top of other objects in game. bear in mind, no css, javascript canvas programming. how can that? if need code rectangle: ctx.fillrect(0,0,width,100); that need know guess. the canvas has no in-built layering. have multiple options: add second canvas html document, , use css positioning place above other canvas object. draw rectangle on upper canvas , other content on lower canvas. transparent pixels on upper canvas show content of canvas below. redraw rectangle after other drawing operation. use drawing loop erase , redraw whole scene window.requestanimationframe (any sufficiently complex game ends there anyway sooner or later). draw objects in order want them overlap, means draw said rectangle last.

c++ - Swapping `std::aligned_storage` instances containing non-trivially-copyable types - undefined behavior? -

ideone link #include <iostream> #include <type_traits> using namespace std; // non-trivially-copyable type. struct ntc { int x; ntc(int mx) : x(mx) { } ~ntc() { cout << "boop." << x << endl; } }; int main() { using = aligned_storage_t<sizeof(ntc), alignof(ntc)>; // create 2 `std::aligned_storage` instances // , "fill" them 2 "placement-new-constructed" // `ntc` instances. as1, as2; new (&as1) ntc{2}; new (&as2) ntc{5}; // swap `aligned_storages`, not contents. std::swap(as1, as2); // explicitly call `~ntc()` on contents of // aligned storage instances. ntc& in1{*static_cast<ntc*>(static_cast<void*>(&as1))}; ntc& in2{*static_cast<ntc*>(static_cast<void*>(&as2))}; in1.~ntc(); in2.~ntc(); return 0; } is above code undefined behavior? here's think that&

sql - How to select certain numbers of groups in MySQL? -

Image
i have table data: , table need create pegination productid column. know limit n,m, works rows , not groups. examle table pegination = 2 expect retrieve 9 records productid = 1 , 2 (the number of groups 2). so how create pegination numbers of groups ? i thankfull answers example. one way pagination groups assign product sequence query. using variables, requires subquery: select t.* (select t.*, (@rn := if(@p = productid, @rn + 1, if(@rn := productid, 1, 1) ) ) rn table t cross join (select @rn := 0, @p := -1) vars order t.productid ) t rn between x , y; with index on t(productid) , can subquery. condition can go in having clause: select t.*, (select count(distinct productid) t t2 t2.productid <= t.productid) ) pno t having pno between x , y;

java - Does superclass constructor exist (but not inherited) in subclass? -

we able invoke super() subclass constructor. since subclass is-a superclass , , there 1 object created ( new subclass()) imply superclass constructor exists, although cannot inherited, in subclass? constructors not inherited . superclass constructor 'exists' in way call subclass unless it's marked private . and i.k. has mentioned class have default constructor : if class contains no constructor declarations, default constructor no formal parameters , no throws clause implicitly declared.

c# - StopWatch to Show Counter of Elapsed Time? -

i have textbox on windows form wanting show elapsed time procedure has taken, not seeing time counting in textbox. below code public partial class form1 : system.windows.forms.form { private stopwatch watch = new stopwatch()l private void btn_rashadsl() { watch.start(); //lots of code here typically takes around 15 - 20 minutes complete } private void timer_tick(object sender, eventargs e) { textbox1.text = watch.elapsed.seconds.tostring(); } } given code have posted i'd problem @ no point have set timer call timer_tick method.

Serving static html files to a meteor template using Iron Router -

i've set meteor website , loving how easy build templates data in mongo db. one part of website want render static html file in layout template i've setup. @ moment have layout file looks this <template name="mainlayout"> {{> yield region="navbar"}} {{> yield}} {{> yield region="footer"}} </template> all want when hit specific route instead of finding template , filling data db want insert static html page main part of layout. is possible or have suggestions on other ways solve this? i can't think of way standardise have in these html files fit 1 template easier serve them static pages.

ios - UITableViewCell right detailTextLabel frame resizes after reloadData -

i have uitableview 1 right detail cell , scrolling disabled , height of table set 44 (same cell). cell displays data representing object of class a. when user taps cell, pushes new vc table pick new object of class a. when pop old vc , call reloaddata in viewwillappear , detailtextlabel.frame changed , not visible. so in log, first line initial call cellforrowatindexpath (object 1), , displays correctly. second line after selecting object 2 (empty string detailtextlabel ). third line after selecting object 1 again, , detailtextlabel working before, invisible. 2015-03-28 10:48:11.747 dojo[32523:5852510] detail text label: <uitableviewlabel: 0x15d5de470; frame = (463 12; 42 20); text = '1234'; opaque = no; autoresize = rm+bm; layer = <_uilabellayer: 0x17429a810>> 2015-03-28 10:48:20.374 dojo[32523:5852510] detail text label: <uitableviewlabel: 0x15d5de470; frame = (468.5 13; 36.5 19.5); text = ''; autoresize = rm+bm; layer = <_uilabellayer: 0

CSS Issue on Mobile Site -

i have site working on @ http://wpmend.com . site looks ok on desktop on mobile well, think custom css has messed up. you'll see text , button on homepage section don't right, , in request job section, buttons first 2 job types don't show @ all. i have searched site , found similar issues , fixes none have addressed exact problem. please advise on how can fix on mobile site. way, it's wordpress site using rapid theme. thanks in advance! scott. maybe you're working media query css3. add code css page, #container object wraps button @ top. @media screen , (max-device-width:480px){ #container: margin-top:15px; } this implement css code when device width smaller 480px. it'll move container below header down little bit. note: not mobile devices smaller 480px, you'll have implement multiple media queries specific devices. refer to: https://css-tricks.com/snippets/css/media-queries-for-standard-devices/

java - Is there a way to replicate an IDE's console like Eclipse, or NetBean's on a website? -

i've created website portfolio , want show of projects i've done. far many of projects i've done have been in java, or c/c++ , interactive/fun programs take input console. i wondering if there way simulate program using javaserver faces , taking input textbox (possibly) used in java program i've created , posted website. just give idea of kinds of programs i'd show. range simple things determining if entered data user leap year text i/o credit card validation program i've made up. if question clear enough, have ideas how can show programs i've created? i thought of creating java class writes output data java file in string , posts webpage, user have refresh page. thought if somehow simulate console on website take care of problem. extra: there easy way display javafx programs on website? thank in advance!

python - Convert PDF with columns to text -

in unix or windows, want convert dictionary python dictionary . copied contents of pdf dictionary , put them in .rtf file, intending read them python. however, gives like: a /e/ noun human blood type of abo system, containing antigen (note: some- 1 type can donate people of same group or of ab group, , can receive blood people type or type o.) aa abdominal distension /􏰄b􏰁dɒmn(ə)l ds 􏰂tenʃ(ə)n/ noun condition in abdo- men stretched because of gas or fluid a abdominal distension aa abbr alcoholics anonymous it has squashed columns pdf strange mismash. how convert pdf text columns respected? in other words, desired output is: a /e/ noun human blood type of abo system, containing antigen (note: some- 1 type can donate people of same group or of ab group, , can receive blood people type or type o.) aa abbr alcoholics anonymous ...and on you have 2 options text: direct text extraction each page as-is. split each page 2 alo

jquery - Is this a CSS bug or am i completely blind? -

Image
during build of project making page edit user credentials. now, when added css in stylesheet(as did html) refused work! not border, not margins not anything! this html. <div id="editdetails" class="textfont userpagewindows"> <p style="font-size:50px;">edit credentials</p> 5125125125125<br /><br /><br /><br /><br /><br /><br /> 5125125125125 </div> css div.userpagewindows{ min-width:80%; margin-top:190px; border: solid; border-top:none; border-bottom:5px; } the border messed up. doing wrong? i've done tens of times in project far, , worked perfect! this how border looks in div: as opposed picture, how should http://jsfiddle.net/qepybz9l/ this seems work desired? fiddle . function showwindow(el) { $("#userpagemain").fadeout(150); $(el).fadein(150); } concerning css issue, there's lot note. you want displa

wxpython - Display image in wx.GridBagSizer -

i trying display image on wx.gridbagsizer the image being read , can see if comment out sizermain.add lines, not show in sizer. interestingly space reserved in sizer. can please help? import wx class mainwindow(wx.frame): def __init__(self,parent,id,title): wx.frame.__init__(self,parent, wx.id_any, title, size = (1200,600), style=wx.default_frame_style|wx.no_full_repaint_on_resize) sizermain = wx.gridbagsizer(3, 2) self.sizermain = sizermain pnl = wx.panel(self) cmd1 = wx.button(pnl, label='aaaaa') cmd2 = wx.button(pnl, label='bbbbbb') cmd3 = wx.button(pnl, label='ccccc') cmd4 = wx.button(pnl, label='dddd') imgsizer = wx.boxsizer(wx.horizontal) image = wx.bitmap('test.png',wx.bitmap_type_png) img = wx.staticbitmap(self, -1, image) imgsizer.add(img, flag=wx.left, border=10) sizermain.add(imgsizer, pos=(0,0), span=(1, 3), flag=wx.top|wx.lef

python - Best practise to apply several rules on 1 string -

i'm getting url string , need apply several rules it. first rule remove anchors, remove '../' notation, because urljoin joins url incorrect in cases, , remove leading slash. have such code: def construct_url(parent_url, child_url): url = urljoin(parent_url, child_url) url = url.split('#')[0] url = url.replace('../', '') url = url.rstrip('/') return url but dont think best practise. think can done simpler. me please? thanks. unfortunately, there isn't make function simpler here, since you're dealing pretty odd cases. but can make more robust using python's urlparse.urlsplit() split url in well-defined components, processing, , put using urlparse.urlunsplit() : from urlparse import urljoin urlparse import urlsplit urlparse import urlunsplit def construct_url(parent_url, child_url): url = urljoin(parent_url, child_url) scheme, netloc, path, query, fragment = url

sql - Full Text Search For Excel Files -

Image
i have several 100 excel files not normalized enough me efficiently import tables of database. difficult find information have seen possible index xlsx files fts. not looking implement alternate database 1 time thing not receive new data. would possible fts , if point me in right direction info i've found on msdn quite vague. thanks. fts feature in sql server, data want create fts needs in sql server database. excel being in excel , not in sql server , not able create fts them excel sheets. but if import data sql server able make use of fts features, till unfortunately fts not option you.

Android Maps to find nearby pharmacy -

i have created below code find nearby pharmacies.i know if changes required in code.it's throwing errors. package com.example.maps; import android.content.intent; import android.net.uri; public class mapactivity { intent mapintent=new intent(android.content.intent.action_view, uri.parse("http://maps.google.co.uk/maps?q=pharmacy&hl=en")); startactivity(mapintent); } google released places api in latest play services: read here . you can of course use in conjunction location services, idea of parsing results of maps query doesn't make lot of sense more.

matlab - Polyxpoly returns empty matrix -

Image
i'm writing code in have use polyxpoly , i'm having issues output. my code: x=[-286.1018 -363.2334]; y=[4617.4 4725.1]; xv=[-316.7 -128-9 -268.3 -1864.6 -840.4]; yv=[4694.4 4944.7 5641.7 6002.0 4519.9]; [xi,yi] = polyxpoly(x,y,xv,yv); and returns: empty matrix: 0-by-2 what doing wrong can't understand why not working (it should return intersection points)? can me? bug of function polyxpoly? you're getting empty matrix because polylines defined (x,y) , (xv,yv) don't intersect. can shown plotting polylines: x=[-286.1018 -363.2334]; y=[4617.4 4725.1]; xv=[-316.7 -128-9 -268.3 -1864.6 -840.4]; yv=[4694.4 4944.7 5641.7 6002.0 4519.9]; mapshow(xv, yv); mapshow(x,y,'color','red') we get: as can see, bigger shape defined xv , yv not closed, smaller line defined x , y never intersect shape. if want find intersection points, you'll need close larger polygon. can done duplicating first xv , yv point in array , mak

python - finding longest path in a graph -

i trying solve program, in have find max number of cities connected given list of routes. for eg: if given route [['1', '2'], ['2', '4'], ['1', '11'], ['4', '11']] max cities connected 4 constraint can't visit city have visited. i need ideas, in how progress. for now, have thought if able create dictionary cities key , how many other cities connected value, somewhere near solution(i hope). eg: dictionary {'1': ['2', '11'], '4': ['11'], '2': ['4']} above given input. want proceed further , guidance if missing anything. you can use defaultdict create "graph" list of edges/paths: edges = [['1', '2'], ['2', '4'], ['1', '11'], ['4', '11']] g = defaultdict(list) (s,t) in edges: g[s].append(t) g[t].append(s) print g.items() output: [ ('1',

print properties and values of an object at the same time-Javascript -

assuming have following javascript object var t={name:"john",age:34,zip:"82900"} if use following code print properties of object: for(var x in t){ console.log(t[x]); } i john, 34, 82900.now question how to print each propertie's name example print age,34 name,john object might have more properties wrote above since user can add own properties inside object var t = { name : "john", age : 34, zip : "82900" }; for(var x in t){ console.log(x, t[x]); }

ubuntu - PostgreSQL default cluster? -

i running postgresql 9.3 on ubuntu 14.04 lts. didn't remember creating cluster directly went create database. using pg_lsclusters , found have cluster following db ver cluster port status owner data directory 9.3 main 5432 online postgres /var/lib/postgresql/9.3/main i reading postgresql documentation couldn't find relevant info. i have following questions: does postgresql automatically create default cluster? , if so, practice use it? does postgresql automatically start default cluster? never started status online , can see in system-monitor. thanks clarifications! you're asking "postgresql on debian or ubuntu", it's packaging , wrapper utilities doing this, not postgresql self. see the postgresql on ubuntu community wiki information. applies debian too, since uses same style of packaging postgresql. to specific questions: does postgresql automatically create default cluster? , if so, practice us

ruby on rails - configure: error: clang version 3.0 or later is required and I already have it -

i'm trying follow this rvm installation guide , supposedly snow leopard 10.6.8 (i should point out $ rvm -v returns -bash: rvm: command not found ), when run $ curl -l https://get.rvm.io | bash -s stable --auto-dotfiles --autolibs=enable --rails ends in this error running './configure --prefix=/users/mac/.rvm/rubies/ruby-2.2.0 --with-opt-dir=/usr/local/opt/libyaml:/usr/local/opt/readline:/usr/local/opt/libksba:/usr/local/opt/openssl --disable-install-doc --enable-shared', showing last 15 lines of /users/mac/.rvm/log/1427567557_ruby-2.2.0/configure.log [2015-03-28 15:33:08] ./configure current path: /users/mac/.rvm/src/ruby-2.2.0 path=/usr/local/opt/pkg-config/bin:/usr/local/opt/libtool/bin:/usr/local/opt/automake/bin:/usr/local/opt/autoconf/bin:/usr/local/bin:/usr/local/bin:/opt/local/bin:/opt/local/sbin:/library/frameworks/python.framework/versions/2.7/bin:/usr/bin/python:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/x11/bin:/usr/local/git/bin:/usr/x11/bin:/use

one to one - Hibernate One-To-One mapping error with reference key was null -

i have 2 class customer , passport 1-1 relationship. want passport table store it's owner id (customer_id). after save database customer_id alway null, wrong configure. customer class @entity public class customer { private int id; private string name; private passport passport; @id @generatedvalue(strategy = generationtype.identity) public int getid() { return id; } @onetoone(cascade = cascadetype.all, mappedby="customer") public passport getpassport() { return this.passport; } } passport class @entity public class passport { private int id; private string name; private customer customer; @id @generatedvalue(strategy=generationtype.identity) public int getid() { return id; } @onetoone @joincolumn(name="customer_fk") public customer getcustomer() { return customer; } } unit test class public class customertest extends basetes

Stretched plots in R when plotting multiple figures to PDF -

i'm trying create pdf multiple plots in pdf, when create pdf 2 x 2 plots plots square , looks nice: pdf(file=paste0("test.pdf"), paper = "a4") par(mfrow=(c(2,2)), omi=c(0,0,0,0), mar=c(2, 2, 0, 0)) (i in 1:4) { plot(1:10) } dev.off() however if try generate pdf 3 rows , 2 columns plots not square. plots seems stretched entire 3 x 2 matrix of plots squared: pdf(file=paste0("test 2.pdf"), paper = "a4") par(mfrow=(c(3,2)), omi=c(0,0,0,0), mar=c(2, 2, 0, 0)) (i in 1:6) { plot(1:10) } dev.off() how individual plots square in configuration number of rows , columns not equal? thanks in advance. apparantly can use layout instead pdf(file=paste0("test 2.pdf"), paper = "a4") layout(matrix(1:6, 3, 2, byrow = true), respect = true) par(omi=c(0,0,0,0), mar=c(2, 2, 0, 0)) (i in 1:6) { plot(1:10) } dev.off()

javascript - Setting methods through prototype object or in constructor, difference? -

this question has answer here: use of 'prototype' vs. 'this' in javascript? 13 answers could explain difference between setting methods in constructor , through prototype object? following code shows these 2 ways of setting methods - say_hello , say_bye both work fine: function messageclass() { this.say_bye = function() { alert('see ya'); }; } messageclass.prototype.say_hello = function() { alert('hello'); }; x = new messageclass(); x.say_hello(); x.say_bye(); foxxtrot , annakata both correct, i'll throw in 2 cents. if use prototype each instance of "messageclass" referencing same functions. functions exist in memory once , used instances. if declare methods in constructor (or otherwise add specific instance) rather prototype new function created each instance of messageclass. that being said, there

python - Limiting print output -

i have number of objects need print out terminal (for debugging). normal print function perfect, except objects large, print create millions of lines of output. i'd create function print does, except output truncated after predefined number of characters, replacing rest ... . what's way that? note performance concern, ideally i'd prefer not save gigabyte-sized string , take first few characters it; similarly, pprint bit of problem since sorts keys in dictionaries (and millions of keys takes while). example: obj = [ [1, 2, 3], list(range(1000000)) ] my_print(obj, 20) # should output: # [[1, 2, 3], [0, 1, 2... python 3, if matters. the reprlib module (python 3.x only) suggested @m0nhawk made purpose. here's how use it: if you're fine default limits , can use reprlib.repr(obj) : import reprlib obj = [[1, 2, 3], list(range(10000))] print(reprlib.repr(obj)) output: [[1, 2, 3], [0, 1, 2, 3, 4, 5, ...]] in order customize available

MySQL condition (display username if exist row in phonebook) -

i have phonebook table contains user contacts number , name . have messages table ( text , number , date etc.) i need contact name phonebook if there exists record or number messages table. i tried this: select owner, sender, left(text, 28) text, date, status, if((select name phonebook number = sender), name, sender) messages order id desc limit 30 but not work. ( 1054 - unknown column 'name' in 'field list' ) sorry bad english. you left join . if there no phonebook record name null , coalesce returns second argument, i.e. sender . select owner, sender, left(text, 28) text, date, status, coalesce(name, sender) messages left join phonebook on number = sender order id desc limit 30

audio - Steganography in image -

so far, have opened image in hex editor , looked @ bytes. however, life of me cannot identify sound. have spent days on this. tried opening file (as 'raw data') in audacity , playing it. nothing 'noise'. tried create histogram/frequency analysis nothing. any appreciated. steganography works hiding second image or data in lower bits of image. these values becomes insignificant over-all , have little impact on visual of image. to reveal second data, mask off top bits, scale remaining values. however, need know in advance: how many of lower bits used (two common secondary images) how remaining data organized (if not image): is (bit) scaled, how much what order (scan-lines horizontally, vertically...). are color components in use? 1 , how data split on components... is audio file or audio data is resulting data compressed, encrypted, ... audio requires signed values, values signed in data, shifted... (this steals 1 bit means bytes must packed

php - Else break deletes variable -

i going through series of values checking if same or different, want how many values @ top of list same. $counter=0; while ($value<$numberofvalues){ if($valuea == $valueb){ $counter++; }else{ break; } } echo $counter; why $counter equals 0 after break? thanks in advance! because value , numberofvalues should have $ in front of them ( $value , $numberofvalues ), otherwise while() loop not run @ , $counter still 0 .

java - Retrofit call inside AsyncTask -

i've started developing android app , decided use retrofit client of rest service, not sure if approach good: i. i've implemented asynchronous call api, called inside asynctask's doinbackground method. concern : having read this article got me confused. aren't asynctasks suitable kind of tasks? should make call api directly activity? understand retrofit's callback methods executed on ui thread, how call on http? retrofit create threads that? ii. want authenticationresponse saved inside sharedpreferences object, doesn't seem available inside success method of callback. suggestions/ practices? thank in advance :) here's doinbackgroundmethod: @override protected string doinbackground(string... params) { log.d(location_login_task_tag, params[0]); locationapi.getinstance().auth(new authenticationrequest(params[0]), new callback<authenticationresponse>() { @override public void success(authenti

Share variable between methods in Java -

i'm new in java , have little problem. want make array in 1 method , display in length in other. know how to both in 1 method: class test { public void create() { scanner in = new scanner(system.in); system.out.println("number of elements: "); int n=in.nextint(); int arr[]=new int[n]; system.out.println("number of elements: " + arr.length); } } but how can this? class test { public void create() { scanner in = new scanner(system.in); system.out.println("number of elements: "); int n=in.nextint(); int arr[]=new int[n]; } public void display() { system.out.println("wielkosc tablicy: " + arr.length); } } make arr private instance variable of class, accessible method: class test { private int[] arr; public void create() { scanner in = new scanner(system.in); system.out.println("

mongodb - Two identical $regex declarations behave differently in Mongo shell -

according $regex documentation , following $regex declarations identical: { <field>: { $regex: /pattern/, $options: '<options>' } } { <field>: { $regex: 'pattern', $options: '<options>' } } { <field>: { $regex: /pattern/<options> } } i playing around zips.json dataset in mongo shell, , tried find cities begin , end same character. however, query returned different results depending on whether used 'pattern' or /pattern/ . $ mongo mongodb shell version: 3.0.1 connecting to: test > db.version() 3.0.1 > db.zips.find( { city: { $regex: '^(.).*\1$' } }, { city: true } ).count() 0 > db.zips.find( { city: { $regex: /^(.).*\1$/ } }, { city: true } ).count() 1418 is there difference in behavior despite documentation says? latter being javascript regex perhaps? silly me. in first declaration, should have escaped backslash this: db.zips.find( { city: { $regex: '^(.).*\\1$' } }, {

Android layouts - images for the different screen resolutions and the same density -

i want show images on background image. background image contains empty squares, , want show apple image must appear in 1 of squares. have problems apple sizes, background scales , fits screen, apple image stays same different resolution , same density devices. say have 2 ldpi devices 240x320 , 480x800 resolutions. when keep drawable aple file in drawable-ldpi folder, , use wrap_content height , width (or fixed dp values) 2 devices draw apple same size, described in documentation. the linearlayout works slow when stack them. using relaytivelayout must programmatically resize images "not good" solution guess. i've found solution here https://github.com/intuit/sdp maps dp-s. they set dimen-s values-sw300dp be <dimen name="_10sdp">10.00dp</dimen> and values-sw480dp be <dimen name="_10sdp">16.00dp</dimen> and on different cases ... so when set of apple _10sdp means different dp-s 2 devices same density , solv

Swift Compiler error while referencing existing variable -

this question has answer here: swift: expected declaration error setting “label” string variable 1 answer i trying manually create placeholder text uitextview, , when try set placeholder text, swift compiler error. xcode telling me expected declaration pincontent first try set it's text value. here's code: class firstviewcontroller: uiviewcontroller { @iboutlet var pintitle: uitextfield! @iboutlet var pincontent: uitextview! @ibaction func createpin(sender: anyobject) { } override func viewdidload() { super.viewdidload() // additional setup after loading view, typically nib. println(userlocation) } // manually create placeholder text view pincontent.text = "description" // line error pincontent.textcolor = uicolor.lightgraycolor() // change text properties of text view when user begins editing, types in normal black font fun

sql - C++ bad memory alloc exception -

here gist of trying do. store files in sql table. table large 400 records each record stores file archive , size approximately 100mb each. recently, had change our encryption key.so writing threaded ( 5 threads ) code decrypt using legacy key , encrypt using new key.this each thread does struct datatoreencrypt { int id; string data; } vector<datatoreencrypt> results; // database open select id,filedata files id between 1 , 80 // 81-160 , on. // database connection close // database connection open for(int i=0;i<results.size();i++ ) // results contain result of above query. { string decrypted = legacydecryption(results[i].filedata); string encrypted = newencryption(decrypted); update files set filedata = encrypted id = results[i].id; } // database connection close the problem when trying this,i c++ bad_memory alloc exception , sql memory alloc exception. while reading through bad_memory alloc exception read c++ throws when compiler cannot alloc

jquery - Set selected item in dropdown-menu -

i need set selected item of dropdown-menu in jquery can't make work. my dropdown code looks follows: <button type="button" id="aktiv" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false"> aktiv <span class="caret"></span> </button> <ul class="dropdown-menu" role="menu"> <li><a href="#">aktiv</a></li> <li><a href="#">inaktiv</a></li> </ul> the following function can used set text of menu. sets value of button element can retrieve using $('#aktiv').val() . function setaktivmenu(text) { $('#aktiv').val(text).html(function(i, html) { return text + html.slice(html.indexof(' <')); }); } you can call function set menu text this: setaktivmenu('inaktiv'); you can set event handler menu options cause

Not included assets in rails app -

my application.js (in app/assets/) looks like: //= require jquery //= require jquery_ujs //= require_tree . the problem generated html contains (not tree): <script src="/assets/application.js?body=1" type="text/javascript"></script> what expected e.g. jquery.js, etc. this problem occurs on mac os x development machine. (tested on opensuse - unix machine , works). what have tried: replace gemfile.lock (now identical unix machine except json ~> 1.8.2 instead of 1.8.0) , reinstall gems: gem uninstall --all bundle install change ruby version (tested 1.9, 2.1, 2.2) googling around wrong sprockets (without success) elaborating rake assets:precompile --track ** invoke assets:precompile:all (first_time) ** execute assets:precompile:all ** invoke assets:precompile:primary (first_time) ** invoke assets:environment (first_time) ** execute assets:environment ** invoke environment (first_time) *

javascript - How can I go to anchor and open a Bootstrap accordion at the same time? -

i'm using bootstrap accordion , works charm, no problem @ all. however, i'd have link 1 of tabs in accordion. idea once click on link, i'm taken part of teh page (the accordion down in page) , open tab. so used following: <a href="#prizes" data-toggle="collapse" data-parent="#accordion"><i class="mdi-action-info"></i></a> which should work. , in part: opens accordion tab right, however, page doesn't scroll anchor should. stays in same position, opening accordion. any idea how fix it? have found answers related jquery ui accordion nothing bs accordion (and jquery ui answers didn't work either), don't know why isn't working you can manually so: <a href="#accordion" id="my-link" class="btn btn-primary">open group 2</a> js $('#my-link').click(function(e) { $('#collapseone').collapse('hide'); $('#

C# Cannot implicitly convert type 'string' to 'char' PasswordChar -

i making application required simple 10 digit password into. c#. anyways, using "passwordchar" method create password, errored saying "cannot implicitly convert type 'string' 'char'". main lines of code where: public form1() { initializecomponent(); textbox1.passwordchar="1234567890"; textbox1.maxlength = 10; } can provide fix? in advance. passwordchar property want each character displayed as. e.g. if user types abc123 , textbox1.passwordchar = '*' displayed user ****** . if set textbox1.passwordchar = '$' displayed user $$$$$$ passwordchar takes char (a single character) not string which made of array of cahracters. in case want accessing textbox1.text property , set password user typed in.

python - When do you use iterators and when generators? -

i read question , answers differences between iterators , generators. don't understand when should choose 1 on other? know examples (simple, real life ones) when 1 better other? thank you. iterators provide efficient ways of iterating on existing data structure. generators provide efficient ways of generating elements of sequence on fly. iterator example python's file readers can used iterators. might use process 1 line of file: with open('file.txt', 'rb') fh: lines = fh.readlines() # reads entire file lines, line in lines: process(line) # done on each line you can implement more efficiently using iterators with open('file.txt', 'rb') fh: line in fh: # read as needed, each time process(line) the advantage in fact in second example, you're not reading entire file memory, iterating on list of lines. instead, reader ( bufferedreader in python3) reading line @ time, every