Posts

Showing posts from March, 2015

c# - Converting a LINQ result to 2D string array -

i have linq query selects list of teamids , team names populate drop down list. query looks this: var teams = db.teams.where(t => t.isactive) .select(t => new {t.teamid, t.teamname}); however, want result set in form of 2d string array, since that's function populates ddls requires. know can use loop , build array, i'd prefer it, if possible in 1 step. is there similar this? string[][] teams = db.teams.where(t => t.isactive) .select(t => new {t.teamid, t.teamname}) .to2darray(); kind of: string[][] teams = db.teams.where(t => t.isactive).select(t => new[] {t.teamid, t.teamname}).toarray();

arrays - How to use xpath in Postgres to align XML elements -

this query: with x (select '<promotions> <promotion promotion-id="old-promotion"> <enabled-flag>true</enabled-flag> <searchable-flag>false</searchable-flag> </promotion> <promotion promotion-id="new-promotion"> <enabled-flag>false</enabled-flag> <searchable-flag>false</searchable-flag> <exclusivity>no</exclusivity> <price>100</price> <price>200</price> <price>300</price> </promotion> </promotions>'::xml t ) select xpath('/promotions/promotion/@promotion-id', t) promotion_id, xpath('/promotions/promotion/enabled-flag/text()', t) enabled_flag, xpath('/promotions/promotion/exclusivity/text()', t) exclusivity, xpath('/promotions/promotion/price/text()', t) price x for elements exclusivity , price

Retaining check box values after the form is submitted in PHP -

