Posts

Showing posts from June, 2014

javascript - How to unit test an asynchronus factory which uses another factory in AngularJS? -

i trying write unit tests databasecontacts factory, , lost how write them, there number of complications. here factory want test: .factory('databasecontacts', function (getdatabasecontactsfromdb ){ return { getcontacts: function(){ var dbcontacts = getdatabasecontactsfromdb.query(); return dbcontacts.$promise.then(function(result){ return result; }); }, removecontact: function (contact){ getdatabasecontactsfromdb.remove(contact); }, addcontact: function (contact){ var addedcontact = getdatabasecontactsfromdb.save(contact); return addedcontact.$promise.then(function(result){ return result; }); } }; }) and here getdatabasecontactsfromdb: .factory('getdatabasecontactsfromdb', function ($resource){ return $resource('http://localhost:8000/contacts/'); }) here's attempt @ setup test: describe( 'd

excel - VBA Cut and Paste Based on Drop Down Lists -

hoping can :) i'm working on spreadsheet has 2 different drop down variables 3-4 options in drop down each. i.e first drop down has option {2-tier, 3-tier, 4-tier, 40-tier} , second can {2-tier, 3-tier, 4-tier}. i'm new vba, , have ever worked sql before, i'm kind of shooting in dark here. basically, based on drop down selected, spreadsheet "copy , paste" pricing grid corresponding other tab, , paste on "set sheet". since there 2 drop downs, imagine columns 8-16 being used first pricing grid , 18 down being used second set of pricing grids. here's kind of have far: sub ifs() if worksheets("set table").range(b3) = "2-tier" worksheets("2 tier mec rates").range(a1, f3).copy destination:=worksheets("set table").range(a7) elseif if worksheets("set table").range(b3) = "3-tier" worksheets("3 tier mec rates").range(a1, f4).copy destination:=worksheets(&quo

r - Libraries not loading when running Rscript from PHP -

i trying run r script php. my php file looks this: exec("rscript fig_lollipop.r"); and r script looks this: library('rpostgresql') #more goes code here... i keep getting following error: error in library("rpostgresql"):there no package called 'rpostgresql' i have attempted searching common answers this, , think might related www-data user, i'm not sure. r script works fine when running terminal. thanks in advance help! rc i ran .libpaths() command in terminal, , discovered additional folder (where of relevant packages stored), compared .libpaths() command run web app. ended copying relevant packages folder listed in web app .libpaths() , , works now. thanks "mrflick" advice! i'm newbie stuff, , thought packages installed users.

ruby - Some code that I don't understand -

i don't understand while true , name = gets(',').chomp(',') , relationship. me, seems infinite loop. explain this? print "enter more names separated commas: " while true name = gets(',').chomp(',') puts "hello #{name}" end it is infinite loop. program never end (except crash on input). breaking down: while true this start while loop condition true loop forever on code end . name = gets(',') see documentation gets . if run program directly, wait "line" of input on stdin (the console/terminal). input read record separator, "," , result assigned variable name . .chomp(',') chomp method on string removes record separator end of string (again, ',' in case). puts "hello #{name}" this prints string "hello #{name}" value of name variable interpolated #{} placeholder. end this ends while loop. if run program , type "mary

awt - How to do 2D shadow casting in Java? -

Image
i'm trying implement 2d shadow casting method in java following tutorial: http://ncase.me/sight-and-light/ i want stick line2d , polygon objects. here main part of code far: (polygon p : quads.polygons) { (int = 0; < p.npoints; i++) { osgctx.setstroke(new basicstroke(0.1f)); line2d line = new line2d.double(mousepos.getx(), mousepos.gety(), p.xpoints[i], p.ypoints[i]); osgctx.draw(line); } osgctx.setstroke(new basicstroke(1.0f)); osgctx.draw(p); } which gives result of this: i confused when comes down building parametric form of lines. don't know how implement math java's methods. point me in right direction, code-wise, implementing this? it's not entirely clear actual question is. there quite operations need when doing sort of graphics programming, , built-in functionality of java2d rather rudimentary here. can create point2d , line2d objects, , have structures available

Vb.Net Dataset table = New DataTable -

i came across 1 programming issue have tried solve follows: dsdataset.tables("promotion") = new datatable. but unfortunately not work because error: property 'item' read only is there away accomplish this? the tables collection of dataset modified using add, remove methods dsdataset.tables.add(new datatable("promotion")) of course, line above requires collection doesnt contain table named "promotion". if have table named "promotion" in dataset need remove before adding new one dsdataset.tables.remove("promotion") dsdataset.tables.add(new datatable("promotion"))

avr - Display ADC result on LCD or Terminal using CodevisionAVR -

my project audio spectrum analyzer, stuck in displaying adc results, either on lcd or on terminal of codevisionavr. the project uses atmega16a, 7.37 mhz external oscillator. ide using codevisionavr. the audio spectrum analyzer takes input through 3.5 mm jack audio cable, signal amplified , filtered in order select frequencies between 0 , 4 khz, , output of circuit connected pa0, channel 0 of adc of microcontroller. for testing, have set adc work on 8 bits (read significant 8 bits), taking internal 2.56v voltage reference. have decoupled aref pin using 10nf capacitor (i change 100nf better noise reduction). adc in free running mode. i stuck in displaying adc results, either on lcd or on terminal of codevisionavr (through uart --- configured using wizard). this function used adc: // voltage reference: int., cap. on aref #define adc_vref_type ((1<<refs1) | (1<<refs0) | (1<<adlar)) // read 8 significant bits // of ad conversion result unsigned cha

php - How to load languages in CodeIgniter only once per session? -

according i've read loading custom languages in codeigniter, language file must loaded in controller, "passed" view. here comes performance issue. every time page called, server must load language file. how can language file loaded once? , use along same session? thanks everyone. francesco load language file (e.g. general_lang.php ) in constructor of default controller this: function __construct(){ parent::__construct(); // other stuff ... $this->lang->load('general', 'english'); } the language file called once (whenever call default controller, whenever start new session)

Object Instantiations couting using composition in c++ -

in more effective c++ meyers has described way count instantiation of objects using object counting base class (item 26). possible implement same using composition technique below . there specific advantage using private inheritance , drawbacks of using composition in case. ps:- have reused code more effective c++ small modification. #ifndef countertemplate_hpp_ #define countertemplate_hpp_ #include <iostream> #include <stdio.h> #include <stdlib.h> template <class beingcounted> class counted { public: static int objectcount(){return numofobjects;} counted(); counted(const counted& rhs); ~counted(){--numofobjects;} protected: private: static int numofobjects; static int maxnumofobjects; void init(); }; template<class beingcounted> counted<beingcounted>::counted() { init(); } template<class beingcounted> cou

Python function is changing the value of passed parameter -

here's example of started mylist = [["1", "apple"], ["2", "banana"], ["3", "carrot"]] def testfun(passedvariable): row in passedvariable: row.append("something else") return "other answer" otheranswer = testfun(mylist) print mylist i'd expected mylist not have changed. i tried remove temporary column, didn't work: mylist = [["1", "apple"], ["2", "banana"], ["3", "carrot"]] def testfun(passedvariable): row in passedvariable: row.append("something else") # i'm finished "something else" column, remove row in passedvariable: row = row[:-1] return "other answer" otheranswer = testfun(mylist) print mylist i think tried use different reference: mylist = [["1", "apple"], ["2", "banana"], ["3", "

apigee - How to extract variable from SOAP request in Edge policy? -

here's policy: <?xml version="1.0" encoding="utf-8" standalone="yes"?> <extractvariables async="false" continueonerror="false" enabled="true" name="extract-operation"> <displayname>extract-operation</displayname> <ignoreunresolvedvariables>false</ignoreunresolvedvariables> <source clearpayload="true">request.content</source> <variableprefix>apigee</variableprefix> <xmlpayload stoppayloadprocessing="false"> <namespaces> <namespace prefix="soapenv">http://schemas.xmlsoap.org/soap/envelope/</namespace> </namespaces> <variable name="operation" type="string"> <xpath>/soapenv:envelope/soapenv:body</xpath> </variable> </xmlpayload> </extractvariables> in trace tool

c++ - Getting random/weird data using Winsock -

i'm new using winsock , see made quick http client (not really) requested index page of website. however, when trying read data received server, not expect. here's example output: ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ̤÷ this happens when connecting website try , trying output contents of recvbuf, data received supposed stored. how data returned winsock? also, don't think it's code because don't errors. i'm pretty sure normal , i'm missing step, searching didn't turn i

javascript - getElementById doesn't work correctly -

here code - http://jsfiddle.net/ec6jt/ <input type="text" id="mytext"> <a href='javascript:elem();'>click</a><br/> <input type="text" id="mytext2"> <a href='javascript:document.getelementbyid("mytext2").value = "my default value";'>click</a><br/> <script type="text/javascript"> function elem() { document.getelementbyid("mytext").value = "my default value"; }; </script> why first "click" link works correctly , second 1 doesn't? why second "click" link erases everything? thanks. instead of this <a href='javascript:document.getelementbyid("mytext2").value = "my default value"; '>click</a><br/> use this <a href='javascript:document.getelementbyid("mytext2").value = "my default value"; return false;&#

android - Open activity or dialog box when i press image i have in my viewPAger -

in root activity have slide show displayed viewpager . in case want open new activity or dialog box or when pressed image on slide show . used onclicklistener , assign picture id , don't feedback . rootactivity.java public class rootactivity extends activity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_root); // image slide show viewpager viewpager = (viewpager) findviewbyid(r.id.view_pager); imageadapter adapter = new imageadapter(this); viewpager.setadapter(adapter); viewpager.setcurrentitem(0); imageadapter.settimer(viewpager, 3, 0); // end image slide show viewpager vp = (viewpager)findviewbyid(r.drawable.ax1); vp.setonclicklistener(new onclicklistener() { @override public void onclick(view arg0) { // todo auto-generated m

javascript - Scrolling a DIV container from certain point -

i need html/javascript. have div id sidemenu , it's positioned left main content, right under header ( screenshot ), , need div start following, when browser's top border touches div... here mocked-up example fiddle: http://jsfiddle.net/mifi79/6bk6q/ essentially, need this: $(document).on("scroll", function (e) { var $body = $("body"), $header = $("header"), $nav = $("nav"), $content = $(".content"); if ($(document).scrolltop() >= $header.height()) { $nav.css({ "position": "fixed", "top": 0 }); $content.css({ "margin-left": "27%" }); } else { $nav.css({ "position": "static" }); $content.css({ "margin-left": "2%" }); } }); hope gets headed in right direction.

sqlite query to add index for results -

i have table include 2 parameters: group_id & name create table inf_table (group_id integer not null, name text not null); insert inf_table(group_id, name) values (1,'aa'); insert inf_table(group_id, name) values (1,'bb'); insert inf_table(group_id, name) values (1,'ab'); insert inf_table(group_id, name) values (2,'aa'); insert inf_table(group_id, name) values (2,'ba'); insert inf_table(group_id, name) values (2,'ab'); insert inf_table(group_id, name) values (2,'bb'); i run query order result group_id , name. " select * inf_table order group_id,name;" , got: 1|aa 1|ab 1|bb 2|aa 2|aa 2|ba 2|bb but, add index each row display index of name inside each group: 1|1|aa 2|1|ab 3|1|bb 1|2|aa 2|2|aa 3|2|ba 4|2|bb how i? thanks you have count rows in same group , have name before current name: select (select count(*) inf_table inf2 inf2.group_id = inf_table.group_id

javascript - How to draw a polygon on google map (V3) and save it? -

this question has answer here: how save google maps overlay shape in database? 2 answers i use google map in project , customize create , drawing polygon , poly-line don't save shapes, , want create polygon on map , save in database, question : how save polygon coords in database? my code: function initialize() { var mapoptions = { zoom: 14, minzoom: 14, maxzoom: 19, center: new google.maps.latlng(35.696282, 51.422946), maptypeid: google.maps.maptypeid.roadmap, maptypecontrol: true, scalecontrol: true, streetviewcontrol: false }; map = new google.maps.map(document.getelementbyid('map-canvas'), mapoptions); drawingmanager = new google.maps.drawing.drawingmanager({ drawingmode: google.maps

php - How do i autogenerate an ID in a form? -

<html> <head> <title>the test</title> </head> <body> <?php require 'dbconn.php'; $db = @odbc_connect ($dbconn, '', ''); if (array_key_exists('id', $_post)) { $sql = "insert landlords (id, landlord, address, contact) values ('$_post[id]','$_post[land]', '$_post[add]', '$_post[con]')"; print '<h2>landlord ' .$_post['id'] .' added</h2>'; print '<p>return @ <a href=admin.htm>admin page</a>'; odbc_exec ($db, $sql); } else { ?> <form action="addlandlord.php" method="post"> <p>create new landlord id:<br><input type="text" name="id" size="30"> <p>enter landlord's name:<br><input type="text" name="land" size="30"> <p>enter landlord's address:<br><textarea name="con&

performance - How do I use a typed array using a shared buffer efficiently in JavaScript? -

in code have object contains series of pixel coordinates. performance of object critical because it's being used in 60fps game output cannot cached. after experimentation , benchmarking, 3d array proved fastest way of implementing when using untyped arrays: var pixelcollection = function() { this.pixels = []; }; pixelcollection.prototype = { add: function(x, y) { var pixels = this.pixels; if (pixels[y]) { pixels[y].push(x); } else { pixels[y] = [x]; } }, each: function(callback) { var pixels = this.pixels; (var y = 0, m = pixels.length; y < m; y++) { var row = pixels[y]; if (row) { (var = 0, mm = row.length; < mm; i++) { callback(row[i], y); } } } } }; in situations, object not fast enough, tried uint8array implementation, using 2d array: var width = 255; var height = 160; pix

javascript - How to to return a value from Ajax call to server -

this question has answer here: why variable unaltered after modify inside of function? - asynchronous code reference 6 answers i make ajax call server retrieve records , return them json object. here code call $(".reply").click(function (){ $.ajax({ url: "/ajax_up/", type: 'get', datatype: "json", success: function (data) { sync_data=json.stringify(data) } }); am trying use returned data construct grid, when pass variable syncd_data have declared global in ajax call, seems undefined. $(document).ready(function(){ var data = source_data; //other code .......................... .......................... but when alert(sync_data) within ajax call below: $(".reply").click(function (){ $.ajax({ url: "/ajax_up/", type:

Java Process - Too short lifetime of the process. (Less than 1s...) -

problem: this.proc.isalive in function make_test return false... don't know why... waits user command... (in case of console) external program: -> l10_z1_external_test target: process should life... l10_z1__test__core.java package bst_test; import java.io.ioexception; public class l10_z1__test__core { public static void main(string[] args) { // build proccess processbuilder pr_1 = new processbuilder("java", "-jar", "../bst.jar"); try { process proc = pr_1.start(); l10_z1__test__c_tester test_engine = new l10_z1__test__c_tester( proc); string[] cmd; string[] result; cmd = new string[] { "add", "remove" }; result = new string[] { "sucess (add) | ", "sucess (remove) | ", "sucess (add) | ", "sucess (remove) | ", "s

r - Rewriting loops with apply functions -

i have 3 following functions make faster, assume apply functions best way go, have never used apply functions, have no idea do. type of hints, ideas , code snippets appreciated. n, t, dt global parameters , par vector of parameters. function 1: function create m+1,n matrix containing poisson distributed jumps exponentially distributed jump sizes. troubles here because have 3 loops , not sure how incorporate if statement in inner loop. have no idea if @ possible use apply functions on outer layers of loops only. jump <- function(t=0,t=t,par){ jump <- matrix(0,t/dt+1,n) # initializing output matrix u <- replicate(n,runif(100,t,t)) #matrix used decide when jumps happen y <-replicate(n,rexp(100,1/par[6])) #matrix jump sizes (l in 1:n){ nt <- rpois(1,par[5]*t) #number of jumps k=0 (j in seq(t,t,dt)){ k=k+1 if (nt>0){ temp=0 (i in 1:nt){ u <- vector("numeric",nt) if (u[i,l]>j){ u[

Reference type List<T> with order by -

i have weird situation, can't explain, can me understand it? understanding, list reference type, mean after change list inside function rating, list changed outside function. in real doesn't change after sorting. there problem misunderstand? class program { static void main(string[] args) { list<user> data = new list<user> { new user { totalscore = 0 }, new user { totalscore = 3 }, new user { totalscore = 4 } }; rating(data); //list data doesnt order descending totalscore } private static void rating(list<user> data) { data = data.orderbydescending(e => e.totalscore).tolist(); } } public class user { public int id { get; set; } public decimal totalscore { get; set; } } list reference type, should not confuse passing argument reference function. default, function arguments in c# passed value. passing data reference value

Best strategy for testing database performance -

i'm evaluating 2 different types of databases in order know 1 has best performance in different scenarios. some of tests i'm planning inserting , selecting large amount of data. how large should data in order better , more consistent comparison?

html5 - Pass angularJS $index into onchange -

i have input file within ng-repeat in angularjs app. need pass $index variable onchange attribute. i'm using onchange , not ng-change because need uploaded object ( see post ) in following code 'uncaught referenceerror: $index not defined' jade code sample: div.input-group(ng-repeat='filename in filenames track $index') input(type='file', onchange="angular.element(this).scope().file_changed(this.files, **$index**)") in onchange attribute, scope accessible via angular.element(this).scope() . that's method use call file_changed() function, , should use same in order have access $index attribute: <input type="file" onchange="angular.element(this).scope().file_changed(this.files, angular.element(this).scope().$index)" /> notice becoming pretty long! solution pass dom element function, , obtain informations it: <input type="file" onchange="angular.element(this).scope().

android - problems with ProgressDialog,RunOnUiThread and ListAdapter -

ok i've written android program has 3 tabs(meals,drinks , dessert) each in own activity fragment.the problem i'm having retrieving list mysql database , displaying list in each tab.i'de ran , executed custom code displays list of items retrieved mysql database in single list,which worked fine.now bringing code program gives me 3 errors 1) pdialog = new progressdialog(mealsfragment.this); says progressdialog(android.context,context) in progressdialog cannot applied com.example.tab.tablayout.mealsfragment 2) runonuithread(new runnable() says "cannot resolve method runonuithread " 3)is list adapter. the initial code used oncreate,but fragment uses oncreateview.i dont know if thats issue. here code mealsfragment.java package com.example.tabs.tablayout; import java.util.arraylist; import java.util.hashmap; import java.util.list; import org.apache.http.namevaluepair; import org.json.jsonarray; import org.json.jsonexception; impor