Posts

Showing posts from January, 2014

javascript - Calling a method from inside a view without using "this" keyword? -

my backbone code seems have crazy number of this.methodcall() type of invocations , i'd love able drop this , , call methodcall() directly inside view. see below code: app.main = backbone.view.extend({ el: '#main-div', // how call function without invoking "this"? setpagecookies: function () { console.log('setting page cookies called!'); }, initialize: function () { // saw online possible solution, seems affect scope of "this" _.bindall(this, 'setpagecookies'); // works: this.setpagecookies(); // however, i'd able call instead: setpagecookies(); } }); firstly - this.setpagecookies() , setpagecookies() have drastically different meanings. the way achieve calling setpagecookies() without this make setpagecookies function declaration: function setpagecookies() { } backbone.view.extend({ setpagecookies: setpagecookies,

Get all nested arrays from ElasticSearch document and sort it -

i have mapping similar this: jsonexample this represents changelog structure. each document represents object properties. these properties can changed @ dates. limit space, keeps track of changes instead of updating whole object 1 updated field example. the goal query object based on given date. result should object properties on given date. later changes should discarded , changes matching or recent given date should returned. so nested query can retrieve whole object. want nested properties returned , sorted closest given date can find properties @ given date. is there way elasticsearch queries/filters , without parsing returned json , sort afterwards example java.

amazon web services - Spot Instances Support DCOS -

