Posts

Showing posts from May, 2011

C++: Vector of Pointers to Objects from another Vector -

i have 2 classes, similar this: class { public: b* ptr1; } class b { public: std::vector<a*> list; } in main implementation, i'm doing this: int main() { // there lot more objects b objects, i.e. listofa.size() >>> listofb.size() std::vector<a> listofa; std::vector<b> listofb; while (//some loop) { listofb[jj].list.push_back( &(listofa[ii]) ); listofa[ii].ptr1 = &( listofb[jj] ); } } // int main end basically this. lot of objects assigned 1 b object, , these objects stored in pointer vector pointers. additionally, each of these objects pointer b object belong to. context, i'm doing connected components algorithm run-length-encoding (for image segmentation), class line segments , class b final objects in image. so, pointers of vector in class b point objects stored in regular vector. these objects should deleted when regular vector goes out of scope, right? i've read vector of pointer in class b requires w...

html5 - Add class "active" to Actionlinks generated by loop in ASP.NET MVC5 -

i've written button group using actionlinks filter products. want add "active" class clicked button. how this? <div class="btn-group" role="group" aria-label=""> @html.actionlink("all categories","index",0,new { @class = "btn btn-default" }) @foreach(var category in viewbag.allcategories) { @html.actionlink((string) category.name, "index",new { categoryid = category.categoryid}, new { @class="btn btn-default"}) } </div> thanks!

associations - How can I set up a static form for adding associated records in Rails? -

i have following models i'm using... game class game < activerecord::base has_many :workout has_many :participations end participation class participation < activerecord::base belongs_to :player belongs_to :game end workout class workout < activerecord::base belongs_to :player belongs_to :game has_many :measurables end measurable class measurable < activerecord::base belongs_to :workout end workout nested resource player . usually, create workout record on player 1 @ time. add measurable s workout using gem nested_fields_for allow me add/remove 1 measurable @ time, 1 player @ time. i'm trying build form user edit multiple measurables every player participating in game. example form player | height | weight | hand span | player 1's name [input box] [input box] [input box] player 2's name [input box] [input box] [input box] player 3's name [input box...

mysql - SQL. Unique and Primary Key -