but when form submitted not retain check boxes selected. instance if select , checked 2 check boxes how keep them checked after form submitted? thanks. below have. <form method='post' action=''> <?php $sqlbrands="select * brands"; $runbrands=mysqli_query($db, $sqlbrands) or die ("sql error"); $norow=mysqli_num_rows($runbrands); $brndtable = "<table border='1' cellspacing='0' cellpadding='1' id='brndtable1' class='brndtable1'>"; $brndtable .= "<thead><tr><th class='brt11'>brand name</th><th class='brt21'>variant</th><th class='brt31'>sku</th><th class='brt41'></th></tr></thead>"; $brndtable .= "<tbody>"; while ($rek = mysqli_fetch_array($runbrands)) { $w

Work around SQL array? -

i have form has 6 different inputs: form_no varchar2, form_ver number, org_no varchar2, item_no varchar2, form_type varchar2, line_no number these inputs stored temp table. need build function takes temp variables temp table validation. need use array hold variables. i pretty new sql. have had experience in , other coding languages. have realized there not array in sql. wondering if me started or understand how around not using array, , able finish it. --temp table variables put in insert temp table values (t_form_no, t_max_form_ver, t_org_no, t_item_no, t_form_type, t_line_no, --function validation_form --need have array here takes in temp variables temp table --then have validation scripts placed here if trying same functionality array temp table can work fine. here how. create table #foo (fooid int not null identity (1,1), field1 varchar(20), field2 varcha

asp.net - Request.Url.Host identical to Request.Headers["host"]? -

i've read conflicting things on this: in asp.net (and mvc), request.url.host return host header request? i've seen code checks request.headers["host"] first, degrades using request.url.host if there problem, don't understand why needed if identical. they're not identical. httprequest.headers["host"] gives direct access client-to-server http header. httprequest.url rebuilt asp.net , use incoming request's host: header default, there internal setting usehostheaderforrequesturl , if set false asp.net use httprequest.headers["server_name"] instead, under circumstances uses value of "127.0.0.1" instead.

curl through proxy syntax -

i don't understand how read general syntax. want request url through our proxy , requires specific host, port, username, , password. don't know how figure out protocol is. want curl through proxy. based on helpfile below, guess line should be: curl -x [whatever-my-protocol-is://]my-host-which-i-know[:my-port-which-i-know] -u my-username-which-i-know[:my-pass-which-i-know] http://www.google.com is right? how figure out protocol? relevant info man: -x, --proxy [protocol://]host[:port] use proxy on given port --proxy-anyauth pick "any" proxy authentication method (h) --proxy-basic use basic authentication on proxy (h) --proxy-digest use digest authentication on proxy (h) --proxy-negotiate use negotiate authentication on proxy (h) --proxy-ntlm use ntlm authentication on proxy (h) -u, --proxy-user user[:password] proxy user , password --proxy1.0 host[:port] use http/1.0 proxy on given port solved: ignore "["

php - Compiled binaries VS interpreted code in python -

i'm planning use python build couple of programs used services, run php code later on. in terms of performance, faster, compile python code binary file using cx_freeze or run python interpreter each time run program? deployment environment: os: arch linux arm hardware: raspberry pi [700mhz armv6 cpu, 256mb ram, sd card filesystem] python interpreter: python2.7 app calls frequency: high you need test it, because there's no single right answer. cx_freeze wrap bytecode executable, vs. interpreter reading cached .pyc on disk. in theory packaged executable quicker because it's reading fewer files, on other hand interpreter quicker because in disk cache. there's little choose, , whatever difference is, it's not down "compiled" vs. "interpreted".

sql server 2008 r2 - Alternative to calling stored procedure for multiple records -

i have ssrs report displays summary table of records. after click on 1 of records, goes individual report of record has multiple lines on configurable. now have add column in summary table report displays line numbers checked on individual report. there scalar function in database used determine whether line checked based on guid of record , internal label string given line. there stored procedure gets line number displayed on report database. so getting line numbers display on summary report, planning on calling udf each record in stored procedure gets records summary report. there problem in case since cannot call stored procedure function. need call stored procedure gets line number display each record, since line numbers can be unique different records. i thought of converting function stored procedure mean need call each record require while loop or cursor. not sure whether loop best possible solution case. cannot change stored procedure gets line numbers function si

sql - Joining a nested mysql query with field from another table -

i have table integers , parameters: date timestamp 123 2013-07-22 16:33:17 123 2013-07-22 16:34:47 234 2013-07-20 16:33:15 332 2013-07-24 16:33:37 422 2013-07-21 10:13:11 422 2013-07-22 14:53:12 and run following query number of distinct data choosing , random piece of distinct data: select count(distinct(data)) count, (select data data_table date(timestamp) >= '2013/07/22' , date(timestamp) < '2013/07/23' group data order rand() limit 1) data data_table date(timestamp) >= '2013/07/22' , date(timestamp) < '2013/07/23' and get: count data 2 123 or count data 2 422 now have table, *text_table*, whith primary key data . looks this: data text 123 "hi" 234 "hey" 332 "bye" 422 "cya" i need query result of previous query, plus text : count data text 2 123 "hi" or count data text 2 422 "cya" i tried:

php - CakePHP Support Legacy URL -

i have legacy url absolutely have support, in format: http://domain.com/page.php?hash=crazymd5hashhere the new version of site being done in cakephp 2.4, want redirect actual controller action , pass hashed parameter. what's best way of accomplishing in cakephp? i use .htaccess file rewritecond %{request_uri} ^/page.php$ rewriterule ^(.*)$ /controller_name/ [qsa,l,r=301]

c# - membership provider, change password returning false -

is there way full message response changepassword method? need find out why it's returning false. never has in past, current password correct , emailresponse variable. membershipuser u = membership.getuser(emailresponse); bool changed = u.changepassword("password~123", txtpassword.text); if (changed){ //code emitted }

php - error parsing XML file to google maps (XML Parsing Error: junk after document element) -

i have problem xml file loads google maps markers. map works postal codes doesn't work others. these xml files. first 1 works fine. second 1 doesn't. gives "xml parsing error: junk after document element" error. www.soshapal.com/maptst.php?lat=45.5001031&lng=-73.57686610000002&radius=5km&country_id=2&city_id=30&section_id=2 www.soshapal.com/maptst.php?lat=45.4932559&lng=-73.57964709999999&radius=5km&country_id=2&city_id=30&section_id=2 can help? your xml creation script attempting inform of errors: <br /> <b>warning</b>: domelement::setattribute() [<a href='domelement.setattribute'>domelement.setattribute</a>]: string not in utf-8 in <b>/home/vozemg0/public_html/soshapal.com/maptst.php</b> on line <b>44</b><br /> <br /> <b>warning</b>: domelement::setattribute() [<a href='domelement.setattribute'>domeleme

cordova - How to add app icon within phonegap projects? -

i created new phonegap (v 3.0.0-0.14.0) project default config.xml , added ios , android platforms. the config contains paths platform icons. i have overwritten default icons ios , android path , name still matches pngs. when running in simulator icons don't show up. have looked in xcode tells me "resources" folder icons still contains phonegap default icons. same android. what doing wrong? how can add custom app icons ios , android phonegap? thanks my config.xml <icon src="icon.png" /> <icon gap:density="ldpi" gap:platform="android" src="res/icon/android/icon-36-ldpi.png" /> <icon gap:density="mdpi" gap:platform="android" src="res/icon/android/icon-48-mdpi.png" /> <icon gap:density="hdpi" gap:platform="android" src="res/icon/android/icon-72-hdpi.png" /> <icon gap:density="xhdpi" gap:platform="android" src=

Ruby: How do I stop execution and print a string in a loop? -

i writing rake task. thing want stop execution of task when if keeper.has_trevance_info? && candidate.has_trevance_info? true. want print another record has info! in log , stop task. how that? raise or throw ? billing_infos.each |candidate| unless keeper.nil? raise "another record has info! manually compare billinginfo ##{keeper.id} , ##{candidate.id}" if keeper.has_trevance_info? && candidate.has_trevance_info? else keeper = candidate end end you don't want use exception handling exit task. can use 'abort' or 'exit'. so code this: billing_infos.each |candidate| unless keeper.nil? if keeper.has_trevance_info? && candidate.has_trevance_info? puts "another record has info! manually compare billinginfo ##{keeper.id}" exit end else keeper = candidate end end or: billing_infos.each |candidate| unless keeper.nil? abort("

c# - Close Main Form -

i developing simple app using c# windows forms. main form open form, dont want both forms. want when second form opens first form closes. since first form main using this.close(); after showing second form close both. used instead private void btnsubmit_click(object sender, eventargs e) { frmdata qs = new frmdata(); qs.show(); this.windowstate = formwindowstate.minimized; this.showintaskbar = false; } private void frmdata_formclosed(object sender, formclosedeventargs e) { application.exit(); } i want know if there other way this. any appreciated. do not pass main form argument application.run : application.enablevisualstyles(); application.setcompatibletextrenderingdefault(false); mainform frmmain = new mainform(); frmmain.show(); application.run(); thus able close when showing form: private void btnsubmit_click(object sender, eventargs e) { frmdata qs = new frmdata(); qs.s

SQL Server 2008R2 Express upgrade to SQL Server 2012 Express -

i have sql server 2008 r2 express installed. upgrade sql server 2012 express. i using 64 bit system (windows 7 home premium). is there wizard can upgrade? checked few places on web not sure option choose. thank in advance. as documented , upgrade supported sql server 2008 r2 sp1 express sql server 2012 express. install 2008 r2 sp1 , , run installation of 2012 express normally. should pick , offer upgrade. operating system supported .

jquery - Populate jsTree from external JSON file -

i've been experimenting jquery.jstree library , need help. please advise me on how read json_data external .json file. $("#treedemo").jstree({ "plugins" : [ "themes", "json_data", "ui", "types" ], //"json_data": { // "ajax" : { // "url" : "series.json" // } //}, "json_data" : { "data" : [{"data":"series 1","children":[{"data":"season 1","children":[{"data":"episode 1.avi","attr":{"rel":"file"}},{"data":"episode 2.avi","attr":{"rel":"file"}},{"data":"episode 3.avi","attr":{"rel":"file"}}],"attr":{"rel":"folder"}},{"data":"season 2","children":[{&q

objective c - Adding key/value Pairs results in keys with null values -

i'm having issue dictionary timestamps changes values null . keys fine, if switch key value , vice versa. no matter order, values end null , keys end should. here's code. it's xml parser. building dictionary has array of codes keys , array of timestamps values. keys , values parallel arrays representing categories. all variables allocated , initiated elsewhere. imports header file has of these variables properties. @property (strong, nonatomic) type variablename; in main file has line @synthesize variablename . also, has variablename = [[type alloc] init]; . thank help! - (void) didstartelement (elementname passed xml tag) { //tells if in dance categories if ([elementname isequaltostring:@"categories"]) { iscategory = yes; // tells we're ready start reading } else if ([elementname isequaltostring:@"category"] && iscategory) { oncategory = yes; // } } - (void) foundcharacters (curre

iis 7 - What file extension should I set to cache for my asp.net mvc4 application? -

i have been reading various approaches tuning iis7 , 1 of course caching files @ server level. articles detail setting rules file extension (css, js, asp)... dumb question, file extension (other css, js, png) should set asp.net mvc4 project, not render file extensions @ runtime? you want output caching within mvc app: improving performance output caching (c#)

How to add properties (markers, geopoints, etc...) to a Google Android Map v2 created programmatically -

the code used this: private googlemap mmap; mapfragment mmapfragment = mapfragment.newinstance(); fragmenttransaction fragmenttransaction = this.getfragmentmanager().begintransaction(); fragmenttransaction.add(r.id.rl_map, mmapfragment); fragmenttransaction.commit(); mmap = mmapfragment.getmap(); and shows map inside relative layout (r.id.rl_map), when try put marker with: mmap.addmarker(new markeroptions().position(new latlng(0, 0)).title("hello world")); it gives null pointer exception that because googlemap not yet exist. commit() schedules map created, not created time try calling getmap() . either: switch inflating layout containing mapfragment , can call getmap() after inflation complete, or delay getmap() call later point, or subclass mapfragment , call getmap() , add marker in method onactivitycreated() (basically, called after oncreateview() has completed)

time - If function execute more than x seconds php -

in script use function: function url_exists($url) { if ((strpos($url, "http")) === false) $url = "http://" . $url; if (is_array(@get_headers($url))) return true; else return false; } how can set time limit of execute function @get_headers? need function set_time_limit() works 1 function, not whole script. the function get_headers() doesn't supports timeout or context param. try: ini_set('default_socket_timeout', your_value_in_seconds); this set default timeout value of choice. don't forget reset timeout after operation has finished.

node.js - Sequelize drop table in wrong order -

i using sequelize orm in nodejs app , seems drops table in wrong order when sequelize.sync({force: true}) for example, with: var stationentity = sequelize.define('station', { id: { type: sequelize.integer, primarykey: true, allownull: false}, name: { type: sequelize.string, allownull: false} }) var stationsnapshotentity = sequelize.define('stationsnapshot', { id: { type: sequelize.bigint, autoincrement: true, primarykey: true}, snapshottimestamp: { type: sequelize.bigint, allownull: false} }) stationentity.hasmany(stationsnapshotentity, {as: 'snapshots', foreignkeyconstraint: true, allownull: false}) i following logs after sequelize.sync({force: true}) : executing: drop table if exists `stations`; executing: drop table if exists `stationsnapshots`; executing: create table if not exists `stationsnapshots` (`id` bigint auto_increment , `snapshottimestamp` bigint not null, `createdat` datetime not null, `updatedat` datetime not null, `

sql server - access report field pulling from not null column error without NZ() function -

i working on converting access database sql server backend. i've got of working, 1 thing haven't been able figure out yet on 1 of reports run, few fields show #error! field's control source is: =dsum("[customerminutes]","qryoutagesummarybydaterange","nz([cityrelated])= 0") it works fine shown, takes lot longer load report , cityrelated field not null field, feel though shouldn't need use nz() function. have opened query in datasheet view , there appropriately isn't nulls. more happy provide more detail, don't know other information should provide. or general direction appreciated! the database function (dsum, etc.) fussy use of brackets. try this. =dsum("iif([customerminutes] null,0,[customerminutes])","[qryoutagesummarybydaterange]","[cityrelated] null or [cityrelated]=0") if customerminutes never null can use customerminutes first argument. notice square brackets around tab

javascript - Asynchronously update EmberJS Fixture Adapter -

i have table of links i'm trying pull external json file. simple html , handlebars: <table class="table"> <thead> <tr><th>links</th></tr> </thead> {{#each model}} <tr><td> <a target="_blank" {{bindattr href="url"}}>{{title}}</a> </td></tr> {{/each}} </table> and app.js, i'm trying load json asynchronously fixture adapter: var externallinksjson = [{ id: 0 }]; $.getjson('externallinks.json', function(data) { externallinksjson = data; }) .fail(function() { console.error("there error loading externallinks.json"); }); app.externallink.fixtures = externallinksjson; debugging javascript shows externallinksjson variable getting updated successfully, emberjs isn't updating html newly fetch json. i'm trying avoid blocking browser synchronous calls. there way in emberjs bind fixtures updates when values chang

Mongodb combining queries -

i have 2 collections: collection 1: tags { "tagname":"tag1", "tagid":"id1" } collection 2: questions { "questionid":"1". "title":"question title", "tags":tag1 } i want know query can give me tags no questions. in sql select * tags tagname not in (select tags questions) form shell can var c = db.questions.distinct('tags'); db.tags.find({tagname:{$nin:c}}) how do same in java you can't in 1 step current schema. in order this, need store question ids each tag instead of have now. generally, in mongodb store relations between collections "the other way around" compared relational database. example, can store as: tags { "tagname": "tag1", "tagid": "id1", "questions" : [ 1, 3 ] } { "tagname": "tag2", "tagid": "id2" } questions { "questio

api - Multiple charges to equal specified amount using Stripe -

getting confused on how should set up. need charge customer 2 separate amounts on 2 separate dates provide. provided total , able choose 2 dates charged , how on each date. after reading through docs , faqs on stripe's website day, think might know how tackle this. create customer. setup plan specified amount want pay , calculate how many days until should charged using trial_end start on specified date. listen first charge. cancel current plan, take second amount , preferred charge date (stored in database) , create new plan. again, using trial_end charge on correct date provided. listen second charge , cancel plan. is ideal way accomplish want? trying not waste bunch of time, have tight deadline project. appreciate insight. thanks! i'd recommend following. create customer , store customer token store 2 dates in database write script looks 1 of 2 dates , tries run charge customer token. schedule cron or similar scheduler. on charge failure or de

Facebook apprequests blocked when accessed via http protocol -

this error: blocked frame origin " https://www.facebook.com " accessing frame origin " http://www.mysite.com ". frame requesting access has protocol of "https", frame being accessed has protocol of "http". protocols must match. on website dialog box show , select people when click send request nothing happens. request never sent. instead receive same error again. my understanding error code accessing different protocol http vs https so how force facebook go http? tried http://connect.facebook.net/en_us/all.js didn't help. <div id='fb-root'></div> <a href='#' onclick='facebookinvitefriends()'>invite friends</a> <script src='http://connect.facebook.net/en_us/all.js'></script> <script> window.fbasyncinit = function() { fb.init({appid: "app id", status: true, cookie: true, xfbml: true}); }; function facebookinvitefriends(){ fb.ui({

Set android shape color programmatically -

i editing make question simpler, hoping helps towards accurate answer. say have following oval shape: <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <solid android:angle="270" android:color="#ffff0000"/> <stroke android:width="3dp" android:color="#ffaa0055"/> </shape> how set color programmatically, within activity class? note : answer has been updated cover scenario background instance of colordrawable . tyler pfaff , pointing out. the drawable oval , background of imageview get drawable imageview using getbackground() : drawable background = imageview.getbackground(); check against usual suspects: if (background instanceof shapedrawable) { // cast 'shapedrawable' shapedrawable shapedrawable = (shapedrawable) backgr

loops - Iterate with step and apply function -

how can pseudo-c++ code: vector<int> vs = {...}; (i = start; < vs.size(); += step) { vs[i] *= 10; } in clojure? have code: (defn step-do [start step v] (if (< start (count v)) (recur (+ start step) step (assoc v start (* 10 (v start)))) v)) (defn -main [& args] (println (step-do 2 3 (vec (range 1 15))))) or for variant: (defn step-do [start step v] (last (for [i (range start (count v) step)] (assoc v (* 10 (v i)))))) what better? faster? should else? the recur -based version fine , among fastest possible solutions, though might want use transients if it's going operate on larger vectors. as possible alternative i'd suggest using reduce handle looping, input vector passed in initial value of accumulator , reduced sequence provided range step argument. (defn step-do [start step v] (reduce (fn [v i] (assoc v (* 10 (nth v i)))) v (range start (count v) step))) from repl:

android - Keep menuitem animations from overlapping? -

Image
so i'm trying animate refresh menuitem whenever webview loading , whenever activity starts. i'm trying hide forward menuitem whenever it's not necessary. following code works except whenever webview loading , hit or when try more 1 task @ time (clicking through lot of history). whenever happens refresh menuitem tends duplicate, animate, , overlap itself. happens forward menuitem . tends overlapped animated refresh icon. there way keep happening? following code code except whatever not relevant has been trimmed. can me overcome bug? public class tideweb extends activity { private static webview webview; string name = null; menuitem refresh, forward; actionbar ab; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); intent launchingintent = getintent(); name = launchingintent.gettype().tostring(); setcontentview(r.layout.webview); webview = (webview) findvi

visual studio - ClickOnce Security Zones Installation Bug -

i've run haunting bug. i've built c# application (visual c# 2008 express) , have published in past clickonce application deployed zip file. had no problem installing on our customers' computers several months ago, when attempt install application message @ startup: "application cannot started. contact application vendor." when @ details of message see, "deployment , application not have matching security zones." again, problem doesn't show when installing on second computer, shows 2 of our customers (again, problem did not appear on computers few months ago). because can't replicate problem on own systems, difficult approach, haven't thought of publishing settings before today. here further thoughts: -there app.manifest file listed under properties in solution explorer didn't seem there earlier in year. i'm not sure why here , whether there should corresponding file when publish this. -sign clickonce manifests selected. -ena

c# - If else condition on dropdown list on MVC -

i have 2 dropdown list on web application. populated data of 2 dropdown comes database. contain same data. what want if 1 of list selected on first dropdown, should not available on second dropdown anymore. i have following razor syntax: @html.dropdownlistfor(model => model.questions1, (selectlist)viewdata["questions"], "select>>", new { id = "questions1", name = "questions1"}) @html.dropdownlistfor(model => model.questions2, (selectlist)viewdata["questions"], "select>>", new { id = "questions2", name = "questions2"}) the questions came model retrieve database. thanks in advance! in order accomplish this, need store pool of options in javascript object. then, in 'onchange' event each drop-down, re-build options in other drop-down, excluding 1 chosen. here example using jquery: // build javascript array of select names/values var options = new array(); $(

c++ - Strange (?) behavior with virtual keyword with g++ (Ubuntu) -

i going through notes virtual destructors , virtual functions. now, when tried write simple code validate learning, #include <iostream> using namespace std; class base{ public: base (){ cout << "constructing base" <<endl; } void dosomething (){ cout << "inside void " << endl; } ~base (){ cout << "destructing base" << endl; } }; class derived : public base{ public: derived(){ cout << "constructing derived" << endl; } void dosomething (){ cout << "inside derived void " << endl; } ~derived(){ cout << "destructing derived" << endl; } }; int main(){ derived *d = new derived(); d->dosomething(); delete d; } shouldn't expect output so: constructing base constructing derived inside void destructing base because didn't us

html5 - how change image domain using jquery while page loading -

i extracting table url http://rid3201.org/site/club_members2.php?id=mtk3ng== using ajax jquery , append div. cant access images table because of different domain. how can solve problem. content extracted using following code $.ajax( { url: '/member/downloadurldata', type: "post", datatype: "html", async: true, cache: false, beforesend: function (request) { }, success: function (data) { // $('#rdata').load('data #container'); var html = $.parsehtml(data); var table = $(html).find('#container>table:first'); $("#rdata").append(table); }, error: function (xmlhttprequest, textstatus, errorthrown) { }, complete: function (xmlhttprequest, textstatus) { } }); use code $(document).ready(function () { $('table img').each(f

Callback function in c# - WPF -

i have class define class b: b b=new b() i call function in class b.when tried make function- static- got error cause have in function- dispatcher.begininvoke... is there way it? why not pass reference of b. something like public class { public a() { b b = new b(this); } } public class b { public b(a a) { } } or make property of b. something like public class { public a() { b b = new b { mya = }; } } public class b { public mya; }

jquery - how to use this in combination with div element classname -

how use this in combination classname in div tag, $(this).$('.reason_1').show(); if need check whether current element has class reason_1 try: if($(this).hasclass('reason_1')){ $(this).show(); } if need change html then: $(this).html($('.reason_1').html());

How can you two color in plot matlab? -

i want make script show me picture this: https://www.dropbox.com/s/zzx2chi0jbclf66/figura.jpg the code is: a = load('file.txt'); x = a(:,1); y = a(:,4); area(x,y) but not making out 2 colors, think bruh command used not sure? this submission on file exchange might help: http://www.mathworks.co.uk/matlabcentral/fileexchange/7255-areashade

python - What's the best way to insert over a hundred million rows into a SQLite database? -

i have load of data in csv format. need able index data based on single text field (the primary key), i'm thinking of entering database. i'm familiar sqlite previous projects, i've decided use engine. after experimentation, realized that storing hundred million records in 1 table won't work well: indexing step slows crawl pretty quickly. come 2 solutions problem: partition data several tables partition data several databases i went second solution (it yields several large files instead of 1 huge file). partition method @ first 2 characters of primary key: each partition has approximately 2 million records, , there approximately 50 partitions. i'm doing in python sqlite3 module. keep 50 open database connections , open cursors entire duration of process. each row, @ first 2 characters of primary key, fetch right cursor via dictionary lookup, , perform single insert statement (via calling execute on cursor). unfortunately, insert speed still dec

oop - Merging two objects and override empty attributes (PHP) -

i have 2 objects , way our finder function works (i have call twice... 1 config key, value i.e. non multilanguage stuff. , second call multilanguage stuff) makes them this: [config] => array ( [cfg] => config_model object ( [id] => 2 [key] => system.default.main_color [value] => #ff7c11 [deleted] => 0 ) [help] => config_model object ( [id] => [key] => [value] => [id_config] => 2 [name] => hauptfarbe [help] => die hauptfarbe ihres cis. der adminbereich erscheint in dieser farbe. [id_lang] => 1 ) ) i want compine these 2 objects one. code, gets stuff looks this: public static function get($key) { $config['cfg'] = self::find(array('key' => $key), true); $config['

C++ ofstream output to image file writes different data on Windows -

Image
im doing simple thing: writing data of image file stored string image file containing string. std::ofstream f("image.jpeg"); f << image_data; // image_data created using python , copied over, in hex , turned ascii and yet, unexpected happens: becomes: i cannot understand why happening. when use python2.7 data original picture , write new file, works fine. when compile , run program in ubuntu, picture comes out fine. when write large text file (larger image) .txt, file comes out fine. it jpegs on windows fails. original image tried image pgp key packet, came out half of person's head clear , other half messed up. the compiled program doesnt mess of data, since said above, of original picture shown. also, images same size, jpeg format preserved @ least. what happening? using ming2 4.7.2 in code::blocks on windows 7. windows being crazy? you must open file in binary mode: std::ofstream f("image.jpeg&

c++ - I am getting thread1:SIGNAL sigbart in output -

this code, please me ! im using xcode.. want generate sequence polynomial , terms xor'ed , made feedback first input bit since 8 bit done 2^8-1 times.alternate code helpful in advance #include "32bit.h" #include<iostream> using namespace std; int main() { bool input[8]; int n; bool out=0; cout<<"enter no of terms "; cin>>n; int temp1[n]; int gen=0; bool store[255]; cout<<"input power of x in increasing order, omit x^0"; for(int i=0;i<n;i++) cin>>temp1[i]; cout<<"enter key generate "; cin>>gen; for(int m=0;m<255;m++) { store[m]=input[gen]; bool temp2[n]; int var=0; for(int j=0;j<n;j++) { var=temp1[j]; temp2[j]=input[var]; } int c=0; for(int k=0;k<n;k++) { if(temp2[k]%2==1) c++; }

android - How to get chat history from openfier server using asmack? -

i'm developing simple chat application, in have done chat functionality, means app user can send , receive chat messages @ both end. but want chat history of same user, how can that? have tried various things , done lots of r & d don't required information. i'm using asamck lib, , openfire server. added monitoring service plugins on server, next step history?

rspec - how to call a test script from another test script? -

for example : consider log in function .it requried test cases .i want call log in test script test scriptooking making b ?iam using capybara , rspec automation . one possibility write helper method in login_helper example, , call method tests. another possibility create parent class test classes need log in function , put in before(:each) hook.

jquery - How to avoid loosing focus on click of anchor tag? -

i have input type text element , anchor element, don't want loose focus on click of anchor tag if focus on input text element. have tried following not work. html: <input type = 'text' value='click here first' /> <a href='javascript:void(null);' id='nothing'>do nothing</a> jquery code: $('#nothing').bind('click', function(e){ e.preventdefault(); }) above not work me. can tell me missing here? i have faced similar problem try using 'mousedown' instead of click event. here demo <input type = 'text' value='click here first' /> <a href='javascript:void(null);' id='nothing'>clicking not loose focus input field!</a> $('#nothing').bind('mousedown', function(e){ e.preventdefault(); })

hibernate - Mapping JPA for DB2 Spatial -

i working on application based on websphere application server 7 , db2 spatial extender , i'd use jpa data access layer. i've set simple table in database testing purpose: jmtest (id integer | position db2gse.st_point) the challenge map position column (db2gse.st_point) field of jpa entity the working solution found far use hibernate jpa implementation can make use of @columntransformer annotation: @entity @namedquery(name = "getallrecords", query = "select j jmtest j") public class jmtest implements serializable { private static final long serialversionuid = 1l; @id @generatedvalue(strategy=generationtype.identity) private int id; @columntransformer(read="db2gse.st_astext(position)",write="db2gse.st_pointfromtext(?,1003)") private string position; since using websphere 7, comes jpa 1.0 , ibm or openjpa implementation. unfortunately, afraid have stick these (no possibility use jpa 2.0 neither us

rhomobile - integrating images in ruby command -

i have index.erb , want show picture dependent on condition. so, choose if loop, don´t know how call image written in html within ruby command? perhaps it´s easy, don´t have idea, because i´m newbie ;). <%= if (condition 1 < 40) picture 1 elsif (condition 2 > 70) picture 2 else picture 3 end %> <img src="/public/images/picture1.png"> <img src="/public/images/picture2.png"> <img src="/public/images/picture3.png"> please :) i'm not sure if whether want, i'd try anyway... <% if condition 1 %> <img src="/public/images/picture1.png"> <% elsif condition 2 %> <img src="/public/images/picture2.png"> <% else %> <img src="/public/images/picture3.png"> <% end %> change condition 1 , condition 2 conditional code want...

python - Django: adding a random.py file in project dir destroyed the setting's import in WSGI -

this seems weird has happened number of times now. have artitrary .py file added "project/project" directory (same directory settings.py). 2-3 scripts import script. after adding script , restarting apache, django website shows following errors exclusively: error from: raise importerror("could not import settings '%s' (is on sys.path?): %s" % (self.settings_module, e)) [wed jul 24 08:10:03 2013] [error] [client 127.0.0.1] importerror: not import settings 'project.settings' (is on sys.path?): no module named settings any advice? thank you. here directory repr: project/ project/ __init__.py settings.py urls.py views.py wsgi.py something.py app/ __init__.py views.py models.py tasks.py i tried restore site removing something.py , imports, nothing worked. update: in wsgi.py file put print os.getcwd() # prior os.environ.setdefault("d

html - Using the body element as a page wrapper -

yesterday had discussion colleagues using body element wrapper avoid div.page-margins or div.wrapper direct first child of body element. i use body page wrapper , apply sorts of styles width, margin, positions etc. on it. quick search found these 2 blog posts [ 1 , 2 ] confirm me. my colleagues don't idea because there once problems (ie7 + page zoom) , used use div.wrapper inside body. so question is: there code specific arguments against using body element normal container element? addendum : because defining best practices our frontend team want rid of habits- , using div.wrapper because used 1 of habbits :) in addition background-color reasoning provided others, other case can think of necessary have wrapper these days enforce footer "stick" end of document (bottom of viewport when document short). aside these cases, can't think of reason why wrapper required . know i've used wrapper long can remember, chances colleagues me - it's old h

parallel processing - Is the multiprocessing module of python the right way to speed up large numeric calculations? -

i have strong background in numeric compuation using fortran , parallelization openmp, found easy enough use on many problems. switched python since more fun (at least me) develop with, parallelization nummeric tasks seem more tedious openmp. i'm interested in loading large (tens of gb) data sets to main memory , manipulate in parallel while containing single copy of data in main memory (shared data). started use python module multiprocessing , came generic example: #test cases #python parallel_python_example.py 1000 1000 #python parallel_python_example.py 10000 50 import sys import numpy np import time import multiprocessing import operator n_dim = int(sys.argv[1]) n_vec = int(sys.argv[2]) #class contains large dataset , computationally heavy routine class compute: def __init__(self,n_dim,n_vec): self.large_matrix=np.random.rand(n_dim,n_dim)#define large random matrix self.many_vectors=np.random.rand(n_vec,n_dim)#define many random vectors organize

mysql query to avoid multiple queries -

i have table : create table my_table ( col1 varchar(55), col2 varchar(55), col3 varchar(55), 0101 varchar(55), 0202 varchar(55), 0303 varchar(55) ); now want fill table data returned query, 1 example : select col1, col2, col3, group_concat(col4) my_other_table group col1, col2, col3 now query results in line (and more case 1 line enough) : col1 col2 col3 group_concat(col4) ------------------------------------------------- fib100 internet 1megamax 0202,0404 now want check if in concatenated values have column name of not yet populated columns (0101 0202 0303) of table my_table. if true want put x like : table : my_table after insertion col1 col2 col3 0101 0202 0303 ----------------------------------------------------- fib100 internet 1megamax x my question : there way same query ?? thank hope you. i've changed names of columns (you can't use numbers c

python - QAudioOutput strange peak sound at beginning in PyQt4 -

that's general question: how can rid of peak sound @ beginning of sound? here complete code can try out. comparison: if play same sound qsound, not have peak noise. can't use qsound because not work on ubuntu. if playing sound in player vlc, there no noise @ beginning. here sound: http://www.file-upload.net/download-7876205/delete_2.wav.html import struct, sys, time pyqt4.qtcore import qiodevice, qt, qfile pyqt4.qtgui import qapplication, qwidget pyqt4.qtmultimedia import qaudio, qaudiodeviceinfo, qaudioformat, qaudiooutput class window(qwidget): def __init__(self, parent = none): qwidget.__init__(self, parent) format = qaudioformat() format.setchannels(1) format.setfrequency(48000) format.setsamplesize(16) #format.setcodec("audio/pcm") format.setcodec("audio/wav") format.setbyteorder(qaudioformat.littleendian) format.setsampletype(qaudioformat.signedint) self.

objective c - cocoa code- how to reallocate the buffer in the method which i have used below? -

how reallocate buffer buf , in method have used below? [filedata getbytes: buf length: 1024]; in code have declared buf char n storing 1050 characters in char buf[1050] . you can't "reallocate" buffer on stack, size of defined @ compile time. want use dynamic allocation instead: #define mybuflen 1024 char *buf = (char *)malloc(mybuflen); [filedata getbytes:buf length:mybuflen]; and don't forget free() when you're done it, else leak memory pretty quickly: free(buf);

actionscript 3 - calling movieclip of a class from another class, error#1009 -

i got error: method of null object reference. i'm confused , don't know real cause. got player movieclip on stage has instance of "player_mc", pass thru document class , player class. player.as import flash.display.*; import flash.events.*; public class player extends movieclip { public var myplayer:movieclip; public function player(player:movieclip) { myplayer = player; addeventlistener(event.enter_frame,on_enter); } document.as import flash.display.*; import components.player.player; public class game_main extends movieclip { public var player:player; public function game_main() { player = new player(player_mc); } } now here think problem comes from. have green_enemy movieclip on stage has base class enemy. enemy.as import flash.display.movieclip; import components.player.player; import flash.events.event; public class enemy extends movieclip { var theplayer:player; publ

android - Will ad show up in above config. or it will directly start the next activity? -

new game button in xml on clicking newgame run. <button android:id="@+id/button1" android:layout_width="130dp" android:layout_height="wrap_content" android:layout_alignparentbottom="true" android:layout_alignparentleft="true" android:layout_marginbottom="1dp" android:layout_marginleft="1dp" android:onclick="newgame" android:text="@string/newgame" /> public void newgame(view view) { if (startappad != null){ startappad.show(); startappad = null; } intent intent = new intent(this,mainactivity.class); startactivity(intent); finish(); } question , ad show in above config. or directly start next activity ?? if not please suggest way show ad on clicking button & after start new activity. in advance ( have tried in emulator not show

jquery - How can i revoke a setTimeout variable from an iframe (Javascript)? -

i have problem settimeout , cleartimeout: in index.php: enter code here datevar = new date(); timer = settimeout(function() {myfuncfirst();}, 10000); $(document).click(function(e) { cleartimeout(timer); timer = settimeout(function() {myfuncnext();}, 10000); }); than want use cleartimeout in iframe in myframe.php : cleartimeout(parent.timer); i couldn't but, same code running parent.datevar = new date(); why happening? how can solve that? you can't interact variables within iframe. page loaded inside iframe separate page. to overcome might want ajax talk between 2 pages, between 2 websites.

android - Retrieve leaderboard position in Google play game services -

is there way retrieve position of current user in leaderboard? thanks in advance. i haven't tried myself how ? https://developer.android.com/reference/com/google/android/gms/games/leaderboard/leaderboardscore.html#getrank() public abstract long getrank () retrieves rank returned server score. note may not exact , multiple scores can have identical ranks. lower ranks indicate better score, rank 1 being best score on board. returns rank of score.

c# - ASP.NET Web Api Help Page doesn't show any tips -

Image
i have working pages (start mvc 4 project , web api) , enable documentation , still working. working time , @ api , see this: i can't find out change cause this. tried reinstall package pages didn't help. can cause this? how fix it? edit: helppagearearegistration: public class helppagearearegistration : arearegistration { public override string areaname { { return "helppage"; } } public override void registerarea(arearegistrationcontext context) { context.maproute( "helppage_default", "help/{action}/{apiid}", new { controller = "help", action = "index", apiid = urlparameter.optional }); helppageconfig.register(globalconfiguration.configuration); } } web api routes registration same default. public static class webapiconfig { pub

timer - Before Download Page -

i site. issue when people download files downloads them instead of taking them page before can download them example page timer on it. if tell me how let make them view page before downloading it, appreciated if can me. you can here codding can find codding countdown timer before download link appears : http://www.makingdifferent.com/make-countdown-timer-download-button-link-appears/ cheers !!

Jquery tooltip is not disappearing on click of item -

Image
i using jquery-1.9.1.js , ui jquery-ui-1.10.3.custom.min.js . when mouse on over form element shows tooltip , disappear on mouse out. want vanish toolip on click event of item, because in current scenario shows tooltip button , persist after button click. hence see multiple tooltips on page. need hide them after click.(below screen shot). i used below code not work me $(document).click(function() { $(this).tooltip( "option", "hide", { effect: "explode", duration: 500 } ); }); how resolve pls help. edit i using update panel. create problem? according jqueryui documentation, code changes how closes. want close http://api.jqueryui.com/tooltip/#method-close . however might have change code bit make work. judging code use delegation (allowing else make tool tip item), instead of applying directly item. according documentation close not work on delegated tooltips. you'll want similar $('.editbuttons'