is possible change dcos template use spot instances? have looked around , there not seem information regarding this. okay, given dcos template , launchconfiguration slaves looks this: (i've shortened somewhat) "masterlaunchconfig": { "type": "aws::autoscaling::launchconfiguration", "properties": { "iaminstanceprofile": { "ref": "masterinstanceprofile" }, "securitygroups": [ ... ], "imageid": { ... }, "instancetype": { ... }, "keyname": { "ref": "keyname" }, "userdata": { ... } } } to started, need add spotprice property in there. value of spotprice is, obviously, maximum price want pay. you'll need more work around autoscaling, alarms , time of day. here's new launchconfiguration spot price of $1.00 per hour: "masterlaunchconfig": { "type": "aws::autoscaling:

shiny - Reactive input to ggvis in R-markdown cause quit -

i'm trying use r-markdown shiny interactive visualization. file let user specify bunch of data files , use reactive shiny expression processed dataframe, data() . can use data() renderplot correctly plot out bunch of graphs(like heatmap.2 , plot ). however, when try using ggvis plot reactive data, generation of html quit @ ggvis code chunk. tried answer how data passed reactive shiny expression ggvis plot? . both of 2 methods in answer led "quitting lines". here's code: reactive({ data %>% ggvis(~pcomp, ~variances) %>% layer_points()%>% layer_bars(fill := "gray", opacity := 0.5) %>% layer_lines() }) %>% bind_shiny("plot1") ggvisoutput("plot1") here's code based on other method: data %>% ggvis(~pcomp, ~variances) %>% layer_points()%>% layer_bars(fill := "gray", opacity := 0.5) %>% layer_lines() i'm using r-studio version 0.99.441, r version 3.2.1 (20

php - How to query and echo all data in column using Slim Framework -

i working on simple highscore system in slim framework (still beginner @ it), , stuck @ querying user datas. need query 2 columns in table (user, level) , sort level (desc). user ----------------------- id | name | level | ----------------------- 1 | tom | 10 | code in pure php $result = mysql_query("select name, level user"); $storearray = array(); while ($row = mysql_fetch_array($result, mysql_assoc)) { $storearray[] = $row['name']; } could more experienced provide me sample of code, can need ? the php slim code user resource be: <?php $app = new \slim\slim(); $app->get('/api/users', function () { $sql_query = "select id,name, level user order level desc"; try { $conn = new pdo('mysql:host=localhost;dbname=test', 'user', 'password'); $conn->setattribute(pdo::attr_errmode, pdo::errmode_exception); $rst = $conn->query($sql_query); $users= $r

Automatically Create Database in Entity Framework 6 with Automatic Migrations Disabled -

i able automatically create new database, if not exist, using code-first ef6 automatic migrations disabled. if recall correctly, before automatic migrations existed in entity framework, worked fine. however, in ef6, receive following exception: an exception of type 'system.data.entity.migrations.infrastructure.automaticmigrationsdisabledexception' occurred in entityframework.dll not handled in user code additional information: unable update database match current model because there pending changes , automatic migration disabled. either write pending model changes code-based migration or enable automatic migration. set dbmigrationsconfiguration.automaticmigrationsenabled true enable automatic migration. to verify exception not caused external factor in production project, created new test project. however, same exception. for database context, have: public class mycontext : dbcontext { public dbset<entity> entities { get; set; }

appending one object to another in javascript -

i have created 2 objects shown in below script. i'm able append them onto page using 'document.body'. now, wanted append 'appitem' header in 'mainwrapper'. how can this. function mainwrapper() { var wrapper; var header; function create() { wrapper = document.createelement('div'); header = document.createelement('div'); wrapper.appendchild(header); } function style() { wrapper.classname = "wrapper"; header.classname = "header"; } function init() { create(); style(); } init(); this.render = function (k) { k.appendchild(wrapper); } } function appitem() { var appitemicon; appitemicon = document.createelement('img'); appitemicon.src = 'icons/list.png'; this.appitemrender = function (k) { k.appendchild(appitemicon); } } window.addeventlistener('load', onload);

xcode - Setup screen iOS - Name edits -

Image
i looking change 2 info in xcode showing in simulator when app installed. do know should (see attached screenshot), name , copyright. i tried change bundle name , target without success. there's file called launchscreen.xib in project. automatically created part of project template, , shows name of project (at time of creation - that's why had no luck changing settings) , organization name . you can customize screen wish (e.g. show logo), or rid of altogether - need provide old 'default*.png' files, , indicate in project settings don't want use launch screen file.

c# - DataGridViewCell Change Error Icon -

i using .net 4.0 , i'm looking way change error image in cell when error text set word "linked". want original error image display if other error text. i've tried setting image when set text unable so. this have far: protected override void oncellpainting(datagridviewcellpaintingeventargs e) { if (e.errortext == "linked") { //image } else { base.oncellpainting(e); } } p.s. i've never used overrides before i'm aware i'm doing maybe wrong. reading you can try following code change error icon of datagridviewtextboxcell ... class datagridviewcell: datagridviewtextboxcell { protected override void painterroricon(graphics graphics, rectangle clipbounds, rectangle cellvaluebounds, string errortext) { if(errortext == "linked") { graphics.drawicon(systemicons.error, new rectangle(cellvaluebounds.width - 10, 0, 10, 10));

asp.net - Dynamic property changing, C# -

so have function replacement looking this: powerpointeventarg.powerpointdatalist[index].property = powerpointeventarg.powerpointdatalist[index].property.replace("deeperskyblue", "0066cc"); powerpointeventarg.powerpointdatalist[index].property = powerpointeventarg.powerpointdatalist[index].property.replace("deepskyblue", "3366ff"); powerpointeventarg.powerpointdatalist[index].property = powerpointeventarg.powerpointdatalist[index].property.replace("skyblue", "99ccff"); powerpointeventarg.powerpointdatalist[index].property = powerpointeventarg.powerpointdatalist[index].property.replace("yellow", "ffff00"); powerpointeventarg.powerpointdatalist[index].property = powerpointeventarg.powerpointdatalist[index].property.replace("darkturquoise", "0066cc"); powerpointeventarg.powerpointdatalist[index].property = powerpointeventarg.powerpointdatalist[index].property.replace("salmom"

c++ - Using lambda expressions by value capture -

quick query regarding usage of lambda captures, particularly "by value capture". here code: class carl{ public: int x; void sayhi(); }; void carl::sayhi(){ auto c1 = [=](){ //capture value std::cout<<&x<<std::endl; x = 10; // access copy? }; c1(); std::cout<<&x<<std::endl; // same address 1 inside lambda std::cout<<x<<std::endl; //prints 10 why???? } int main(int argc, char** argv) { carl x; x.sayhi(); return 0; } my issue that, "by value" captures in lambda supposed affect original? aren't supposed make copy? example, used [=] lambda make copy of variable within class's scope. tried accessing x , directly altered x's original value. tried researching , own words: it's stated accessing variable inside lambda has [=] capture access lambda's local copy. edit: feeling trying access this pointer captured [=

javascript - Issue with JsonForm in mvc -

i trying use jsonform libary github generate html markup json schema. trying in mvc view not have default form tag. added 1 html.beginform still markup not generated , following javascript error in console :typeerror: _ null . me out ? below code in view : @{ viewbag.title = "index"; layout = "~/views/shared/_layout.cshtml"; } @using (html.beginform()) { <script type="text/javascript" src="~/scripts/jquery-1.8.2.js"></script> <script type="text/javascript" src="~/scripts/json-form.js"></script> <script type="text/javascript" src="~/scripts/bootstrap.min.js"></script> <script type="text/javascript" src="~/scripts/underscore.js"></script> <link href="~/content/bootstrap.css" rel="stylesheet" /> <script type="text/javascript"> $('form').jsonform({ schem

java - Is placing all setters of derived class to util class a good design? -

i read codes this: public class base { protected map<string, object> attrmap = new hashmap<>(); public map<string, object> getattrmap() { return this.attrmap; } } public class deriveda extends base{} public class derivedb extends base{} public class util { public void setderivedaattrx(base base, object object) { base.getattrmap().put("deriveda_x", object); } public void setderivedaattry(base base, object object) { base.getattrmap().put("deriveda_y", object); } public void setderivedbattrx(base base, object object) { base.getattrmap().put("derivedb_x", object); } public void setderivedattrz(base base, object object) { base.getattrmap().put("derived_z", object); } } i asked implementor of codes why design this, here answer: we can't let setters in base , because it's set derived attributes. if move setters corresponding deriv

objective c - OSX application testing with OCMock -

i getting started osx tdd , ocmock, following http://pathfindersoftware.com/2009/01/testing-delegate-ocmock/ . right now, i'm @ phase application displays login upon startup , wish test user invalid/no credentials cannot login. in detail, appdelegate set login view controller's delegate, attempt login (without setting credentials), delegate method didnotauthorizeuser called. i'm getting error in test. further details below. object setup appdelegate - real object, instantiates login vc , conforms protocol ( somedelegateprotocol ) loginvc - mocked application - mocked test.m id mocklvc = [ocmockobject mockforclass:[loginviewcontroller class]]; [appdelegate setloginviewcontroller:mocklvc]; id qtapp = [ocmockobject mockforclass:[nsapplication class]]; id logindelegate = [ocmockobject mockforprotocol:@protocol(somedelegate)]; [[mocklvc expect] setlogindelegate:logindelegate]; [[mocklvc expect] authenticatewithservice]; [[logindelegate expect] didnotauth

extjs - Sencha cmd - Grid Rowediting -

i have grid, when open first time can edit normal use rowediting plugin. when close window edit , open again can not edit. thanks. you have use cancel event , if want update use update on place of "canceledit" var rowediting = ext.create('ext.grid.plugin.rowediting', { clickstomoveeditor: 1, //autocancel: false, listeners:{ 'canceledit': function(rowediting, context) { // canceling editing of locally added, unsaved record: remove if (context.record.phantom) { context.store.remove(context.record); } } } });

click a data toggle button using Jquery -

i have form has 4 data toggle tabs , submit button @ 4th tab. when click submit button, showing popup alert on filed not correct. should navigate 1st tab. how can click data toggle button using jquery ? tried many methods .click , .trigger , show , hide etc. not working.. of try.. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> function triger() { $('#trigered').trigger('click'); } function trigered () { $('#vamsi').show(); alert('hello. clicked'); } <script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css"> <button onclick=&q

fileinputstream - Java Resource Leak -

i have code snippet in application , quite sure have closed streams. but, surprisingly, keep getting: resource acquired @ attached stack trace never released. see java.io.closeable information on avoiding resource leaks. java.lang.throwable: explicit termination method 'close' not called any pointers useful. if (fd != null) { inputstream filestream = new fileinputstream(fd.getfiledescriptor()); bytearrayoutputstream bos = new bytearrayoutputstream(); byte[] buf = new byte[1024]; try { (int readnum; (readnum = filestream.read(buf)) != -1;) { bos.write(buf, 0, readnum); } content = bos.tobytearray(); } catch (ioexception ex) { ex.printstacktrace(); } { try { if (filestream != null) { filestream.close(); } if (bos != null) { bos.close(); } } catch (ioexception e) { e.printstacktrace(); }

javascript - d3 - drag node groups in radial tree layout without jumping to new position on click -

following on this question , i'm trying drag nodes (containing groups of circles , text) combined units without them first jumping new position when click. i've tried implementing suggested technique radial tree layout ( jsfiddle ) hitting wall. suspect because radial layout using different x,y system usual x,y system. i've been trying work rotate var drag can't quite seem crack it. should focusing? thanks. var drag = d3.behavior.drag() .on("drag", function(d,i) { d.x += d3.event.dx d.y += d3.event.dy d3.select(this) .attr("transform", function(d,i){ return "translate(" + d.x + "," + d.y + ")" }) }); it because of different x,y transforms used in radial view. changed drag function normal x,y coordinates var drag = d3.behavior.drag() .on("drag", function(d,i) { var translatecoords = d3.transform(d3.select(this)

Loading instance variables form a file in Typescript -

here's code: import fs = require('fs'); export interface answer { order: number, text: string } export class config { responses:answer[]; timestamp_column: string; name_column: string fromjsonfile(filename: string) { var filestring = fs.readfilesync(filename); var parsedfile = json.parse(filestring.tostring()); this.responses = parsedfile.responses; this.timestamp_column = parsedfile.timestamp_column; this.name_column = parsedfile.name_column; } mapanswertonum(answer:string):number { (var of this.responses) { if (a.text == answer) { return a.order;} } throw new error(`invalid response string ${answer}`); } } it reads in file: { "responses": [ { "value": 0, "text": "at loss explain it..."}, { "value": 1, "text": "have vague sense..."}, { "value": 2, "text": "pretty handle on it..."}, { &quo

Difference between Jquery Html callback function and append function? -

what difference between jquery html callback function (source http://www.w3schools.com/jquery/jquery_dom_set.asp ) , jquery append function (source http://www.w3schools.com/jquery/jquery_dom_add.asp ) also ecsctly use of parameter index in jquery html callback function? callback used manipulate content of html element. here can put logic handle text provided , return modified text. in below code, adding original text new 1 return index. same way can put own logic handle text. $("#test1").text(function(i, origtext){ return "old text: " + origtext + " new text: hello world! (index: " + + ")"; }); while in append got choice add more text after existing text , nothing can done extra. in below example, appending new text existing text. $("p").append("some appended text.");

css3 - Apply a CSS filter only on background -

in following snippet, have applied blur filter on .sub-menu text filtered. how can apply blur filter only on background , not text ? .sub-menu { list-style: none; position: relative; float: left; margin: 0px; padding-left: 0px; z-index: 1; } .sub-menu li { display: block; color: #888888; text-decoration: none; font-size: 14px; line-height: 32px; padding: 0 12px; } .sub-menu li a:hover { color: black; } .sub-menu { position: absolute; top: 100%; left: 0; -webkit-filter: blur(10px); /* chrome, opera */ -moz-filter: blur(10px); -ms-filter: blur(10px); filter: blur(10px); padding: 0 } <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css" rel="stylesheet" /> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/boo

sbt compile in Compile meaning -

can kindly explain each compile , compile mean in cryptic sbt idiom: compile in compile <<= (compile in compile).dependson(def.task { println("task running") // or whatever code here in body }) compile means compile task, opposed to, say, package compile means compile configuration (derived from/matches apache ivy's configurations), opposed to, say, test

google reflections - Java - determine where an object is instantiated from object's class -

say have class called myclass , within class, want find out class name instantiated object of myclass , example: class myclass { final string whocreatedme; public myclass() { whocreatedme = ??? } } public class driver { public static void main(string[] args) { system.out.println(new myclass().whocreatedme); // should print driver } } this not advisable, , breaks in unexpected (and expected) ways. hope you're not going use in production code. public class temp { static class testclass { public final string whocreatedme; public testclass() { stacktraceelement ste = thread.getallstacktraces().get(thread.currentthread())[3]; whocreatedme = ste.getclassname(); } } public static void main(string[] args) throws exception { system.out.println(new testclass().whocreatedme); } }

c# - Multi-threading in custom SSIS transformation data flow task -

i have ssis package this: 1. read records flat file source 2. transform calling webservice adds additional response column buffer 3. output input records , response column destination file. 2 custom transformation data flow task wrote, synchronous because outputting input. i thought default buffersizes , enginethread properties multithreaded , call multiple processinputs @ same time. once ran it, realised called web service 1 @ time. how can make multi-threaded? i've googled around found myself getting more confused. thanks in advance have seen this excellent blog ? quote blog: sql server integration services (ssis) allows parallel execution in 2 different ways. these controlled 2 properties outlined below. the first 1 maxconcurrentexecutables, property of package. defines how many tasks (executables) can run simultaneously. defaults -1 translated number of processors plus 2. please note if box has hyperthreading turned on, logical processor rather

java - javax validation not validating complex object attributes -

i trying validate class using javax.validation.validator. below doing. final set<constraintviolation<paymentdetailsform>> set = validator.validate(accountpaymentdetailsform); my paymentdetailform looks this public class paymentdetailsform { private string paymentid; private string cardtypecode; private boolean newbillingaddress; private addressform billingaddress; private string securitycode; when submitting form validating paymentid,cardtypecode, etc. not validating billingaddress form inside paymentdetailsform. do need give anotation on getbillingaddress() method?

python - Unable to run Django's unit test -

when typed python manage.py test run unit testcases, prompted error messages below: traceback (most recent call last): ... django.test.utils import contextlist file "d:\dev\py27\lib\site-packages\django\test\utils.py", line 8, in <module> unittest import skipif, skipunless importerror: cannot import name skipif when run unittest alone, works fine, running unittest in django failed. unittest should built-in library of python. please let me know how fix issue. thanks. use dir(unittest) verify skipif etc included in unittest . in case skipif missing, , install python interpreter work. i tried several versions of python on windows , miss skipif .

c# - Delete sqlite database file in .net environment -

i'm doing integration tests of software uses sqlite. the software needs use database file prevent data being lost. after each of tests, want delete database file leave @ beginning. the problem when try delete file throws exception says "system.io.ioexception: process cannot access file '*****' because being used process". before trying delete file, i'm closing , disposing of connection this: if(_connection.state == system.data.connectionstate.open) _connection.close(); _connection.dispose(); to delete file using instruction: file.delete(_databasefilepath); doing wrong?, miss something? in advance.

How to fix battlefield 4 directx errors? -

i error: directx function “getdeviceremovedreason” failed dxgi_error_device_hung(“the application’s device failed due badly formed commands sent application. design-time issue should investigated , fixed.”). any ideas? there few fixes solve this: fix #1: install visual c++ redistributable visual studio 2012 update 4 fix #2: run clean boot on pc or mac fix #3: downclock graphics card more informations can find here: http://theitbros.com/battlefield-4-directx-error/

windows - How can I make a batch file that will tell me which lines of a text file are NOT in another file? -

what i'm trying take text file bunch of strings search for, each on own line, , search each 1 of these strings in file (check.txt). want output text file list of strings couldn't found. i've tried few things far. /f "tokens=*" %%a in search.txt ( @echo on findstr %%a check.txt if errorlevel 1 echo %%a fail > fail_match.txt ) another attempt made (this 1 tell me if whole list or not) @echo on findstr /g:search.txt check.txt > a_match.txt if errorlevel 1 echo bad > a_match.txt i realize these incredibly basic, , i'm sure there's easy answer don't understand. i'm not programmer; want make job lot easier (and faster). to clarify, list of things search in search.txt, list of things check them against check.txt. check.txt json file, it's 1 enormous line. don't know if make difference or not. want list of lines in search.txt not in check.txt. your search scheme seems naive on 2 fronts: 1) json not guaranteed

apache camel - NoModificationAllowedError in Hawtio -

i deployed camel route in servicemix in local machine hawtio feature installed. im able view diagram, source, osgi bundle, trace, debug in hawtio url http://localhost:8181/hawtio/ with username , password smx/smx or karaf/karaf but when deploy same route in virtual machine running in network , check in hawtio, showing nomodificationallowederror on checking camel contexts. can me out issue?

c++ - Error handling when parsing text file to object -

i want parse simple text file , create object data contains. i'm using c++11 (and i'm not fluent). in case of kind of error (e.g. missing file or invalid text) wish tell caller of parsing function went wrong, providing information kind of error occurred , in file. i don't consider exceptional errors occur while parsing, seems exceptions not way go. i thought of returning struct info, including resulting parsed object in case of success: struct parsingresult { bool success; int errorcode; int errorline; parsedobject object; } however i'm not convinced solution because, in case of errors, must still provide parsedobject . can define default constructor that, of course, it's nature parsedobject makes sense when parsing successful. i change parsedobject parsedobject* , i'm reluctant use pointers when not necessary, , wonder if can avoided. my question: can suggest better solution problem? it? struct obj { // object d

entity framework - EF Migrations in Hierarchy -

i'm using entity framework multiple existing databases in hierarchy. 1x parent 3x children i aim have 2 database contexts, 1 support parent , 1 support children. intend have automatic migrations setup , enabled on both contexts. my child contexts pass in connection string name determine child connection create /// <summary> /// represents child database context within hierarchy /// </summary> public class childdbcontext : dbcontext { public childdbcontext(string name) : base(name) { database.setinitializer(new migratedatabasetolatestversion<childdbcontext, migrations.configuration>()); } } question will automatic migrations update each child database first time accessed i.e first time new childdbcontext("child1") , new childdbcontext("child2") , new childdbcontext("child3") ? i'm not 100% sure when migration check performed or whether work without parameterless contructor. ef de

Rails Asset Pipeline with sass @imports -

this question has answer here: import regular css file in scss file? 14 answers i'm using rails 4.2. in rails project directory, have frontend directory: /railsproject/frontend /railsproject/frontend/styles /railsproject/frontend/styles/main.scss /railsproject/frontend/styles/variables.scss /railsproject/frontend/node_modules/normalize.css/ /railsproject/frontend/node_modules/normalize.css/normalize.css ( i know it's unusual have directory period in it, have tried changing directory name , corresponding @import statement , didn't make difference ) i have added config.assets.paths << rails.root.join("frontend","styles") application.rb . in /railsproject/app/assets/stylesheets/application.css : @import "main.scss"; everything far, loads/processes main.scss file. in /railsproject/frontend/styles/main.scss

java - Adjacency Lists for graph representation using space O(number of edges) -

i'm trying represent graph(connected-non directed-without weights) in java using adjacency lists (the space represent graph has o(m) m number of edges) in order find informations usings bfs. information graph txt called graph.txt. i'm not sure if use space o(m) save graph , i'm not sure if way save in order use bfs. public class vertex { boolean visited = false; int number; arraylist<integer> adjlist; public vertex(int i) { this.number= i; adjlist = new arraylist<integer>(); } public void addneighbor(int i) { this.adjlist.add(i); } } yes, representation use o(m) space. have 2 different suggestions, given representation. 1. if want represent vertex class, have it's list of adjacent verticies list<vertex> instead of list<integer> or 2. since vertex class not seem hold information other integer value of vertex, why not use integer itself? graph represented as arraylist<

Ajax in Firefox add on panel content JavaScript -

i use firefox add on sdk . have button in toolbar , in on click event show panel html file . need use ajax function in on click of html button used in panel html file. <html> <script> function test() { var xhr=new xmlhttprequest(); //some ajax code } </script> <button onclick='test()'>click here</button> </html> i new in using firefox sdk . possible @ ?? , if possible how should ? you can't use inline scripting inside html page in firefox addon, add script packaged local resource , executed. basically have split in two, html , js , reference js in html

amazon web services - Elastic beanstalk periodic tasks on autoscaled environment -

on autoscaled environment running periodic task, if environment scaled up, periodic tasks run on each instance? or more specifically, each instance post queue leading multiple "periodic tasks" running? yes. if there's periodic task should triggered once, should have separate auto scale environment of minimum 1 maximum 1 instance either perform task or trigger on 1 of servers (maybe make request load balancer , 1 of instances perform task)

python - Modifying Code to work for Month and Week instead of Year -

Image
i making stacked bar plot on year time span x-axis company names, y-axis number of calls, , stacks months. i want able make plot run time span of month, stacks days, , time span of week, stacks days. having trouble doing since code built around year time span. my input original input csv file. pulling 2 rows this: companyname recvd_dttm company1 6/5/2015 18:28:50 pm company2 6/5/2015 14:25:43 pm company3 9/10/2015 21:45:12 pm company4 6/5/2015 14:30:43 pm company5 6/5/2015 14:32:33 pm then make datatable looks this pivot_table.head(3) out[12]: month 1 2 3 4 5 6 7 8 9 10 11 12 companyname customer1 17 30 29 39 15 26 24 12 36 21 18 15 customer2 4 11 13 22 35 29 15 18 29 31 17 14 customer3 11 8 25 24 7 15 20 0 21 12 12 17 and code far. first grab years worth of data (i change month or week

Resize file data image .PNG in Python -

import image import os def resize_file(fname): width, height = get_image_size(fname) /// get_image_size return width , height /// name, ext = os.path.splitext(fname) new_image_file = "%s%s%s" %(name, 'new' , ext) im1 = image.open(fname) im5 = im1.resize((width, height), image.antialias) ext2 = ".jpg" im5.save(name + 'new' + ext2) import webbrowser webbrowser.open(name + 'new' + ext2) if __name__ == "__main__": resize_file('/home/kirito/desktop/hd_69830_planet.jpg') resize_file('/home/kirito/desktop/cod2.png') * problem : line when change ext2 = ".png" data file not change. when ext2 = ".jpg" data size down (case true). want change image.png data file size down , result still image.png ! close ! a lossless format, such png, allows 1 recover exact pixel values of original image compressed file. lossy format makes assumptions human eye c

python - Disable output buffering -

is output buffering enabled default in python's interpreter sys.stdout ? if answer positive, ways disable it? suggestions far: use -u command line switch wrap sys.stdout in object flushes after every write set pythonunbuffered env var sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) is there other way set global flag in sys / sys.stdout programmatically during execution? from magnus lycka answer on mailing list : you can skip buffering whole python process using "python -u" (or#!/usr/bin/env python -u etc) or setting environment variable pythonunbuffered. you replace sys.stdout other stream wrapper flush after every call. class unbuffered(object): def __init__(self, stream): self.stream = stream def write(self, data): self.stream.write(data) self.stream.flush() def writelines(self, datas): self.stream.writelines(datas) self.stream.flush() def __getattr__(self,

report - Conditional style in cognos graph -

Image
is possible apply conditional style depending on column? i have chart shows machine's productivity on time. every few weeks, there maintenance operation on these machines , have dates stored in table. change de color of 'production brut' square when maintenance operation has been done. i tried conditionnal styles 'date de production' = 'date de maintenance' nothing happens. managed simple condition (change color when 'production brut' > production standard')

javascript - Parse JSON from the body of the POST -

i'm using cameratag.com record video on website. service can send json response server can save data database. don't know how proceed here: the documentation states please note json repsonse passed in body of post , not form parameters. here example of how parse response in ruby: data = json.parse(request.raw_post) video_uuid = data["uuid"] but don't know how data on javascript. i'm not experienced in js please bare me :) post sample: { "uuid": "00012710-4b65-0131-ffe6-22000a499ea4", "camera_uuid": "98373a20-79ee-0130-3e42-1231390fcc11", "created_at": "2013-12-20t05:25:02.000z", "percent_complete": 100, "short_code": "kktb4q", "metadata": { }, "state": "published", "recorded_from": "http://singwho.com", "publish_type": null, "formats": [ { "name&qu

bash - rsync script expands variable incorrectly -

i have script takes in unique location number file. these formatted 7325-05, 5269-09 , 7479-14, example. first 4 numbers folder called , second number first 2 characters of filename unique within each folder. so wrote script use locate , find full path of folder , use wildcard download specific file using rsync. here's script have right now: #!/bin/bash #ifs=' #' oifs=$ifs ifs=$'\n' while read line; name=$line; folder=${line:0:4} track=${line: -2} folderlocation="$(locate -r '/'$folder'$')" filelocation="$(find "$folderlocation" -type f -name "$track*")" rsync -vazhn --progress "$filelocation" /cygdrive/c/ # mkdir /cygdrive/c/test/"$folder" # cp -rvi "$filelocation" /cygdrive/c/test/"$folder" echo ""; done < $1 the code using cp commented out works fine. prefer use rsync, due better feedback , more accurate progr

Android: bitmap rotation leads to black background -

i'm facing issue related bitmap rotation, issue follow code rotates bitmap fine background when draw rotated bitmap on canvas, see version 5.0 above , 4.0 transparent background... clue please share. int resid = context.getresources().getidentifier(mdrawablename, "drawable", context.getpackagename()); matrix mat = new matrix(); mat.postrotate(i*6%30); // angle rotated bitmap logobm = bitmapfactory.decoderesource(context.getresources(), resid) ; logobm = density.getinstance().scaleit(logobm, density.getinstance().getpixelfordp(80), 0); logobm = bitmap.createbitmap(logobm, 0, 0, logobm.getwidth(), logobm.getheight(), mat, true); i issue. after goolge, find if use bitmapfactory.decoderesource,this issue can't fixed @ devices. use these code instead of bitmapfactory.decoderesource: bitmap bitmap = yourbitmap; matrix matrix = new matrix(); matri

regex - Apache2 - mod_rewrite and .htacess - Not working 404 rule when i add other rules -

here current .htaccess file: rewriteengine on rewritecond %{the_request} ^[a-z]+\s([^\s]+)\.php\s rewriterule .* %1.html [r=301,l] rewriterule ^(.*)\.html$ $1.php errordocument 404 /page-404.html like when open adress ending .php auto redirected same adress ending of .html want. when remove these lines: rewriteengine on errordocument 404 /page-404.html and try open non-existing directory got 404 error redirected page want. problem comes when add additional lines shown in first code posted. where problem , why 404 error redirection not working in first example ? thanks in advance! have rules this: errordocument 404 /page-404.html rewriteengine on rewritecond %{the_request} ^[a-z]+\s([^\s]+)\.php\s [nc] rewriterule .* %1.html [r=301,l] # make sure .php file exists requested .html file rewritecond %{document_root}/$1\.php -f [nc] rewriterule ^(.+?)\.html$ $1.php [l,nc]

c++ - Is calling std::min on an empty initializer list (and explicitly specifying the type) undefined behavior? -

calling std::min() empty initializer list not compile (all question can stated in same way std::max() ). code: #include <iostream> #include <algorithm> int main() { std::cout << std::min({}) << "\n"; return 0; } with clang gives error: test.cpp:6:17: error: no matching function call 'min' std::cout << std::min({}) << "\n"; ^~~~~~~~ algorithm:2599:1: note: candidate template ignored: couldn't infer template argument '_tp' min(initializer_list<_tp> __t) i can see why case not allowed, because difficult agree on sensible value return in case. however, technically speaking code not compile because template parameter cannot deduced. if force parameter code compiles crash: #include <iostream> #include <algorithm> int main() { std::cout << std::min<int>({}) << "\n"; return 0; } $ clang++ -std=c++11 test.cpp -o test

c - Is there a better way to find length of any String or a Number? -

here 1 way problem unnecessary usage of output screen. lenth=printf("%d",num);// or lenth=printf("%s",str); how find length without having output printf? you can use snprintf() empty buffer (i.e. pass null pointer), return number of characters have been written buffer if there enough space in it: int length = snprintf(0, 0, "%d", num); this way, don't need use actual buffer , won't print on stdout printf() does.

Left outer join in MySQL -

is possible join these 2 tables following result. table stats date cus_id pur amount 2015-02-01 2585711 2 100 2015-02-02 2585711 5 250 2015-05-03 2585711 8 400 2015-02-01 2585475 2 100 2015-02-02 2585475 5 250 2015-05-03 2585475 8 400 table customer reg_date cus_id gender country 2014-04-11 2585711 male sweden 2015-02-01 2585475 female sweden expected result date cus_id pur amount gender country 2014-04-11 2585711 null null male sweden 2015-02-01 2585711 2 100 male sweden 2015-02-02 2585711 5 250 male sweden 2015-05-03 2585711 8 400 male sweden 2015-02-01 2585475 2 100 female sweden 2015-02-02 2585475 5 250 female sweden 2015-05-03 2585475 8 400 female sweden if use left outer join join 2 tables, following

c - HC - SR04 raspberry pi -

i have raspberry pi b , trying write code in c allow me use hc-sr04 ultrasonic ranging module . used bcm2835 library control gpio pins. have connected according this website . here attempt: # include <bcm2835.h> # include <stdio.h> # include <time.h> # include <stdlib.h> # define echo rpi_v2_gpio_p1_03 # define trig rpi_v2_gpio_p1_05 int main(int argc, char **argv) { if (!bcm2835_init()) return 1; bcm2835_gpio_fsel(echo, bcm2835_gpio_fsel_inpt); bcm2835_gpio_fsel(trig, bcm2835_gpio_fsel_outp); time_t clockstart = 0; time_t clockstop = 0; bcm2835_gpio_write(echo, low); delay(2); printf("trigger\n"); bcm2835_gpio_write(trig, high); usleep(10); bcm2835_gpio_write(trig, low); printf("measure\n"); while (bcm2835_gpio_lev(echo) == 0) { clockstart = time(null); } printf("b: %i\n", (int)clockstart); while (bcm2835_gpio_lev(echo) == 1) { clockstop = time(null); } printf("e: %i\n", (int)clockstop); ti

how does ORC indexing work -

the way how indexing in database works: refering answer xenph yan creating index on field in table creates data structure holds field value, , pointer record relates to. index structure sorted, allowing binary searches performed on it. the way understood orc indexing is, orc keeps statistics (min, max, sum) rows every 10'000 rows (by default )and if query data looks @ statistics figure out if needs read row chunk or not. so correct orc indexing not sort data? i have 69 column large table unstructured data , able perform ad-hoc queries on every column. so, able sort every column through index (or @ least of them). there no 'key' column in data get's queried rapidly. hive has been designed pseudo-sql front-end running (long) batch jobs on (massive) data sets. can run "ad hoc queries" forget "rapidly" . besides, when index column in database (i.e. create index command in sql), index entire, exact value of each row. if

sql server - Global temp tables with SQLCMD -

in ssms, can create global temp variable in 1 batch , use in another. this: create table ##temp (col1 int) go drop table ##temp go with sqlcmd, create global temp table in 1 call , not exist in second. sqlcmd -s localhost -d tempdb -e -q "create table ##temp (col1 int)" sqlcmd -s localhost -d tempdb -e -q "drop table ##temp" msg 3701, level 11, state 5, server vatllxt7lgbare2, line 1 cannot drop table '##temp', because not exist or not have permission. is global temp table not supposed stick around until server reset? yes that's correct cause global temporary table exists in connection/session created , gets dropped automatically if connection closes. in case, first sqlcmd creates table sqlcmd -s localhost -d tempdb -e -q "create table ##temp (col1 int)" and connection closes drops temporary table , in next connection doesn't exists anymore sqlcmd -s localhost -d tempdb -e -q "drop table ##temp"

Powershell -like won't compare to variable -

in powershell, can this: $useraccount = get-aduser -filter { name -like "*smith*"} and find user(s), when this: $namefilter = "smith" $useraccount = get-aduser -filter { name -like "*$namefilter*"} nothing found. why? -filter looks accepts script block where-object, it's string. if use curly braces syntax, tends treat literal string, variables won't expand. try: $useraccount = get-aduser -filter "name -like '*$namefilter*'"

Datastax DSE jar location -

i installed datastax enterprise on mac. can find dse.jar? or can download from? i want use spark , cassandra helpers. thanks, id to find dse.jar, run: sudo find / -name dse.jar or within particular directory: sudo find . -name dse.jar

Need 'return' statement following 'fail' call in a Ruby method? -

i got following code rails tutorial: def do_something # code here.... if @user.blank? fail notauthenticatederror return end # more code here... end is return statement necessary, or fail call sufficient stop rest of code in method running? perhaps depends on how notauthenticatederror handled? no, don't need return. def do_something puts "start" fail notauthenticatederror puts "this doesn't print" end that code never last line. check out: what-does-the-fail-keyword-do-in-ruby

linux - What can I do when an external client try to run a PHP script on my server? -

i have lamp configured server , multiple times apache error log file can see warning messages one: [thu jul 02 08:54:04.263981 2015] [:error] [pid 12059] [client 5.45.79.44:49144] script '/var/www/html/wp-update.php' not found or unable stat, referer: http://example.org/wp-update.php currently have mod_security , inside wordpress wordfence enabled. what should done in such cases protect , prevent these attacks? those warning messages can ignored, since generated when apache can't find requested file (404) or permission requested file denied (403). i see tons of such messages daily in server logs , reason appear is, automated scripts try check server vulnerable/insecure scripts, admin may have forgotten. lately noticed, kind of mass-requests target ssh keys (get /var/www/.ssh/id_rsa - in case server admin misconfigured server). running mod_security on server tight ruleset (e.g. owasp crs ) gives basic protection against various kind of known/unknow

c# - OleDbConnection close method taking long execution time -

constr = string.format(constr, filepath, ishdr); oledbconnection connexcel = new oledbconnection(constr); oledbcommand cmdexcel = new oledbcommand(); oledbdataadapter oda = new oledbdataadapter(); datatable dt = new datatable(); cmdexcel.connection = connexcel; //get name of first sheet connexcel.open(); datatable dtexcelschema; dtexcelschema = connexcel.getoledbschematable(oledbschemaguid.tables, null); string sheetname = dtexcelschema.rows[0]["table_name"].tostring(); connexcel.close(); i using above code read excel. stuck @ connexcel.close(); few seconds , move next statement. causing late processing on page. suggestions?? updating question give more details. test case:- uploaded xls file took normal time. uploaded xlsx file halt @ connexcel.close() 25sec. uploaded xls file , halt xls also. i have used following connection strings for xls :- c

c# - "COM target does not implement IDispatch" exception when opening Outlook.Contact -

my code straightforward: using outlook = microsoft.office.interop.outlook; private outlook.contactitem contact; private void outlookbutton_click(object sender, routedeventargs e) { try { contact = new outlook.contactitem((outlook.contactitem)((button)sender).tag); contact.display(); the display() line raises exception related idispatch : system.reflection.targetinvocationexception: com target not implement idispatch. there outlook contact object bound buttons tag, , idea when button clicked open show them. outlook (the application) not running. above works fine first time, if click on same button second time, exception above raised. if tried using netoffice , gave me same result. you can't create outlook items using class ctor. instead, need use createitem or createitemfromtemplate methods of application class. also add method of items class can used create new outlook items. most need correct code: contact = (outl

plugins - Get list of attributes of a specific woocommerce product -

i have array of product ids , want attributes of each product in array. is possible list of attributes product id ? i found solution. use get_post_meta() attribute , use get_terms() list of term values like: $attribute = get_post_meta( $products->post->id, '_product_attributes', true); get_terms($attribute);

mysql - Sub query with count -

this query works fine , list of (male,female) items. select dmg.dmg_sex demographic dmg join link lnk on lnk.lnk_dmgid = dmg.dmg_id join admission adm on adm.adm_id = lnk.lnk_admid adm.adm_id in (select distinct(adm.adm_id) admission adm join link lnk on lnk.lnk_admid = adm.adm_id join daily_link dlnk on dlnk.dlk_lnkid = lnk.lnk_id dlnk.dlk_assessdate >= '2011/01/01' , dlnk.dlk_assessdate <= '2011/03/31') if male, female result in counted list select dmg.dmg_sex, count (dmg.dmg_sex) demographic dmg join link lnk on lnk.lnk_dmgid = dmg.dmg_id join admission adm on adm.adm_id = lnk.lnk_admid adm.adm_referraldate >= '2011/01/01' , adm.adm_referraldate <= '2011/03/31' group dmg.dmg_sex desc but trying combine 2 queries adding count (dmg.dmg_sex) first query not work. why or missing something select dmg.dmg_sex, count (dmg.dmg_sex) demographic dmg j

oracle11g - Oracle Intersection of rows in a Table -

hi have table 2 columns (wid,dt) data.. wid dt ------- 10 11 12 b 10 b 11 c 10 c 13 if pass a,b in input should output 10 , 11. intersection of dt. if pass a,b,c in input should 10 output. if pass input 10,11,12 output.. input dynamic depends on conditions ui. how achieve in query... here's way doesn't require add intersect each item in list pass in parameter. can't guarantee peform on large data sets, however, you'd have test data! this first example shows results mimics effect of multiple values of parameter being passed in @ same time (mainly show results of different test cases mentioned): with sample_data (select 'a' wid, 10 dt dual union select 'a' wid, 11 dt dual union select 'a' wid, 12 dt dual union select 'b' wid, 10 dt dual union select 'b' wid, 11 dt dual union select 'c' w

How do I print a millisecond count from epoch as a date-time in UTC using Java? -

i trying use java format time in milliseconds date in utc. have following code: long ms = 1427590800000; calendar cal = calendar.getinstance(timezone.gettimezone("utc"), locale.root); cal.settimeinmillis(ms); date date = cal.gettime(); simpledateformat dateformat = new simpledateformat("yyyy-mm-dd hh:mm:ss"); system.out.println(dateformat.format(date)); // 2015-03-29 02:00:00 this printing time in bst (i.e. using default time-zone) rather utc. seems time-zone being set on calendar has no bearing on date being printed. the actual time in utc shown following python snippet: import datetime ms = 1427590800000 print datetime.datetime.utcfromtimestamp(ms/1000.0) # 2015-03-29 01:00:00 setting default jvm time-zone "utc" results in correct date being printed, doesn't seem safe solution. you need set timezone formatter before formatting if want desired timezone. use dateformat.settimezone(timezone.gettimezone("utc")); , cal

matlab - Circular ROI is not being drawn from input -

Image
for reason, following code displays masked image roi @ 10,10 height , width 100,100. these initial values. seems image not update after getposition function. explain issue? `i = imread('/users/imageuser/documents/pt300.tif'); h = imshow(i); % define circular roi square bounding box x = 10; y = 10; d1 = 100; d2 = 100; e = imellipse(gca, [x y d1 d2]); % roi can interactively moved/adjusted % not close figure window before createmask called %%% these lines needed if move or resize roi pos = getposition(e); x = pos(1); y = pos(2); d1 = pos(3); d2 = pos(4); %%% bw = createmask(e,h); pause; imshow(bw);` you need put lines (note inverted order): pause; bw = createmask(e,h); before calling getposition , otherwise new position not updated. whole code: clear clc close = imread('coins.png'); h = imshow(i); % define circular roi square bounding box x = 10; y = 10; d1 = 100; d2 = 100; e = imellipse(gca, [x y d1 d2]); pause; bw =

java - Internally resolving HTML of specified URL using routing -

i developing web application using play framework 2.3.9 java. love have method gets corresponding result specified call or url. know routing, able call method controller, can example retrieve html several pages @ once. need widget support in application. example input: routes.applicationcontroller.index("hello world") example output: corresponding result html body is there such method in play? or have own solution this? feel useful in many other situations well. i saw useful methods in testing module of play, failed use them in normal environment. , don't idea of referencing test module else testing. unfortunately, not @ scala, don't mind having solution in scala, long need call method , expected result. cheers, dusan

Android Spinner Dialog Multi Column -

please me. my spinner (default android): https://lh3.googleusercontent.com/-eeuaen-sry4/vavxkajrkai/aaaaaaaanys/jwp-o9kxajo/s505-ic42/now.jpg i want (custom): https://lh3.googleusercontent.com/-iqv1pnomi6i/vavxkcbogdi/aaaaaaaanys/s9eepi2ivli/s505-ic42/i-want.jpg and custom layout xml code: <?xml version="1.0" encoding="utf-8"?> <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:gravity="center"> <imageview android:layout_margintop="@dimen/boslukaz" android:layout_marginbottom="@dimen/boslukaz" android:background="@color/actionbaracik" android:contentdescription="@string/uygulama_adi" android:id="@+id/simges" android:layout_w