Posts

Showing posts from February, 2014

c++ - std::sort doing lots of unnecessary swaps -

i have following code try lexicographical comparison of 2 simple vectors class expensiveclass { public: static int increment; std::vector<int> bigvector; expensiveclass() { (int j = 0; j < 1 + increment; ++j) bigvector.emplace_back(j); ++increment; } expensiveclass(const expensiveclass& other) { std::cout << "expensive copy constructor called!" << std::endl; this->bigvector = other.bigvector; } }; int expensiveclass::increment = 0; bool sortfunc(const expensiveclass& a, const expensiveclass& b) { bool ret = a.bigvector < b.bigvector; if (ret == false) std::cout << "need swap" << std::endl; return ret; } int main() { std::vector<expensiveclass> vectorofvectors; vectorofvectors.reserve(100); (int = 0; < 100; ++i) vectorofvectors.emplace_back(); std::cout << "start sorting.." << std::endl; std::sort(vectorofvectors.begin...

javascript - Understanding Yield in ES6 with functions -

so understand concept of generators , keyword 'yield' represents in javascript i've played around in chrome (version 43.0.2357.81 (64-bit) on mac os x 10.10.3) i've ran situation don't understand result of. here working example of how yield works: function* test() { var = 0; while ( < 4 ) { yield ++index; } } tester = test(); console.log( tester.next().value ); //1 console.log( tester.next().value ); //2 console.log( tester.next().value ); //3 console.log( tester.next().value ); //4 console.log( tester.next().value ); //undefined the result expect. following example in mdn documentation see can use yield* use generator function. in understanding expect using yield function should return function it's value. here example: function* test() { var = 0; while ( < 4 ) { ++i; yield function( ) { return + i; }; } } tester = test(); console.log( tester.next().value ); //undefined console.log( tester.nex...

How to put array values to specific column in listview in C#? -

Image
i created 2 listview column ' sample ' , ' quantity ' in design view mode. want add array data mysample 'sample' column , myquantity 'quantity' column. not how specific column data should go to. please help. here code - str[] mysample = somedata; str[] myquantity = somedata; (int = 0, < mysample; i++) { listviewitems item1 = new listviewitem(); item1.subitems.add(mysample[i].tostring()); listview1.items.add(item1); listviewitems item2 = new listviewitem(); item1.subitems.add(myquantity[i].tostring()); listview1.items.add(item2); } you need 1 listviewitem per row. string[] mysample = { "sample a", "sample b", "sample c"}; string[] myquantity = { "1", "2", "3"}; (int = 0; < mysample.length; i++) { string[] subitems = new string[] { mysample[i], myquantity[i] }; listviewitem item = new listviewitem(subitems); li...

sql server - SQL - Stored Procedures - get values from subquery -

i have stored procedure , exec call like: exec schedule_insertreservations @scheduleid = (select scheduleid schedule job_no = 'abc'), @scheduletaskid = (select scheduletaskid scheduletasks (scheduleid = (select scheduleid schedule job_no = 'abc')) , librarytaskid = 247), @resourceid = (select vendor_id tblvendors vendor_name = 'blue line taxi') and trying set values stored procedure using sub-queries these errors when run it: msg 102, level 15, state 1, line 1 incorrect syntax near '('. msg 102, level 15, state 1, line 1 incorrect syntax near ','. msg 102, level 15, state 1, line 1 incorrect syntax near ','. can not use sub-queries in stored procedures? why cant declare 3 variables , use parameter procedure. declare @sch_id int,--change datatype based on schema. @vendor_id int, @sch_taskid int select @sch_id = scheduleid schedule job_no = 'abc...

many to many - Symfony + Sonata, OneToMany Relation -

could give me hand please? i need implement list of books , readers using sonata admin bundle. the problem empty column of read books each reader in list. forein keys written okay db. please see code: readersadmin class protected function configureformfields(formmapper $formmapper) { $formmapper ->add('name') ->add('book', 'entity', array( 'class' => 'appbundle:books', 'property' => 'name', 'multiple' => true, 'expanded' => true ) ); } /** * @param \sonata\adminbundle\show\showmapper $showmapper * * @return void */ protected function configureshowfield(showmapper $showmapper) { $showmapper ->add('name') ->add('book') ; } /** * @param \sonata\adminbundle\datagrid\listmapper $listmapper * * @return vo...

git - Why is github showing different authorname? -

i cloned fresh repo of code. made necessary changes in repo followed these 3 steps git add --all git commit git push -u origin master it asks username,password, enter. but after push, git repo shows changes authored colleague rather am. why so? can't it. check email in config git config --global user.email if not yours, change , commit again: $ git config --global user.name "john doe" $ git config --global user.email johndoe@example.com

Common LISP addition program -

i trying write program takes in list of numbers , adds 1 each element in list. if list 0 return nil. tried doing recursively shows me no output. know it's simple beginner , hard me think problem recursively. thanks! a list made of cons . has first value , list consisting of rest of list except first value. should check if list null (or endp same) , if isn't make cons calculation have first , recursive call using rest . argument. (add-1 '(1 . (2 . (3 . ())))) ; ==> (2 . (3 . (4 . ()))) or more commonly written: (add-1 '(1 2 3)) ; ==> (2 3 4)

ruby - guarantee order of keys in hash after much manipulation -

here's problem. going through these steps below can see how hash keys no longer in order. in below example, keys 0, 2, rather 0,1. , sure larger data set, situation worse. there way can guarantee order of keys in hash? task: if fields has defaults doesn't have, add defaults if defaults has key k field not have, remove key-value pair key k default test data: fields = { "0"=>{"field"=>"name", "field_type_id"=>1}, "1"=>{"field"=>"address", "field_type_id"=>2} } defaults = {0=>"name", 1=>"email" } step 1: find ones in fields not in defaults: fields_arr = fields.values.collect {|hsh| hsh['field'] } => ["name", "address"] defaults_arr = defaults.values => ["name", "email"] updates = fields_arr + defaults_arr - (fields_arr & defaults_arr) - defaults_arr => ["address"] ...

security - Style-src CSP Errors with JQuery and Modernizr -

when remove unsafe-inline script-src on csp headers multiple errors on modernizr 2.8.3 , error on jquery 2.1.3. it's strange because error on 1 of sites although using same libraries on others no csp issue. error example: refused apply inline style because violates following content security policy directive: "style-src 'self' *.github.com *.bootstrapcdn.com *.jsdelivr.net *.twitter.com *.googleapis.com *.google.com dmjwor2go9n1u.cloudfront.net". either 'unsafe-inline' keyword, hash ('sha256-cwe3bg0vyqoidnakbb_btdkhul49qzuwgncmpgny5zw='), or nonce ('nonce-...') required enable inline execution. i have hunch has part of script: style = ['&#173;','<style id="s', mod, '">', rule, '</style>'].join(''); when click chrome console link me error placed around here: <style id="s',v,'">',e,"</style>"].join(""),u.i...

Rails Routing Incorrectly links to show.html -

i'm learning rails , have encountered behavior don't understand. i'm trying create simple crud app. on 'new' view after data entry fields , submit button trying add link go page (i'll call 'fnord'). instead of linking fnord, it's going show.html. given rails convention based wonder if default behavior of kind, haven't been able figure out triggers or proper way of routing fnord. this rails 3.2.21, ruby 1.9.3. generated model, views , controller using scaffold , started tweaking things. here's controller (minus unrelated actions - index, destroy, etc): class employeescontroller < applicationcontroller def show @employee = employee.find(params[:id]) respond_to |format| format.html # show.html.erb format.json { render json: @employee } end end def new @employee = employee.new respond_to |format| format.html # new.html.erb format.json { render json: @employee } end end ...

ios - BOOL vs. bool on iOS7 -

in ios came across problem bool vs. bool. i know 1 bitfield , other integer. however following code behaves differently on ios7 , ios8: self.nativationitem.rightbarbutton = _editbutton; //where editbutton uibarbuttonitem. _editbutton.enabled = _some_nsarray.count; since count defined nsuinteger , expect 0 (false) or true other value > 0. however, on ios7 when _some_nsarray.count > 0, editbutton disabled on ios8 editbutton enabled! exact same code. another thing if cast _some_nsarray.count "bool" (not capital letters), works on both if cast (bool) works on 8 not 7. any ideas? enabled bool . count nsuinteger . proper code be: _editbutton.enabled = _some_nsarray.count > 0; bool should assigned yes or no values (or equivalent result of conditional expression).

c - XOR maximization using a trie -

i trying solve question- given array of unsigned 32-bit ints, choose 2 in-bounds indices i, j maximize value of a[i] ^ a[j], ^ bitwise xor (exclusive or) operator. example input: 4 2 0 13 49 output: 60 explanation: 13 ^ 49 60 here code #include <stdio.h> void insert(int n, int pos, struct node *t); int find(struct node *p1, struct node *p2); struct node *alloc(); struct node{ int value; struct node *left; struct node *right; }; int main() { int t; scanf("%d", &t); while (t--) { int n; scanf("%d", &n); struct node root; root.value = 0; root.left = root.right = null; while (n--) { int num; scanf("%d", &num); insert(num, 31 , &root); } int max = find(&root, &root); printf("%d\n", max); } return 0; } void insert(int n, int pos, struct nod...

swift - How do I call a function from another scene? -

my game unlocks level every-time beat level. problem im having when user beats level 1 want show button of level 2 thats in gamescene. when call function unlockleveltwo() in level1.swift file doesn't show in gamescene.swift file. doing wrong? //gamescene.swift func unlockleveltwo() { let fadein = skaction.fadeinwithduration(0.5) leveltwo.position = cgpointmake(self.size.width / 2.0, self.size.height / 2.2) leveltwo.zposition = 20 leveltwo.setscale(0.8) leveltwo.alpha = 0 leveltwo.runaction(fadein) leveltwo.name = "leveltwo" addchild(leveltwo) } //level1.swift if firstbody.categorybitmask == herocategory && sixthbody.categorybitmask == goldkeycategory{ //calling function gamescene unlock leveltwo button. var gamescene = gamescene() gamescene.unlockleveltwo() } this function: if firstbody.categorybitmask == herocategory && sixthbody.categorybitmask == goldkeycategory{ ...

redhat - vmware-toolbox-cmd Command not found -

i'm working redhat vm indicates vmware tools osps installed , running, since vmware tools status in vsphere "running (3rd-party/independent)". have verified vmware tools daemon, vmtoolsd , running running following command ... # pgrep -fl vmtoolsd >> 6048 /usr/bin/vmtoolsd however, whenever try run vmware-toolbox-cmd command, says command not found. vm missing has vmware tools osps installed not have command it? there no gui interface called vmware-toolbox vmware player 5 (and other newer products), per installing , configuring vmware tools: the graphical user interface vmware tools, called vmware tools control panel , available notification area in guest operating system, has been deprecated you can find settings toolbox, "update automatically", in graphical user interface of vmware player on host (as in player -> manage -> virtual machine settings -> options -> vmware tools). as vmware-toolbox-cmd doesn't anyt...

java - Is there a way to fill out the console with print statements like matrix numbers? -

i'm trying make intro game i'm making want cooler text games. i'm not sure if awkward question there way me "fill" console numbers starting top left , spreading down , right, way until numbers hit bottom right corner? gives feeling random numbers being generated , sort of gives cool look. there possible way accomplish task? i'm thinking loops , such i'm not sure if works. cool number method below public void coolnumbers(int width){ for(int i=0; i<width; i++){ system.out.println(); for(int j =0; j<width; k++){ system.out.print("cool number here"); } } } note: replace "cool number here" actual cool number prefer.

street address - Dealing with Long 60 Character Addresses from Amazon B2B Orders -

Image
amazon allows extremely long addresses (60 characters), apparently validation. example screen shot: a cursory shows ups , fedex labels limit addresses 35 characters. we received addresses of 60 characters b2b partner selling through amazon, our system takes 35 characters. receive data through purchase order in edi 850 format. does each company automated shipping amazon have write address manipulation routines make data fit? or there ways print extremely long address fedex , ups? i don't want limit question 1 language or technology. i'm wondering conceptual issues , how people handle in general.

sql server - Does Persisted Computed Column need to update all rows or just affected rows? -

Image
in stackoverflow article , understand persist mean , advantages , disadvantages. however, tried research deeper cannot find "update" one. here scenario (tl;dr version below): have order table , orderdetail table, in diagram: the orderdetail.subtotal computed column, simple fomula: ([price]*[quantity]) the order.total computed column, formula: ([dbo].[calculateordertotal]([id])) , , here function: alter function [dbo].[calculateordertotal] ( @orderid int ) returns int begin declare @result int; select @result = sum(od.subtotal) orderdetail od od.orderid = @orderid; return @result; end tl;dr : order , orderdetail updated, inserting. need query usually, though not inserting. if check subtotal , total persist , since of operations won't affect subtotal field of row, sql server know database need update affected record, or have recompute record of order table? or bad? p.s: using sql server 2008 in case matters. co...

css - How to animate an image as it grows from the width of a container to the full viewport width? -

i have container div image inside of it. when user clicks image, want grow fill viewport width. works me, want animate smoothly grows, not. how can make image grow smoothly centre of page, rather growing in situ until touches right edge of viewport, , jumping left , continuing until fills viewport? here's example (you can try on codepen ): html: <div> <img id="expandableimage" src="https://placekitten.com/g/500/200"> </div> css: div { width: 50%; margin: 0 auto; } img { width: 100%; cursor: pointer; position: relative; } .fullsize { animation-duration: 1s; animation-name: zoom-in; animation-fill-mode: forwards; } .smallsize { animation-duration: 1s; animation-name: zoom-out; } @keyframes zoom-in { { width: 100vw; position: relative; left: calc(-50vw + 50%); } } @keyframes zoom-out { { width: 100%; } { width: 100vw; position: relative; left: calc(-50v...

ios - tableView cellForRowAtIndexPath method not getting called -

func tableview(tableview: uitableview, cellforrowatindexpath indexpath: nsindexpath) -> uitableviewcell { print("wtf getting hit...") let cell = tableview.dequeuereusablecellwithidentifier("cell") as! uitableviewcell cell.textlabel?.text = self.funlists[indexpath.row] print("this better getting hit") return cell; } for reason method isn't getting called. i have set following uitableview.delegate=self uitableview.datasource=self uitableview.registerclass(uitableviewcell.self, forcellreuseidentifier: "cell") and have included, class viewuniversitylist: uiviewcontroller, uitableviewdelegate, uitableviewdatasource { there might several reason this. of them : if using tableview in viewcontroller file, should add uitableviewdelegate , uitableviewdelegate delegates, : class viewcontroller: uiviewcontroller,uitableviewdelegate, uitableviewdelegate { ... } if have created tablevi...

javascript - ASP.NET MVC5, JSON, popup partialView - set DropDownList selected -

i want set ddl selected item item inserted in popup page. used script sample here - http://www.advancesharp.com/blog/1126/search-sort-paging-insert-update-and-delete-with-asp-net-mvc-and-bootstrap-modal-popup-part-2 in jsonresult see inserted value (checking in debug mode breakpoint), need setting value selected in ddl in main page. public actionresult workplaces(int id = 0) { var workplace = new work(); return partialview("workplaces", workplace); } [httppost] public jsonresult workplaces(work work) { if (modelstate.isvalid) { db.works.add(work); db.savechanges(); return json(new { success = true }); } return json(work, jsonrequestbehavior.allowget); } model classes public class person { public int id { get; set; } [display(name = "person name")] [required(allowemptystrings = false, errormessage = "name required")] public string name { get; set; } ...

osx - What is the best way to show the content below the NSWindow? -

Image
here ui mock up: the blue background screen, , red nswindow, , build nsview? (yellow) on top of nswindow. nsview transparent, can shows live information behind red nswindow. best way implement nsview? suggestions? thanks. ***one more remarks, yellow view not need transparent, need use analysis. so, if can raw data or transfer nsimage great. my 2 cents. let view nsimageview. can draw background clear - (void)drawrect:(nsrect)rect { [[nscolor clearcolor] set]; nsrectfill(rect); } convert whatever draw in there image using [nsbitmapimagerep initwithfocussedviewrect:] . work?

sockets - The meaning of Java's DatagramChannel.write() -

i found code using datagramchannel.write() . code asked host ip , port before connected , allow sending (via datagramchannel.write() ). being new network programming, seemed odd wouldn't request destination ip/port. why not? oracle's documentation states this method may invoked if channel's socket connected, in case sends datagrams directly socket's peer. what mean "the socket's peer"? datagramchannel part of java.nio package. take parameter bytebuffer send connected channel. before trying send should connect using inetsocketaddress, takes host ip , port parameter. connect(socketaddress remote) --> connects channel underlying socket. can socket datagramchannel because channel non blocking io used read/write purpose. socket peer's nothing remote machine.

java - Unable to start Tomcat7 on 32 bit Ubuntu 14.04 -

i'm running virtualbox of 32-bit version of ubuntu 14.04. when attempting run sudo service tomcat7 start following message. start-stop-daemon: unable stat /usr/lib/jvm/java-t-openjdk-amd64/jre/bin/java it returns saying server has started. after running service tomcat7 status following: tomcat servlet engine running pid notice there no pid shown, doesn't make sense me. regardless, ends in servlet not running when attempt navigate localhost/. i have no idea why looking 64 bit java on 32 bit install. have else (to knowledge) installed properly. i've uninstalled/reinstalled tomcat , java no avail. any appreciated. check version of java using java -version. architecture of java. make sure have installed 32 bit jre properly. (my recommendation use oracle jre instead open jre). try download tomcat site .tar.gz. extract somewhere in system. locate startup.sh script ,by default present in bin folder of tomcat, , execute script. hope helps!!

Is there an upload API for Google Photos (photos.google.com)? -

does google photos app, released on may 28, 2015, have api allows uploading of photos? app seems build on picassa , google+. can 1 of apis can used upload google photos? by looks of google photos based off same system google+ handled photos through picasa web albums data api. edit: came across question while trying develop using google photos. working on application transfer stuff dropbox on google photos. i can confirm google photos indeed use picasa web albums api. api data storage related photos. drive , google+ make use of data api persist photos. looking @ picasaweb.google.com can see redirects google+ , shows collection of of photo. you can experiment looking on protocol guide can further experiment using oauth 2.0 playground through picasa api.

java - Direct standard output of dynamically compiled & executed code -

background information: i used javax.tools.javacompiler compile code dynamically memory. i used custom class loader load , execute dynamically compiled code. my question let's provides following code: package cs.compile; import java.util.arrays; public class foo { private static int[] nums = new int[] { 1, 2, 3, 4, 5 }; public static void main(string[] args) { system.out.println(getwords() + " " + arrays.tostring(nums)); } public static string getwords() { return "hello world!!!"; } } when execute main() via reflection, works fine. standard-out , standard-error results execution , save them in variable can return them result. i'm not sure how think, once class loaded, shares same standard-out , standard-error rest of application. there standard way of dealing perhaps? don't want direct entire application's output streams away, i'm not sure how target new class. since you compiling it, can c...

actionscript 3 - as3; stop bg sound after replay game; avoid overlapping sound -

i've made little quiz school project. stuck sound issues. want play background sound when player hit start btn on start screen. after game finished, can replay it. when come start screen sound still playing und when hit start btn again, sounds overlapping. best be, after clicking replay btn sound stops. , when click start btn sound start again. code start screen far: stop(); var bgsound:sound = new bgsnd(); var bgchannel:soundchannel = new soundchannel(); start_btn.addeventlistener(mouseevent.click, start_quiz) function start_quiz(event:mouseevent):void{ nextframe(); bgchannel = bgsound.play(); } function rebtnf(event:mouseevent):void{ gotoandstop(1); bgchannel.stop(); } the replay btn start function rebtnf. works frame 1, sound continues play. can me? hope so! one love, monkeycel

sql server - Error occur while there is no row at position 0 -

imports system.data.sqlclient imports system.data public class window1 private sub btn_click(sender object, e routedeventargs) handles btn.click dim cmd sqlcommand = new sqlcommand("select * tencmpc1 qnumber='1';", new sqlconnection("server=(localdb)\projects;database=master;uid=sa;pwd=12345;")) try cmd.connection.open() dim adp new sqldataadapter(cmd) dim dt new datatable() adp.fill(dt) txt1.text = dt.rows(0)("qnumber").tostring() txt2.text = dt.rows(0)("topic").tostring() txt3.text = dt.rows(0)("umcq").tostring() txt4.text = dt.rows(0)("usq").tostring() txt5.text = dt.rows(0)("ulq").tostring() txt6.text = dt.rows(0)("emcq").tostring() txt7.text = dt.rows(0)("esq").tostring() txt8.text = dt.rows(0)("elq"...

PHP array custom looping -

i want create custom toc(table of contents) generated array. example array values looks : $angka = array(1,11,12,13,2,21,22,23); when values containts more 1 digit (11,12,13,21,22,23, etc) should categorized "sub". otherwise, should categorized "non-sub". desired output should https://jsfiddle.net/thekucays/azordcv5/2/ in order achieve that, loop array, check current index, previous index, , next index length. code looks this <?php $angka = array(1,11,12,13,2,21,22,23); $hitung = count($angka); $keys = array_keys($angka); echo "<ul>"; foreach(array_keys($keys) $k){ if(strlen($angka[$keys[$k]])==1){ echo "<li>ini bukan sub</li>"; } else if(strlen($angka[$keys[$k]])>1 && strlen($angka[$keys[$k-1]])==1){ //buka sub baru echo "<li><ul>"; echo "<li>ini buka sub</li>"; } else if(strlen($angka[$keys[$k]])>1 &...

julia lang - Updating vector to avoid excess memory use -

i have function returns vector. since call function many times, want update vector provide rather create new vector. avoid use of memory , increase speed. the original code looks like: function!(prob1,pi,prob0) prob1=pi'*prob0 return prob1 end of course creates new prob1 vector each time. i've attempted amend in 2 different ways: function!(prob1,pi,prob0) in 1:length(prob1) prob1[i]=pi[:,i]'*prob0 end return prob1 end #or function!(prob1,pi,prob0) in 1:length(prob1) prob1[i]=dot(pi[:,i],prob0) end return prob1 end however, both run slower original code although use less memory. suggestions improving performance time great. you don't need define function, there 1 (albeit undocumented): at_mul_b!(prob1,pi,prob0) should give want.

machine learning - What is the advantage of the paperboat format in performance optimization of ML? -

the paperboat format claims provide better dataset representation machine learning routines. i'd understand nature of optimization. understand using integer representation model attributes means faster processing of data set, other improvements. also, how tune ml algorithm work file format. i don't know if format provides better representation, can speculate why can more efficient. first, state @ format description, "having data of same precision consecutive enables hardware vectorization."; consider wikipedia : "vector processing techniques have since been added modern cpu designs". second, format allows mix sparse , non-sparse features, since sparse features placed consequently, possible take them sparse matrix , optimize methods learning conjugate gradient. how tune ml algorithm work file format? what mean ml algorithm tuning? learning algorithm doesn't know , doesn't need know file format of dataset; , can't inc...

Running a C++ program in Windows vs Linux -

i've been told teacher homework (a simple program, chose code in c++) must runnable in linux. here's said exactly: "...you should include readme file contains command lines should run cut-and-paste. if used c, then $ gcc –o 2010-11649-hairpin 2010-11649-hairpin.c $ 2010-11649-hairpin –input filename –l 200 –m 4 –h 20 " where -l 200 , -m 4 , parameters of program. i've coded in windows, , have little experience running programs command line, i'm not sure need make sure program can run in linux. can me figure out need do? i've written program, need make sure works when ta tries run in linux. first of have try executing instructions on linux. if have written program in standard c/c++ compile , run on linux fine. once less basic parts, have big chances have used os specific headers , might not work easily. when compiling c++ program under linux, want use g++ c++ compiler in gcc . depending on program, replacing gcc g++ in exam...

Inject parameters to constructor through annotation in Spring -

i using spring boot annotation configuration. have class constructor accepts 2 parameters (string, class). fruit.java public class fruit { public fruit(string fruittype, apple apple) { this.fruittype = fruittype; this.apple = apple; } } apple.java public class apple { } i have class needs autowire above class injecting parameters constructor("iron fruit",apple class) cook.java public class cook { @autowired fruit applefruit; } the cook class need autowire fruit class parameters("iron fruit",apple class) the xml configuration looks this: <bean id="redapple" class="apple" /> <bean id="greenapple" class="apple" /> <bean name="applecook" class="cook"> <constructor-arg index="0" value="iron fruit"/> <constructor-arg index="1" ref="redapple"/> </bean...

html2canvas - After conversion of div into canvas the images gives white spaces at the bottom -

i using html2canvas convert div canvas. div contain table , each td contain image. canvas getting created every image shows white space @ bottom of it. is there other way convert div canvas? yes, here's 1 alternative using html2canvas render all/part of webpage. you can use "headless browser" on server capture webpage image. headless browser can render contents of webpage image without security restrictions apply html2canvas. i recommend phantomjs because uses webkit , therefore delivers compatibility modern browsers: http://phantomjs.org/screen-capture.html

tsql - T-SQL filter on external join -

Image
using schema below, write query lists total value of sales customers bought item sales person same middle initial them. query should return single result. the quantity , price columns both ints . sales - employee link on employeeid - salespersonid . something should work: select sum(s.quantity * p.price) totalsales sales s join products p on s.productid = p.productid join customers c on s.customerid = c.customerid join empleyees e on s.salespersonid = e.employeeid c.middleinitial = e.middleinitial

java - Force test on extension of abstract class -

i have abstract class has test coverage. want make sure extensions of class pass tests of abstract class. there way ensure code using junit? all method didn't changed in sub-classes checked in test of abstract class. method not changed don't need tested again under scope of extending classes. if method override vary bad decision apply same tests on them might have different business logic. hence if inherit class should write own tests methods had overridden. this point of inheritance change or add logic business logic.

sql server - Drop temp table if it exists on SQL Azure -

is there better way drop temp table on azure sql ? begin try drop table #custommap end try begin catch end catch maybe there no need drop temp tables on azure sql since tables dropped when session ended. this if (object_id('#candidates')) not null begin drop table #candidates; end; or this if (object_id('tempdb..#candidates')) not null begin drop table #candidates; end; does not work. in azure sql database can use drop if exists (die) syntax: create table #temp (id int) drop table if exists #temp

java - Is it truly never okay to call Component.getGraphics? -

madprogrammer made comment here stating should never ever use component.getgraphics, agree with: in virtually situations, wrong. but take case of class created years ago. i'm posting think relevant code. can find full code here public class mousedragoutliner extends mouseadapter implements mousemotionlistener { private class myrunnable implements runnable { public void run() { graphics g = mcomponent.getgraphics(); if (g == null) { return; } graphics2d g2 = (graphics2d) g; stroke s = g2.getstroke(); g2.setstroke(dash_stroke); int x = math.min(mstart.x, mend.x); int y = math.min(mstart.y, mend.y); int w = math.abs(mend.x - mstart.x); int h = math.abs(mend.y - mstart.y); if (w == 0 || h == 0) return; g2.setxormode(color.white); if (mcustomshape != null) { rectangle r = mcustomshape.getbounds(); affinetransform scale = affinetransform...

javascript - Invert scrolling direction in browser -

i tried using onwheel -event this: event.preventdefault(); $('#mydiv').scrolltop -= event.deltay; but there 2 issues code: it works in chrome in firefox scrolling unnatural (as far know firefox use smooth scrolling default , code breaks it) i want invert scrolling not mouse keyboard added : not similar the question because want scrollbar move opposite direction.

django - Python: Mock doesn't work inside celery task -

this question has answer here: why python mock patch doesn't work? 2 answers i want use python mock library testing django application sends email. test code: # tests.py django.test import testcase class mytestcase(testcase): @mock.patch('django.core.mail.mail_managers') def test_canceled_wo_claiming(self, mocked_mail_managers): client = client() client.get('/') print(mocked_mail_managers.called) mocked_mail_managers.assert_called_with('hi, managers!', 'message body') first example - without tasks # views.py django.views.generic import view django.core.mail import mail_managers class myview(view): def get(self, request): mail_managers('hi, managers!', 'message body') return httpresponse('hello!') second example - tasks # views.py dj...

razorengine - ASP.NET Razor templates editable by users - remove @ for security reasons -

i made multi-user blog engine uses great asp.net razor template engine. users able edit page templates , compose them custom tags {{blog_post_name}} {{blog_post_comments_list}} then tags {{...}} replaced using regex appropriate razor code. all usage of razor syntax done inside {{...}} custom tags not editable users. so user can edit blog post templates beside custom {{...}} tags composed from. what way restrict razor syntax in user defined templates? i don't want user @(viewmodel.db.dropalltables()) inside template of blog post, must have access @(something...) inside tags not editable users. as now, before user saves template remove @ user edited template , replace tags razor content. but users can @viewmodel.something , still calls razor logic... i'm thinking of removing @ symbols user template prevent it, not allow user css @media-queries , use email@addresses.com in template. last thing did - changed regex finds symbols delete user templates...

Execute php script inside a javascript script -

i've got problem using javascript (as i'm pretty new language) my problem : i've got javascript script adds form fields when click on button, , change name incrementing it. data stored array. when i've saved filled fields, need them , show them <input type="text" value="<?php $myvalue[] ?>"/> . problem is, need javascript file, , don't know how can interpret stuff inside php script. here's i've tried : var counter = 1; var limit = 10; var new_div = '<?php echo json_encode($arrayspecialite['+ counter +']); ?>'; function addinput(divname){ if (counter == limit) { alert('you cannot add more than' + counter + ' fields'); } else { var newdiv = document.createelement('div'); newdiv.innerhtml = 'specialité ' + (counter + 1) + ' <br><input type="text" name="specialite[]" id="specialite[]"" value="...

docker - does the FROM directive in a dockerfile allways pull the latest version of an image -

if have dockerfile: from ubuntu/latest and ubuntu update image in public registry. when run docker build . , use ubuntu got first time or pull new version? no, not. from directive use whatever happens available in local image cache, unless pass --pull docker build .

excel - SUMIF and multiple sheets -

i searching multiple sheets string, once string found copies mergeddata sheet. in column 1 payment number, instance 50 . column 2 work order number 11111 . columns "3,4,5,6,7,8" or other information. "9,10,12" £ values. when data copied on there multiple instances on work order number in column 2. need have sumif find duplicates in column 2 , sum columns "9, 10 & 12". i have managed code sumif working can't seem work after data has been copied over. what need happen is, when click button searches string, , have copy mergeddata sheet, , on same button click perform sumif function, after data has been copied. any assistance can provide appreciated! this code using copy data multiple sheets one: private sub commandbutton1_click() dim firstaddress string, whatfor string dim cell range, sheet worksheet dim ssheetswithdata string, ssheetswithoutdata string dim lsheetrowscopied long, lallrowscopied long dim bfound boolean dim soutput ...

data warehouse - Aggregate Transformation vs Sort (remove Duplicate) in SSIS -

i'm trying populate dimension tables on regular basis , i've thought of 2 ways of getting distinct values dimension: using aggregate transformation , using "group by" operation. using sort transformation while removing duplicates. i'm not sure 1 better (more efficient), or 1 adopted more in industry. i tried perform tests using dummy data, can't quite solid answer. p.s. using select distinct source not option here. my first choice correct in source query if possible. realise isn't option, sake of completeness future readers: first check whether had problem in source query creating duplicates. whenever distinct seems necessary, first see whether there's problem query needs resolving. my second choice distinct - if possible - because 1 of cases quicker resolve in sql in ssis; realise that's not option you. from point, you're getting situation might need try out remaining options. aside using aggregate or sort in ssi...

multithreading - Running javascript function on background while receiving push notification? -

i know 1 has been asked before, not context of push notifications . i'm developing app using ionic/cordova sends push notifications clients, new video messages them watch. videos not going streamed transferred client-side (not call), thought of implementing background javascript function store video on client-side when , while push has been received. i have looked on web-workers , multithreading needs client-side running. javascript code has event listener when pushes being received, of course not executed until app being opened. so question is, possible? i'll appreciate words of advice on matter, thanks! i did in app using signalr push notification. app. chat app. client x can send rich text message pictures or video client y. when client x send message, calls signalr server , server save message in server sql , save picture or video in web server. if client y offline, message during next online. if client y on-line: case 1: online in foreground: sig...

java - Different JDBC Driver version -

in application have created oracle datsource. datasource used ojdbc6.jar. when test datasource getting below information on console. database product name : oracle database product version : oracle database 11g enterprise edition release 11.2.0.3.0 - 64bit production jdbc driver name : oracle jdbc driver jdbc driver version : 11.1.0.7.0-production in second application have created datasource same database same ojdbc6.jar. when testing thic datasource getting below information on console. database product name : oracle database product version : oracle database 11g enterprise edition release 11.2.0.3.0 - 64bit production jdbc driver name : oracle jdbc driver jdbc driver version : 9.2.0.1.0 why there difference between jdbc driver version ? creating datasources in ibm web console. issue facing second data source select throwing below exception, while works fine first data source. java.lang.classcastexception: java.lang.long incompatible java.lang.string @ oracle.jdbc...

Matlab - How to check the existence of a handle -

is there way check if handle exists or not? like: if didnt declare handle, want 0 output , else 1. i tried ishandle,isvalid,isfield,isempty don't work on "non-existent field" receive error if didnt declare handle.. "reference non-existent field 'sp'." if try "exist name" function works variables not handles so: handle.a=figure; exist handle.a; returns 0 while handle.a=figure; a=handle.a; exist returns 1 but i'm looking for: handle.a=figure; exist handle.a ans=1 %without setting handle: exist handle.a ans=0 i hope post understandable. thank help! klaus let me rephrase: assigning handle field of structure. want test whether there valid handle in field, , guard against wrong: (1) there's no field, (2) it's empty, (3) it's array instead of scalar, (4) it's not handle, (5) it's not valid handle. thus: tf = isfield(handle,'a') && isscalar(handle.a) && ishandl...

hyperlink - postLink() in cakePHP 3.x -

i created crud operations in cakephp 3.x. deleting records using postlink() function. $this->form->postlink("<i class='fa fa-remove'></i>", ['action' => 'delete', $role->id], ['escape' => false],['title' => 'delete', 'class' => 'users'])]); it doesn't set class delete icon. need set class name delete icon. can create own dialog box. if removed escape attribute means create class doesn't display icon. changed order of escape , class not working. please me did use proper ide? did check amount of attributes may use postlink()? documentation states: postlink($title, $url, $options). why using forth then? of course 1 ignored. so should instead: $this->form->postlink( "<i class='fa fa-remove'></i>", // first ['action' => 'delete', $role->id], // second ['escape' => false, ...

html - Position center with float left and with, but it's not centered, how? -

i want centered few blocks, in row 3 next each other , row beneath 3 blocks in row. here html , css. @ moment not next each other in row. @ jsfiddle https://jsfiddle.net/fop5q28x/4/ <div id="engagement"> <img src="img/engagement.jpg" alt="engagament" /> <h2>engagement</h2> <p>content automatisch doorplaatsen</br> naar uw youtube, facebook of </br> twitter kanaal</p> </div> <div id="conversie"> <img src="img/conversie.jpg" alt="conversie" /> <h2>conversie</h2> <p>van kijkers naar lid, klant koper of</br> actieve deelnemer. juist niet alleen</br> voor grote organisaties</p> </div> <div id="elearning"> <img src="img/elearning.jpg" alt="elearning"/> <h2>e...

android - Slide to delete with rotation -

i need remove view rotation using on touch event. view not lightweight: contain web browser , other elements. i implemented slide delete without rotation, , works not fast, works. after adding rotation... very slowly. i looking fast method remove rotation. as understand, can read bitmap screen, hide view , paint bitmap on canvas. think, method should works fine. my question is: what library can use? what screen rotation (i must clear canvas, remove bitmap, restore view, , reset touch events)? maybe can use analog of internal drag , drop? (hmmm, idea, how make fullsize shadow , animate action "moving out of screen"?) how solve such problems? update mohammed ali: can read bitmap of view , draw on canvas . opaque shadow drag , drop , shadow size ...