my requirement having table of products cannot have similar vendor, product , version @ same time. but, want table referenced on table primary key, distinct vendor, product version use unique . create table products ( vendor varchar(100), product varchar(100), version varchar(30), unique (vendor, product, version, cve) ); but way cannot reference product_id , want in table: create table product_cve( product_id int, cve varchar(14), foreign key (product_id) references products(product_id), foreign key (cve) references vulnerabilitiescve(cve) ); , thing can that create table products ( product_id int not null auto_increment, vendor varchar(100), product varchar(100), version varchar(30), primary key (product_id) ); this way, going end having duplicated products... the solution simple: create table products ( product_id int auto_increment vendor varchar(100), product v...

python - Why is appengine memcache not storing my data for the requested period of time? -

i have employees stored in appengine ndb , i'm running cron job via taskque generate list of dictionaries containing email address of each employee. resulting list looks this: [{"text":"john@mycompany.com"},{"text":"mary@mycompany.com"},{"text":"paul@mycompany.com"}] the list used source data varing angular components such ngtags ngautocomplete etc. want store list in memcache angular http calls run faster. the problem i'm having values stored in memcache never last more few minutes though i've set last 26 hours. i'm aware actual value stored can not on 1mb experiment hardcoded list of employees contain 3 values , problem still persists. the appengine console telling me job ran , if run job manually load values memcache they'll stay there few minutes. i've done many times before far greater amount of data can't understand what's going wrong. have billing enabled , i'm not on q...

php - Can someone explain how date("YW", strtotime("2016-01-02")); returns “201653”? -

date("yw", strtotime("2016-01-02")); returns “201653” year ok week 2015 php iso-8601 compliant dates: the purpose of standard provide unambiguous , well-defined method of representing dates , times, avoid misinterpretation of numeric representations of dates , times, particularly when data transferred between countries different conventions writing numeric dates , times. this means first week of year defined as: the week year's first thursday in if 1 january on monday, tuesday, wednesday or thursday, in week 01. if 1 january on friday, saturday or sunday, in week 52 or 53 of previous year (there no week 00). this means january 2nd of 2016 not in week 1 of 2016 far php concerned. if use o flag date() iso-8601 year wilol return 2015: echo date("ow", strtotime("2016-01-02")); // outputs: 201553 demo one way may want consider checking if month january , week number 53 first week of new calendar ye...

How to not use loops & IF-statements in R -

i have 2 dataframes in r, 1 big imcomplete (import) , want create smaller, complete subset of (export). every id in $unique_name column unique, , not appear twice. other columns might example body mass, other categories correspond unique id. i've made code, double-loop , if-statement , work, slow: for (j in 1:length(export$unique_name)){ (i in 1:length(import$unique_name)){ if (tostring(export$unique_name[j]) == tostring(import$unique_name[i])){ export$body_mass[j] <- import$body_mass[i] } } } i'm not r know bad way it. tips on how can functions apply() or perhaps plyr package? bjørn there many functions this. check out.. library(compare) compare(df1,df2,allowall=true) or mentioned @a.webb merge pretty handy function. merge(x = df1, y = df2, by.x = "unique_id",by.y = "unique_id", all.x = t, sort = f) if prefer sql style statements library(sqldf) sqldf('select * df1 intersect select * df2') easy imp...

javascript - Adding 3rd party JS libraries to Ionic within the proper workflow -

i have been using jquery mobile hybrid app past few months , wanted exposure ionic , angular.js atempting rebuild it. jqm app relies on xml2json.js , unfamiliar cordova, bower, gulp, node.js , several of other tools used build , deploy ionic apps. is there right way, or right place add xml2json.js when build gets pulled in automatically? the answer question use bower, required bit of setup. install bower (i'm on mac, may not need sudo) sudo npm install -g bower if behind firewall (like @ work) before installing need run npm config set strict-ssl false fix unable_to_verify_leaf_signature after installing bower again if behind firewall need following git config --global url."https://".insteadof git:// forces bower download modules using http address you need edit .bowerrc in project folder rid of bower specific unable_to_verify_leaf_signature { "strict-ssl": false } after can run install command bower install xml2json --save ...

asp.net mvc validation annotation for int either must be 0 or greater than 100000 -

i have int want validate annotation in model. can either 0 or greater or equal 100000. how can that? thanks as others stated, there isn't 1 out of box aware of, there several people have written custom validation attributes can use. example have used in past lessthan greaterthan validation .

Why aren't these dependencies showing up in maven? -

mvn dependency:tree -x shows: ... [info] +- org.springframework.ws:spring-ws:pom:2.1.4.release:compile [info] +- org.springframework.ws:spring-ws-core:jar:2.2.1.release:compile ... ...and yet when @ pom spring-ws see has dependencies aren't shown here. what's that?? how can force maven show dependencies? first of should figure out dependency party of dependency tree using below command or refer link provided mvn dependency:tree -dincludes=name_of_dependency:name_of_dependecy https://maven.apache.org/plugins/maven-dependency-plugin/examples/filtering-the-dependency-tree.html if not might have been excluded.

regex - How to check on initials with html pattern? -

i'm making database can insert customers. by initials of every forename want check if it's in right order. want as: "t.l.r." dots between every initial. to check this, want use pattern. what got this: <input required="true" type="text" required pattern="[a-za-z]{1}+\.[a-za-z]{1}+\.[a-za-z]{1}+\."> this code doesn't anything. know answer? thanx in advance! you combining {1} means 1, , + means 1 or more. not work. try this: [a-za-z]\.[a-za-z]\.[a-za-z]\. since [] default means 1, can drop {1} this mean need 3 characters in initials, i.k. not count. if want use 1 character, followed dot, , repeated can use this: ([a-za-z]\.)+ also, don't forget add prefix ^ postfix $ match whole string: ^([a-za-z]\.)+$

javascript - Select2 multiple select in django -

i'm having few issues select2 drop-down. needed select 1 item on drop dpwn need have manytomanyfield select2 seemed best option. here original code js $.get('/api/foos', function (response){ $.each(response.foos, function(){ $('#foo').append('<option>'+this+'</option>') }) }) api @require_get def foos(request): return jsonresponse({ 'foos':[x.foo_name x in foo.objects.all()] }) {foos: ["shh", "fgdh", "fgb", "ghfs", "sfgh", "sfgh", "srth"]} this worked nicely single selection. trying convert select2, i'm hitting wall cant seem results drop down $.get('/api/foos', function (response){ $("#set_foo").select2({ multiple:true, placeholder: "select foos"}); ('response.foos'); }) and using same api call fixed it $.g...

java - Ensure capacity of List -

i browsing how create own list , landed on site http://www.vogella.com/tutorials/javadatastructurelist/article.html had below method. private void ensurecapa() { int newsize = elements.length * 2; elements = arrays.copyof(elements, newsize); } i found similar methods in many other sites , understood ensurecapacity does. don't understand why length multiplied 2 (elements.length * 2). there specific reason or vary data type? thanks in advance. doubling capacity of list when it's full done couple of reasons. as @jheimbouch , @user3437460 stated, kinda makes sense intuitively. you'd want increase in proportional amount current size of list. adding few fixed elements @ end each time end being bad big fat list. it's more efficent in general. if don't have idea of size list going (as when designing own array-based list class general use), if double size of list each time, on average on each large set of insertions, each insert take o(1) con...

c# - Rendering SurfaceTexture to Unity Texture2D -

i came simillar questions earlier, weren't clarified , right take advice what's wrong i'm doing in code. so i'm trying rendering surfacetexture android plugin unity texture2d. here's unity code: public class androidhandler : monobehaviour { [serializefield] private rawimage _rawimage; private texture2d _inputtexture; private androidjavaobject androidstreamerobj; private system.intptr _nativeptr; void start () { _rawimage.material.settexturescale("_maintex", new vector2(-1, -1)); initandroidstreamerobject(); } private void initandroidstreamerobject() { androidstreamerobj = new androidjavaobject("makeitbetter.figazzz.com.vitamiousing7.androidstreamer"); int32 texptr = androidstreamerobj.call <int32> ("gettextureptr"); debug.log("texture pointer? " + texptr); texture2d nativetexture = texture2d.createexternaltexture (128, 128...

eclipse - Where is Java 1.8 installed on OS X El Capitan? -

i installed jre-8u72-macosx-x64.dmg this page , installation worked well. however, when type /usr/libexec/java_home -v 1.8 returns: unable find jvms matching version "1.8". /library/java/javavirtualmachines/jdk1.7.0_80.jdk/contents/home does know java 1.8 installed? ps: need install eclipse ide java developers , requires java 1.8+ vm . you should install jdk 1.8, using jre. on os x, installing jre doesn't make available system default available applications. as of january 2016, can download jdk 1.8 mac http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html because oracle tends change urls, link might go dead. best web search "jdk mac" or similar find latest version.

php - Refresh div using ajax -

i need refresh select (by id) when ajax call successful. have no idea how process ajax function : $('#insertform').on('click', function(){ var form_intitule = $('input[name=form_intitule]').val(); $.ajax({ type: "get", url: "lib/function.php?insertform="+insertform+"&form_intitule="+form_intitule, datatype : "html", error: function(xmlhttprequest, textstatus, errorthrown) { alert(xmlhttprequest + '--' + textstatus + '--' + errorthrown); }, success:function(data){ /*here need reload #listeformation*/ } }); }); html.php <div class="form-group"> <label for="nomsalarie" class="col-sm-1 control-label" id="nameselect">formations</label> <div class="col-sm-11"> <select name="listeformation[]" id="listeformation" class="form-control" multip...

datepicker - Android: Getting previous date in DatePickerDialog -

Image
i'm displaying datepickerdialog restricting previous date using datepickerdialog.getdatepicker().setmindate(system.currenttimemillis()); . in case not activating previous dates , restricting previous months user still able select previous date of present month (for understanding see image , code) etdate.setonclicklistener(new onclicklistener() { @override public void onclick(view v) { final calendar mcurrentdate = calendar.getinstance(); int myear = mcurrentdate.get(calendar.year); int mmonth = mcurrentdate.get(calendar.month); int mday = mcurrentdate.get(calendar.day_of_month); datepickerdialog datepickerdialog = new datepickerdialog(eventmyeventedit.this, new ondatesetlistener() { @override public void ondateset(datepicker view, int year, int monthofyear, int dayofmonth) { mcurrentdate.set(calendar.year, year); ...

c# - Generics Inheritance and conversion -

this question has answer here: why cannot c# generics derive 1 of generic type parameters can in c++ templates? [duplicate] 5 answers i have following classes: class item { } class meetingitem : item { } class itemgroup<t> { } now, works without issue: item something; = new meetingitem(); this fails: itemgroup<item> itemgroup; itemgroup = new itemgroup<meetingitem>(); // fails here i'm getting "cannot implicitly convert type ' itemgroup<meetingitem> ' ' itemgroup<item> '" error. isn't i'm doing above (assigning type item , instantiating meetingitem)? what have collection of items in itemgroup class along few other members. , i'm going have collection of itemgroups contain different types of derived items. ideally i'd have item abstract class (maybe interface, might need keep ...

android - pyqtdeploy: add external modules -

is there has experience pyqtdeploy , adding external modules? using pyqtdeploy (version 1.2) pyqt 5.5.1 write application can deployed android device. without external modules, freezing pyqtdeploy works pretty well. however, not sure how can add external modules (not pure python ones) application. in particular, want add external module pycrypto . therefore, downloaded pycrypto sourcecode, compiled android toolchain (from android ndk) , have bunch of *.py , *.so files. how can add them application? my initial attempt add *.py , *.so files (so whole pycrypto module) "other packages" tab in pyqtdeploy. now, when import pycrypto related in application ( from crypto.cipher import aes ) following error message: file: ":/crypto/cipher/_aes.py", line 20 in __bootstrap__ typeerror: 'nonetype' object not callable the _aes.py file error thrown, looks this: def __bootstrap__(): global __bootstrap__, __loader__, __file__ import sys, pkgutil, i...

emacs - Refactoring org files (moving data without breaking links)? -

i'm looking sort of workflow let me move things around freely without breaking links. since use org-store-link or org-capture link anything, i'm considering workflow this: any time org-store-link or org-capture called org file, insert copy of exact link being stored/captured current heading's properties. of course, might have wrapper function insert , calls respective org function on every save, search current file such identifiers not match exact current location. file moves break links, too, script might should run periodically on org files - maybe on emacs start-up. if non-matches found, search backlinks point old identifiers, update backlinks new location, , update identifier new location. a helper function finds headings org-links them, without identifier, me current org files ready system. before started, sound idea, how might improved, , has else done it? org-mode has option assign unique id each entry , use in links. lets links keep w...

javascript - LinkButton on Master Page doesn't fire on Second Child Page in ASP.NET -

i'm creating project in asp.net (framework 4.0). have used asp linkbutton in master page & has 2 page linked (home.aspx & service.aspx). question follows : linkbutton1 works on home.aspx , doesn't work on service.aspx . user.master code follow <ul class="nav navbar-nav navbar-right"> <li> <asp:linkbutton id="linkbutton1" runat="server" onclick="linkbutton1_click" autopostback="true">signout <i class="glyphicon glyphicon-off"></i> </asp:linkbutton> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <span> <asp:label id="lblname" runat="server" text=""></asp:label> </span> <i class="icon-user fa"></i...

java - Drop everywhere in a jpanel -

Image
based on example : https://stackoverflow.com/a/17359895/3259386 i have 2 panels, 1 drag , other drop, drag copy , don't move dragged image. the code is... import java.awt.borderlayout; import java.awt.component; import java.awt.dimension; import java.awt.point; import java.awt.datatransfer.dataflavor; import java.awt.datatransfer.transferable; import java.awt.datatransfer.unsupportedflavorexception; import java.awt.dnd.dndconstants; import java.awt.dnd.draggestureevent; import java.awt.dnd.draggesturelistener; import java.awt.dnd.dragsource; import java.awt.dnd.droptarget; import java.awt.dnd.droptargetadapter; import java.awt.dnd.droptargetdropevent; import java.io.ioexception; import java.net.url; import javax.swing.icon; import javax.swing.imageicon; import javax.swing.jframe; import javax.swing.jlabel; import javax.swing.jpanel; import javax.swing.swingutilities; import javax.swing.transferhandler; import javax.swing.transferhandler.transfersupport; import javax.swi...

dictionary - Making a draggable map with inertia in XNA C# (Custom framework) -

i trying make draggable map inertia,friction, i'm kindda lost right example: http://www.emanueleferonato.com/2016/01/18/how-to-create-a-html-draggable-and-scrollable-map-with-inertia-using-phaser-framework/ this have far: override public void update() { base.update(); if (getstate() == state_dragging) { if (input.mouse.pressed()) { setvelocityx(drag_x - input.mouse.getx()); } } if (getstate() == state_stale) { if (cmouse.pressed()) { drag_x = input.mouse.getx(); drag_y = input.mouse.gety(); setstate(state_dragging); } }}

java - Creating a Class, and writing methods for the STARS program -

i have assignment code methods of intro "stars" program. have of loops figured out print out designs, writing classes them tripped up. i'm still new programming , i'm sure there lots of silly mistakes in code. here's document of stars output public class stars { scanner scan = new scanner(system.in); public int rows; public string part1, part2, part3, part4, part5; public stars(int rows){ } private static string part1(int rows){ (int = 0; < rows; i++) { (int stars = 0; stars < rows; stars++) { system.out.print("*"); } system.out.println(""); } return " "; } private static string part2(int rows){ system.out.println(""); (int = 1; <= rows; i++) { (int star = 1; star <= i; star++) { system.out.print("*"); } system.out.pri...

javascript - PHP echoing a table, appending it to a specific element in the DOM? -

i have code, checks database , returns rows php code containing 4 values (id, playera, playerb, turn, int). i use array build table , append table specific location in dom, dont know how that. i way (get rows via js ajax , use js build , append table), know how, dont want that. is possible create table , append div using php/html/css ? thanks <?php if (isset($_session["userid"])){ $dbmanager = dbmanager::app(); $manager = new manager($_session["userid"]); $gamelist = $manager->getgames(); if ($gamelist) { debug::log("got active games: ".sizeof($gamelist); } else { debug::log("no games"); } } else { debug::log("no user id"); } ?> <!doctype html> <html> <head> <link rel='stylesheet' href='style.css'/> <script src="jquery-2.1.1.min.js"></script> <script src='script.js'><...

javascript - Repeating appended html with json data included -

this bit of learning exercise me please excuse code present. sure better. in following code see have created variable pulling in formatted json data. then, creating function appends block of html. within append, referencing specific pieces of json data displayed. html <table id="jobsearchresults" bgcolor="white" style="border: 1px solid #ddd;width:100%;"> <tbody> </tbody> </table> javascript var json = (function () { var json = null; $.ajax({ 'async': false, 'global': false, 'url': "../data/jobsearchresults.json", 'datatype': "json", 'success': function (data) { json = data; } }); return json; })(); $(jobsearchresults).each(function(index, element){ $('#jobsearchresults').ap...

excel - Are there configuration settings to remember docked toolwindow positions in the VBE? -

i've installed rubberduck add-in . if configure vbe windows can see duck-windows looks lovely when restart excel way before: there way around configuration of vbe persists? yes, possible configure this, no, has not been implemented yet. essentially, involve remembering whether dockable windows displayed when add-in unloaded. in order this, rubberduck store these positions in settings file , display them when loaded. if wish, can create issue this, , team may implement in time next release if has enough support. full disclosure: working on rubberduck team.

Pass php array values as JavaScript array values -

i have php array this. array ( [0] => hal([[br,1],[cl,4]]) [1] => alk([[nc(1),1,2],[nc(1),3]]) ) how pass javascript below. var hal=[["br",1],[cl,4]]; var alk=[[nc(1),1,2],[nc(1),3]]; i write code <script> var data = <?=json_encode($input);?>; //$input name of php array var hal=[data[0].substring(5,data[0].lastindexof(']'))]; var alk=[data[1].substring(5,data[1].lastindexof(']'))]; document.write(hal[0]); </script> the output [br,1],[cl,1] , expected output 1 below.any ideas? thank you. document.write(hal[0]); => ["br",1] document.write(hal[0][0]); => ["br"] if want multiple variables, you'll want loop through array; can grab names using regular expression . if you're trying turn valid data can parse, json string, you're going have awful lot of work; wherever you're getting string better place to. have them pass valid json string instead. <scrip...

javascript - How to persist data in a Service Worker -

as of now, chrome not support passing additional data push notifications received gcm. have execute fetch service worker whenever receive push notification. far, good. but: need include request parameter in http request executed in fetch . how tell service worker parameter? what i've tried far using postmessage tell service worker request parameter: var serviceworkerdata = {}; self.addeventlistener('message', function (evt) { console.log('service worker received', evt.data); serviceworkerdata = evt.data.mydata; }); self.addeventlistener('push', function(event) { event.waituntil ( fetch("http://my.url", { method: 'post', body: 'mydata=' + serviceworkerdata }).then(function(response) { //... }) ); }); why not working but not persistent, i.e. after close browser , open again, serviceworkerdata lost. localstorage not availabl...

vba- parse xml that i go from webserver and write it to excel takeing to much tim -

i trying write excel more 50000 rows etch row have 11 cells it's taking me more them 18 minutes so. can tell me am doing wrong?? seeing of time spending on writing values variant , not actual writing excel thanks itay public sub updateresultssheet() dim ws worksheet: set ws = activesheet dim newbook excel.workbook: set newbook = activeworkbook dim suppdistbranchid string dim suppprodid string dim reportingdate string dim query string dim nodecell ixmldomnode dim rowcount integer dim cellcount integer dim rowrange range dim cellrange range rowcount = 1 query = "http://******:8080/rs_excel_api/dailyinvhist/get/1?" reportingdate = trim(range("parameters!f" + cstr(2)).value & vbnullstring) query = query + "reportingdate=" query = query + reportingdate dim req new xmlhttp req.open "get", query, false req.send dim resp new domdocument resp.loadxml req...

Pulling token from JSON responce in Python -

i learning python , working api mediafire , trying automate simple processes. running bit of confusion after pass post session token. problem not sure how extract token response. here call session token: import hashlib import time import urllib.request token = hashlib.sha1() token.update("calvinrock0406@gmail.comheaven3610255k592k2di4u9uok3e8u9pkfepjfoc809kfutv5z".encode('utf-8')) token_dig = token.hexdigest() urllib.request.urlopen("https://www.mediafire.com/api/user/get_session_token.php?application_id=36102&signature=" + token_dig + "&email=calvinrock0406@gmail.com&password=heaven&token_version=2&response_format=json") response: html = response.read() and here responce call: b'{"response":{"action":"user\\/get_session_token","session_token":"618679cd5046c48fface93dee366a1a07eacfefc5bce88173d5118bb3f128f539602dc54f6d667825a376bc2f86b41a5b1cbe178cd45dfcb4ddfc8e965...

android - App "lost property office" with ViewPager, Fragment, ListView, JSON -

i'm doing lost property office application. consists of four tabs , each tab must display announcement feed uploaded users. clicking on particular item opens new activity derive more information.(well, sort of news feed). take data api site in form of json . did 4 tabs using viewpager, fragment. image fragments have tried place every fragment listview , display data json asyntask. , caused asynctask each fragment called same json in first fragment. may not right. so, please tell me correct move. what used display data listview json how display information on new activity opens when press listview item? send fragment on intent or download json again? how realize adding ads user? if possible, write steps. thank much, glad of help. p.s sorry bad english first of can use simple list adapter able put json data listview, can see tutorial of here . second able see details item in list view can use onlistitemclick , extending listactivity. exampl...