Posts

Showing posts from February, 2010

java - GC pauses of 5 seconds but mark, sweep and compact take less than 1 second -

i have aix server running jvm process 8 gb heap using gencon gc policy. today had 5s pause time concerning. looked @ event in gc log couldn't figure out time spent. <con event="collection" id="1" timestamp="oct 22 13:34:10 2015" intervalms="0.000"> <time exclusiveaccessms="0.195" /> <nursery freebytes="871692288" totalbytes="966367232" percent="90" /> <tenured freebytes="375809024" totalbytes="7516192768" percent="4" > <soa freebytes="0" totalbytes="7140383744" percent="0" /> <loa freebytes="375809024" totalbytes="375809024" percent="100" /> </tenured> <stats tracetarget="2430736896"> <traced total="2804446392" mutators="2591437504" helpers="213008888" percent="115" /> <cards cl

Adventure game constructor method problems Java -

i'm creating text adventure game in java. i've created exit, room, creature , item class, , i'm instantiating , putting values them in main class. i'm getting problem though: i'm creating exits room, i'm getting compiler error saying constructor exit in class exit cannot applied given types this line of code i'm getting compiler error for: exit exit1 = new exit("exit1", "exit description", "exit transition text"); and in exit class have constructor method: public void exit(string exit, string exitdescription, string exittransition) { this.exit(exit, exitdescription, exittransition); } but every time tell ide (netbeans) correct compiler error, generates in exit class: exit(string exit1, string exit_description, string exit_transition_text) { throw new unsupportedoperationexception("not supported yet."); //to change body of generated methods, choose tools | templates. } so quest

sbt - PlayFramework resolves dependencies every launch -

every time launch app play resolves dependencies. considering happens every single launch takes lot of time... there time had problem 1 lib wasn't unavailable app didn't launch... there anyway configure play/sbt work maven? download dependencies , use local instead resolve every launch? yes, can this. add skip in update := true in build.sbt file stop dependencies resolution. build.sbt looks like ... scalaversion := "2.11.6" skip in update := true librarydependencies ++= seq( javajdbc, cache, javaws, "com.datastax.cassandra" % "cassandra-driver-core" % "2.1.6" ) ... you can read more dependency tuning in typesafe sbt documentation: http://www.scala-sbt.org/release/docs/dependency-management-flow.html btw, documentation says: if no dependency management configuration has changed since last successful resolution , retrieved files still present, sbt not ask ivy perform resolution. i have behaviou

Portfolio Optimization with Matlab and VBA. cell2mat doesn't work -

i trying write macro in vba execute matlab. when opened, matlab uses data stored in excel sheet macro recorded. in vba code recall matlab function , use cell2mat convert data excel matlab. make life easier post code: public sub usa() dim matlab object set matlab = createobject("matlab.desktop.application") matlab.execute ("cd('c:\users\dales\dropbox\esempi')") serie = sheets("sp500").range("b3:ru686") grupposector = sheets("gruppot").range("b3:ru21") gruppomin = sheets("gruppo").range("z11:z29") gruppomax = sheets("gruppo").range("aa11:aa29") ris = matlab.putworkspacedata("prices", "base", serie) ris = matlab.putworkspacedata("grupposector", "base", grupposector) ris = matlab.putworkspacedata("gruppomin", "base", gruppomin) ris = matlab.putworkspacedata("gruppomax", "base", gruppomax) myresult

unicode - Python - Transliterate German Umlauts to Diacritic -

i have list of unicode file paths in need replace umlauts english diacritic. example, ü ue, ä ae , on. have defined dictionary of umlauts (keys) , diacritics (values). need compare each key each file path , key found, replace value. seems simple, can't work. out there have ideas? feedback appreciated! code far: # -*- coding: utf-8 -*- import os def getfilepaths(directory): """ function generate file names directory tree using os.walk. returns list of file paths. """ file_paths = [] root, directories, files in os.walk(directory): filename in files: filepath = os.path.join(root, filename) file_paths.append(filepath) return file_paths # dictionary of umlaut unicode representations (keys) , replacements (values) umlautdictionary = {u'Ä': 'ae', u'Ö': 'oe', u'Ü': 'ue', u'ä

javascript - JS data manipulation -

i have data this: (the real record has far more this) year type quantity 2011 1000 2012 b 1000 2012 c 1000 2012 1000 2015 1000 json: [{year:2011, type:a, quantity:1000},...] and want have result this: (i want every year , every type has record there) year type quantity 2011 1000 2011 b - 2011 c - 2012 1000 2012 b 1000 2012 c 1000 2015 1000 2015 b - 2015 c - is there way this? underscore solution welcomed! vanilla js, includes final sort var yrs = [], types = [], tmp={}; data.foreach(function(item){ // create arrays of years , types if(yrs.indexof(item.yr) === -1){ yrs.push(item.yr); } if(types.indexof(item.type) === -1){ types.push(item.type); } // temp object used in next step holes tmp[item.yr + item.type] = true; }); yrs.foreach(function(yr){ types.foreach(function(type

excel - SUMIFS for multiple criteria -

i have spreadsheet need sum on column based on 3 criteria (employee name, payment option , dates). have formula =sumifs(c2:c10,b2:b10,"jason",d2:d10,"cash") but works regardless of dates. wanted show value today. this link spreadsheet: https://docs.google.com/spreadsheets/d/1hshrfc05s_q9e5c78yreauh8d2obpcrbmtqjo8cpmwq/edit?usp=sharing thanks in advance! you need add third criteria: =sumifs(c2:c10,b2:b10,"jason",d2:d10,"cash",a2:a10,today())

c# - EF Non-static method requires a target -

i've serious problems following query. context.characteristicmeasures .firstordefault(cm => cm.charge == null && cm.characteristic != null && cm.characteristic.id == c.id && cm.line != null && cm.line.id == newline.id && cm.shiftindex != null && cm.shiftindex.id == actshiftindex.id && (newareaitem == null || (cm.areaitem != null && cm.areaitem.id == newareaitem.id))); i targetexception: non-static method requires target when newareaitem null. if newareaitem not null notsupportedexception: unable create constant value of type 'pqs.model.areaitem'. primitive types or enumeration types supported in context. things i&#

c - How do I free up the memory consumed by a string literal? -

how free memory used char* after it's no longer useful? i have struct struct information { /* code */ char * filename; } i'm going save file name in char* , after using time afterwards, want free memory used take, how do this? e: didn't mean free pointer, space pointed filename , string literal. there multiple string "types" filename may point to: space returned malloc , calloc , or realloc . in case, use free . a string literal. if assign info.filename = "some string" , there no way. string literal written in executable itsself , stored program's code. there reason string literal should accessed const char* , c++ allows const char* s point them. a string on stack char str[] = "some string"; . use curly braces confine scope , lifetime that: struct information info; { char str[] = "some string"; info.filename = str; } printf("%s\n", info.filename); the printf call results in unde

c# - SpeechRecognitionEngine recognizers -

i downloaded fr-fr runtime language pack can recognize french speech through program. however, program throws error additional information: no recognizer of required id found. at speechrecognitionengine recognizer = new speechrecognitionengine(new system.globalization.cultureinfo("fr-fr")); en-us , en-gb works because pre-installed system, installed these new language packs still throwing exception. also, if helps, when do foreach (var x in speechrecognitionengine.installedrecognizers()) { console.out.writeline(x.name); } it prints ms-1033-80-desk edit: not possible duplicate because isn't having no recognizers installed, it's c# sapi not seeing have installed pack current language i able work... there step involved. since you're using system.speech, uses installed desktop speech recognition comes windows. error you're getting not because don't have language installed, because didn't install speech re

dns - Pulling docker images behind a proxy -

i have been having trouble using docker whenever on campus' wifi. trying pull or run image needs pulled gives me following error: error while pulling image: https://index.docker.io/v1/repositories/library/redis/images: dial tcp: lookup index.docker.io on 66.170.14.12:53: server misbehaving my research has lead me across this post seems consistent i'm experiencing, proposed fix has not worked. can avoid issue in future? as explained in context (windows, corporate proxy), need set http_proxy environment variables in dockerfile (if dockerfile needs access internet) or in session environment variables ( in .profile or .bashrc ): export http_proxy=http://<user>:<pwd>@proxy.company:80 export https_proxy=http://<user>:<pwd>@proxy.company:80 export no_proxy=.company,.sock,localhost,127.0.0.1,::1,192.168.59.103 note docker 1.9, able leave outside dockerfile build-timeargument passing (merge in pr 15182 ).

HTML: How to output to .txt or xml file -

how i'm trying create survey , out answers text or xml file. possible in html? <html> <head> <title>testing survey application</title> </head> <body bgcolor="#e6e6fa"> <font color=black size=+3>modifying sentiment</font> <hr> add positive adjective: <img adjective src="http://findicons.com/files/icons/2776/android_icons/96/ic_question_mark.png" alt="question" title="adjective: word naming attribute of noun, such sweet, red, or technical." width=20 /> <br> <textarea cols=40 rows=3 name=textbox1></textarea> <p> <hr> <input type=submit value=submit> <input type=reset value=clear> <br> </form> </body> </html> html markup language. used describe elements of web page. if want functionality, such submitting , processing forms, example. need add server-side language, such python , php , ruby , among many

mapreduce - How hadoop decides how many nodes will do map and reduce tasks -

i'm new hadoop , i'm trying understand it. im talking hadoop 2. when have input file wanto mapreduce, in mapreduce programm parameter of split, make many map tasks splits,right? the resource manager knows files , send tasks nodes have data, says how many nodes tasks? after maps donde there shuffle, node reduce task decided partitioner hash map,right? how many nodes reduce tasks? nodes have done maps reduce tasks? thank you. tldr: if have cluster , run mapreduce job, how hadoop decides how many nodes map tasks , nodes reduce tasks? how many maps? the number of maps driven total size of inputs, is, total number of blocks of input files. the right level of parallelism maps seems around 10-100 maps per-node, although has been set 300 maps cpu-light map tasks. task setup takes while, best if maps take @ least minute execute. if havve 10tb of input data , blocksize of 128mb, you’ll end 82,000 maps, unless configuration.set(mrjobconfig.num_maps, int)

html - Inserting a table into a PHP while statement -

Image
i have created wrote php code includes array , while statement. need put results table shown below. tried many different ways had no luck if can point me in right direction grateful. (new php) http://main.xfiddle.com/b5a1cb57/test.php <!doctype html> <html> <head> <link type="text/css" rel="stylesheet" href="main.css"/> <title>loops</title> </head> <body> <?php echo "<b>associative arrays </b><br />"; $prices = array('t-shirt'=>'9.99','cap'=>'4.99','mug'=>'6.99'); echo "<br />"; print_r($prices); echo "<h1>loops</h1><br />"; echo "<b>while looop</b><br />"; echo "<br />"; $shirt_price = $prices['t-shirt']; $counter = 1; while ($counter<=10) {$price2 = ($counter*$shirt_price); echo $counter . ' '

c++ - Reading from an Excel file -

i trying read excel file has 4 columns , 121 rows. tried .csv idea, guess understood wrong because when compile this, gets messed up. how can make sure city gets first cell, country gets second, lon gets third, , lat gets fourth? #include "stdafx.h" #include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream infile; string city; string country; string lat; string lon; infile.open("worldcities.csv"); if (infile.is_open()) { cout << "file has been opened" << endl; } else { cout << "no file has been opened" << endl; } while (!infile.eof()) { infile >> city; infile >> country; infile >> lon; infile >> lat; cout << "city: " << city << endl; cout << "country: " << country << endl; cout << "lat: " << lat << endl;

json - vb net + getting content from a div with htmlagilitypack -

flow: 1. (ok) download json 2. (ok) parse value json object contains html 3. (not ok) display values inside div.countries code: dim webclient new system.net.webclient dim result string = webclient.downloadstring("http://example.com/countries.json") dim values jobject = jobject.parse(result) dim finalhtml string = values.getvalue("countries_html") basically finalhtml variable looks this: <div class="country_name">usa</div> <div class="country_name">ireland</div> <div class="country_name">australia</div> im stuck , dont know how move on. need go on div.country_name , inner_text of it. hope make sense. since finalhtml string contain target div elements, can load string htmldocument object , use bit of linq project divs collection - ienumerable , list<t> , or whatever suitable need- of innertext strings : .... dim finalhtml string = values.getvalue("countries_html&

python - convert itertools array into numpy array -

i'm creating array: a=itertools.combinations(range(6),2) and have manipulate array numpy, like: a.reshape(.. if dimensions is high, command list(a) slow. how can "convert" itertools array numpy array? update 1: i've tried solution of hpaulj, in specific situation little bit slower, idea? start=time.clock() a=it.combinations(range(495),3) a=np.array(list(a)) print stop=time.clock() print stop-start start=time.clock() a=np.fromiter(it.chain(*it.combinations(range(495),3)),dtype=int).reshape (-1,3) print stop=time.clock() print stop-start results: [[ 0 1 2] [ 0 1 3] [ 0 1 4] ..., [491 492 494] [491 493 494] [492 493 494]] 10.323822 [[ 0 1 2] [ 0 1 3] [ 0 1 4] ..., [491 492 494] [491 493 494] [492 493 494]] 12.289898 i'm reopening because dislike linked answer. accepted answer suggests using np.array(list(a)) # producing (15,2) array but op aparently has tried list(a) , , found slow.

c - sizeof dynamic array is not correct -

Image
this question has answer here: how find 'sizeof' (a pointer pointing array)? 15 answers in array there 4 element size should 4bit*4 = 16. (an int data type take 4 bit in system store value.) when ran code got 8 bit size of dynamicarray . #include <stdio.h> #include <stdlib.h> int main(void) { //dynamic arrays save memory creating pointer stores //the beginning of array int *dynamicarray = malloc(20 * sizeof(int)); *dynamicarray = 10; printf("address %x stores value %d\n", dynamicarray, *dynamicarray); dynamicarray[1] = 20; printf("dynamicarray[1] stores value %d\n", dynamicarray[1]); dynamicarray[2] = 45; printf("dynamicarray[2] stores value %d\n", dynamicarray[2]); dynamicarray[3] = 34; printf("dynamicarray[3] stores value %d\n", dynamicarray[3]); printf(

Python sckitlearn linear regression crashes on random iteration -

i random error (not @ same iteration) when running adapted version of sckitlearn plot_robust_fit.py . files needed reproduce can downloaded here . just run reg.py , error. traceback is: traceback (most recent call last): file "/users/geoffroy/git/sfinder_2/reg/reg.py", line 118, in <module> model.fit(x, acluster_y) file "/library/python/2.6/site-packages/sklearn/pipeline.py", line 141, in fit self.steps[-1][-1].fit(xt, y, **fit_params) file "/library/python/2.6/site-packages/sklearn/linear_model/ransac.py", line 301, in fit y_inlier_subset) file "/library/python/2.6/site-packages/sklearn/base.py", line 328, in score return r2_score(y, self.predict(x), sample_weight=sample_weight) file "/library/python/2.6/site-packages/sklearn/linear_model/base.py", line 155, in predict return self.decision_function(x) file "/library/python/2.6/site-packages/sklearn/linear_model/base.py", line 138, in decision_functi

Configuring Hadoop endpoint in a WSO2 ESB outsequence proxy service -

i have set hadoop endpoint outsequence of proxy service in wso2 esb. should convoy ws response hadoop file repository. here syntax put command write file on hadoop: 2-step commands file-writing how implement working proxy executes 2 steps in outsequence saving ws response on hadoop? first, in insequence, can call request url using call mediator. <call> <endpoint> <address uri="http://localhost:9000/services/yourservice"/> </endpoint> </call> next, can extract header above response , set 'to' header next request. use send or call mediator send content using 'default' endpoint (the default endpoint sends message correct address looking @ 'to' header). <header name="to" scope="transport" expression="get-property('redirecturi')"/> example 5 in this page describes how use default (dynamic) endpoin

sql server - Can I create an ambient transaction for testing? -

my current system has rather aggressive data layer creates sqldatabase instance me calling static method. pass in stored procedure name (string) , magic happens. i want try , of crazy system under test , want control in database. having realised structure [test] public void should_do_some_thing() { using (var scope = new transactionscope()) { cleanupdatabase(); setupdatabasedata(); //run test assert.that(someresult,is.equalto("expectedvalue"); scope.dispose(); } } does want (no database changes persist outside test) nicer if set transaction within [setup] method , remove without committing in [teardown] section. is possible? note cannot call methods on command object or whatever... you use testinitialize , testcleanup set up/clean up: private transactionscope scope; [testinitialize] public void testinitialize() { scope = new tran

node.js - JavaScript String concat replaces first character -

task after extracting sql statements log file i'm doing simple string concatenation append ; @ end: var query = line[i] + ";" problem what should like: insert [...]; what like: ;nsert [...] approaches i tried different concatenation mechanisms, seeing appended concatenation fails. for (i in lines) { var txt = lines[i]; console.log(txt); // "insert into" console.log(txt.concat(";")); // ";nsert into" console.log(txt + ";"); // ";nsert into" console.log(txt+=";"); // ";nsert into" console.log(";" + txt); // ";insert into" } extraction script var fs = require('fs'); var array = fs.readfilesync('file').tostring().split("\n"); var result = []; var currentrow; var line; var value; // loop through lines of file for(i in array) { line = array[i]; // if there insert stat

Android database using ORMLITE sqlite -

i have used sqlite database using ormlite.i have declared primary key in database follows:in database fetch values , display in listview. when delete entry.in list view..primary key goes on increasing values. @databasefield(generatedid = true,columnname = "teacher_id") int teacherid; try { toast.maketext(detaillistview.this, "delete entry", toast.length_long).show(); deletebuilder<teacherdetails, integer> deletebuilder=teacherdao.deletebuilder(); deletebuilder.where().eq("teacher_address", set.teacheraddress); deletebuilder.delete(); stud_list = teacherdao.queryforall(); //adapter = new usersadapter(detaillistview.this, stud_list); // list.setadapter(adapter); list.invalidate()

javascript - jQuery click function not working on IDs -

i'm trying jquery things when click div. i've given id (ghost) , when load page , click it, nothing happens. if change script "#ghost" "html" script works. what's wrong syntax here? jsfiddle: https://jsfiddle.net/vl78vr5m/ <body> <div class = "graveyard"> <div id="cont"> <div id="ghost"> <div class="eye"></div> <div class="eye"></div> <div id="tickle"></div> </div> </div> </div> js: alert("does work?"); $('#ghost').click(function(){ alert("the paragraph clicked."); }); you forgot load jquery in jsfiddle. adding works: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> it practice make functions work first when page loaded. can accomplish wrapping in $(funct

php - Remove alt-codes from string -

is there possibility replace alt-code-characters "" in php? example input: hell©Ã³ output should be: hello i've tried preg_replace("/[^a-za-z]+/i", "", $string); edit: the problem have iconv string before because need letters "á" replaced alphanumeric ones, should not deleted because need compare string later. preg_replace change "ke©Ã¡lo" "kelo". need put out "kealo". this can achieved using 2 seperate functions. strtr() first, preg_replace() following strtr() in order while using present preg_replace("/[^a-za-z]+/i", "", $string); code. sidenote: can later add array if needed. 'é'=>'e' example. $string = "ke©Ã¡lo"; // borrowed http://stackoverflow.com/a/3373364/ $unwanted_array = array( 'Å '=>'s', 'Å¡'=>'s', 'Ž'=>'z', 'ž'=>'z', 'À'=>'a',

jsp - Struts2 html checkbox not pre-checked -

<body> <h3>register prize completing form.</h3> <s:form action="register"> <s:textfield name="personbean.firstname" label="first name" /> <s:textfield name="personbean.lastname" label="last name" /> <s:textfield name="personbean.email" label ="email"/> <s:textfield name="personbean.age" label="age" /> <input type="checkbox" checked="checked" /> <s:submit/> </s:form> <input type="checkbox" checked="checked" /> </body> i have jsp above content. checkbox within form not checked whereas checkbox outside form pre-checked. mixing plain html checkbox , non-html elements within struts2 form. here have malformed html putting input tag in form. to resolve it,you can use s:checkbox <s:checkbo

Asciidoctor: how to replace expression in included document? -

given asciidoctor file my-document.adoc content: include::included-document.adoc[] included-document.adoc contains the content of file cannot changed. text *has replaced*. when render my-document.adoc , want have visible content the content of file cannot changed. text has been replaced . is possible without changing included-document.adoc ? my-document.adoc may changed.

How to best shut down a clojure core.async pipeline of processes -

i have clojure processing app pipeline of channels. each processing step computations asynchronously (ie. makes http request using http-kit or something), , puts result on output channel. way next step can read channel , computation. my main function looks this (defn -main [args] (-> file/tmp-dir (schedule/scheduler) (search/searcher) (process/resultprocessor) (buy/buyer) (report/reporter))) currently, scheduler step drives pipeline (it hasn't got input channel), , provides chain workload. when run in repl: (-main "some args") it runs forever due infinity of scheduler. best way change architecture such can shut down whole system repl? closing each channel means system terminates? would broadcast channel help? you have scheduler alts! / alts!! on kill channel , input channel of pipeline: (def kill-channel (async/chan)) (defn scheduler [input output-ch kill-ch] (loop [] (let [[v p] (async/alts!! [kill-ch [out-ch (preproces

javascript - Meteor Exception in template helper -

i have problem in application, error on line <pre><code>type: 'point'</code></pre> error: exception in template helper the structure in locs geojson structure. this code on client side: nextlocation: function(){ var geodata = geolocation.latlng(); var nextloc = locs.find({ location: { $near: { $geometry: { type: 'point', coordinates: [geodata.lng,geodata.lat] }, $maxdistance: 100000 } } }); console.log(nextloc); return nextloc; } the code in template: {{nextlocation._id}} i have no idea why there error.

ruby on rails - Send thank you message with mail_form -

i'm using mail_form + simple_form gems send email myself after user submits "contact us" form on site. submit fields database. here working fine. i'd able send second email user's email address "thank you" message , other copy directly after submission. know message posted flash, email user better in case. can please provide guidance on how done based on code below? thanks! model: page.rb class page < activerecord::base include mailform::delivery attribute :name, :validate => true attribute :company attribute :email, :validate => /\a([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i attribute :message attribute :nickname, :captcha => true def headers { :subject => "new lead composites first", :to => "myemail@myemail.com", :from => "myemail@myemail.com" } end end controller: pages_controller.rb class pagescontroller < applicationcontroller

bash - Sorting Row and Column from Table of Number -

i'm not sure whether ask or not, if did forgive me. i have chunk of random number (my_number) 1 2 5 8 3 4 3 7 5 4 7 2 2 3 7 7 9 1 i want sort them both row , column: by row 1 2 3 4 5 8 2 3 4 5 7 7 1 2 3 7 7 9 by column 1 2 5 4 3 1 2 3 5 7 7 2 3 7 7 8 9 4 so far, i've tried while read line; tr, $'\n' < <(printf -- "%s" "$line") | sort -g | tr $ '\n', | sed 's/,$/\n/'; done < my_number and tried basic command like sort -g my_number sort -n my_number however, apparently every 1 of them sort first column, rest still randomly scattered. is idea sorting both row change column possible? in fixing code or new code highly appreciated. thanks going from: 1 2 5 8 3 4 3 7 5 4 7 2 2 3 7 7 9 1 to this: 1 2 3 4 5 8 2 3 4 5 7 7 1 2 3 7 7 9 is not terribly difficult, correcting original attempt: while read line; tr ' ' $'\n' <<< $line | sort -g | tr 

C++: 2 templates vs. 1 template specialization on complex class -

i have custom rather complex data structure form: class root; class tree { public: ... // lots of members here, child access etc exactbar *bar() { return mbar; } exactqux *qux() { return mqux; } private: ... // lots of members here exactbar *mbar; exactqux *mqux; }; class root : public tree { // root manages memory tree nodes! ... private: memoryspace<tree> mnodes; memoryspace<exactbar> mbars; memoryspace<exactbar> mquxs; }; the purpose of program build tree requires exact types above. requires massive amounts of memory , i'm literally stretched 32-bit limit. want to, once tree built, convert whole tree inexact type not faster, takes less memory. but of course keep functionality tree offers methods, , of course other algorithms work on tree . writing new class out of question. templates seem appropriate here. however, i'm wondering 2 ways of writing new, templated class. 1 obvious way is template <typ

comments - Using DocBlocks on PHP, Should I use @throws when I do not handle errors with execpetion? -

i have class handling errors, , not using try-throw-catch mechanism. when commenting code uses class, should use the @throws tag though not throwing anything? edit (try make question more clear): my question if @throws tags means error occure when using code , handling in way, or means error occure , handling using throw keyword specifically? after reading the documentation , realize not spelled out. the documentation on @throws suggests if throw keyword present @ inside block of code, should documented each type of exception thrown regardless of whether or not you're handling or not. so if have try { throw new exception(); } catch (exception $e) { // handled! } put @throws entry in docblock.

regex - Remove xml tag that contains specific value with sed -

i have configuration file <configuration> <property> <name>name1</name> <value>value1</value> <description>desc1</description> </property> <property> <name>name2</name> <value>valuetoremove</value> <description>desc2</description> </property> <property> <name>name3</name> <value>value3</value> <description>desc3</description> </property> <property> <name>name3</name> <value>valuetoremove</value> <description>desc4</description> </property> <property> <name>name5</name> <value>valu5</value> </property> </configuration> i want remove property tags contains value valuetoremove. i want next output <configuration> <property> <name>name1</name> <

android - Handling URI tasks manually -

i need select image sd card in android application. i'm using uri run device apps below code: intent photopickerintent = new intent(intent.action_pick); photopickerintent.settype("image/*"); startactivityforresult(photopickerintent, select_photo); i want know if wise handle uri tasks above task myself in app or cause trouble this . yes fine , risk free. incase trying images local storage, library : https://github.com/jaydeepw/poly-picker

python - How to make random.shuffle truly random? -

so have list: words = ["games","development","keyboard","speed","typer","anything","alpha","zealous","accurate","basics","shortcut","purpose","window","counter","fortress","modification","computer","science","history","football","basketball","solid","phantom","battlefield","advanced","warfare","download","upload","antidisestablishmentarianism","supercalifragilisticexpialidocious","discombobulation","liberated","assassin","brotherhood","revelation","unity","syndicate","victory"] and have shuffles , displays on label: entry.delete(0, tkinter.end) random.shuffle(words) label.config(text=str(words[1])) time

excel - Percentage finding -

i want calculate percentage as: range("e7").value "=(e5/(e5+e6))" this works fine static range. after i'm inserting row like: range("a1").entirerow.insert and percentage column remains static want formula shift 1 row down as: range("e8").value = "(e6/(e6+e7))" use range object resolve problem, range object move when insert or delete row or column. sub answer() dim percentage range set percentage = range("e7") range("a1").entirerow.insert percentage.formular1c1 = "=r[-2]c/(r[-2]c+r[-1]c)" end sub

vhdl - Error: indexed name is not a integer -

i got error when synthesized project. have error in line: axi_rdata <= patterncount(axi_awaddr(addr_lsb+opt_mem_addr_bits downto addr_lsb)); and got error: [synth 8-2234] indexed name not integer i appreciate if me. you have declared array type: type patterncount_memory array (31 0) of std_logic_vector(4 downto 0); signal patterncount : patterncount_memory; you access elements in array this: a <= patterncount(3); b <= patterncount(0); as can see, array indexed integer. if have bitfield: signal bit_field : std_logic_vector(4 downto 0) := "01010"; then error index array directly using this: a <= patterncount(bit_field); -- error, indexed name not integer you want convert bitfield, interpreted integer: a <= patterncount(to_integer(unsigned(bit_field))); -- ok, have converted our bitfield these conversion functions available when using numeric_std package.

javascript - FileReader's onloadend event is never triggered -

i'm trying make small snippet preview images before uploading them: $.fn.previewimg=function($on){ var input = this; try{ if (this.is("input[type='file']")) { input.change(function(){ var reader = new filereader(); reader.onloadend = function(){ (var = 0; < $on.length; i++) { if (/img/i.test($on[i].tagname)) $on[i].src = reader.result; else $on[i].style.bakgroundimage = "url("+reader.result+")"; } }; }); }else throw new exception("trying preview image element not file input!"); }catch(x){ console.log(x); } }; i'm calling like: $("#file").previewimg($(".preview_img")); but onloadend function never called. fiddle actually , got specify file , instruct filereader read it. below corrected code. $.fn.previewimg=function($on){ var input = this;

callback function in AngularJS -

i m trying assign value variable in callback function. how know callback functions asynchronous tried scope.apply doesnt seems work.. ideas ? angular.module("sadf") .factory("browserscamerasupportservice", function ($scope, $apply ) { return { supportsgetusermedia: function () { navigator.getusermedia = navigator.getusermedia || navigator.webkitgetusermedia || navigator.mozgetusermedia || navigator.msgetusermedia; var hascam = true; if (navigator.getusermedia) { navigator.getusermedia({video: true}, function(localmediastream){ }, function(){ $scope.$apply(function(){ hascam = false; }); }); } return angular.isdefined(navigator.getusermedia)&& hascam; } }; }); this case using $ap

foreach - Loop through list of values in table -

i have stata code starts with: local mystate "[state abbreviation]" the user enters state abbreviation (e.g., "fl" ) , runs code. rest of code references mystate multiple times. example: keep if stateabb == `"`mystate'"' replace goal = .95 if stateabb == `"`mystate'"' save "results `mystate'.dta", replace if (stateabb == `"`mystate'"' & pickone==1) using ... i have list of 10 or states need code run. it's saved in table, called "statestorun.dta," 1 variable name, "state" . is there way edit code loops through each state in table, , runs full code each state? i've studied foreach , forval examples cannot figure out how or if apply situation. suggestions? foreach can take local macro list of states want loop through. missing piece creating list. so, can use levelsof local option on "statestorun" dataset (not 'table' in

excel - Parsing variable names from cell content -

i learned from question can declare variables in excel naming cells. i'm wondering whether it'd possible parse text in cell call variable. name cell a1 "var1", , assign value 0.5 , , cell a2 "var2" value 0.75 . want following: b c d 1 var1 10 =b1*c1 2 var2 10 =b2*c2 3 var2 10 =b3*c3 4 var2 10 =parse(b4)*c4 5 var1 10 =cell(b5)*c5 6 var1 10 =value(b6)*c6 that is, multiply values in column d either var1 or var2 , read same row in column c . rows 4, 5, , 6 show unsuccessful attempts of have in mind. use indirect function. in cell d6 formula want =indirect(b6)*c6 . note in excel 2010 or later, can't use var1 cell name, because looks cell reference. have use _var1 or variable1 instead.

apache spark - How to express a column whose name contains spaces in SparkSql 1.3.1? -

we have tried wrapping column name brackets [column name] , single & double quotes, , backticks, none of them works. does sparksql support columns name contains spaces? thank you! backticks seem work fine: scala> val df = sc.parallelize(seq(("a", 1))).todf("foo bar", "x") df: org.apache.spark.sql.dataframe = [foo bar: string, x: int] scala> df.registertemptable("df") scala> sqlcontext.sql("""select `foo bar` df""").show foo bar same dataframe api: scala> df.select($"foo bar").show foo bar so looks supported, although doubt recommended.

r - writeLines() not producing a valid makefile -

i'm trying auto-generate makefile using r, , have run peculiar problem. the makefile produced using following code: v <- "histogram.tsv: histogram.r\r\trscript histogram.r" fileconn <- file("makefile") writelines(v, fileconn) close(fileconn) this produces following makefile histogram.tsv: histogram.r rscript histogram.r this makefile doesn't build, when manually type in tab before "rscript" does! when compare text generated write.lines generated hand, identical() returns true . it works fine when test on linux mint. it's probable distribution not forgiving when comes carriage return characters, typically used in windows. can try removing carriage return characters or use dos2unix : in dos/windows text files line break, known newline, combination of 2 characters: carriage return (cr) followed line feed (lf). in unix text files line break single character: line feed (lf). in mac

ios - Can't retrieve a picture to swift from parse.com using their documentation -

i have been trying follow parse.com's intruction retrieve picture uploaded (also using documentation). code: let testobject = pfobject(classname: "testobject") let file = testobject["sampleimage.png"] pffile file.getdatainbackgroundwithblock { (imagedata: nsdata?, error: nserror?) -> void in if error == nil { if let imagedata = imagedata { let image = uiimage(data:imagedata) self.mainimg.image = image print("image retreived") i getting error: "anyobject! not convertible 'pffile'" and sugests include ! in 'as'. however, when do, application runs not retrieve anything. i realize question posted elsewhere, answer not working me. doing wrong? let testobject = pfobject(classname: "testobject") this new empty object isn't backed on server. need set id known value , refresh instance of need run query f

How to use jquery Backstretch in asp.net mvc -

Image
how use backstretch in asp.net mvc. included script files in view page after when run program image not shown in browser. here code: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="~/scripts/jquery.backstretch.min.js"></script> <script> $.backstretch([ "images/img1.jpg", "images/img2.jpg], { fade:750, duration:10000 }); </script> it syntax error. don't have closing quotation mark img2.jpg . should be $.backstretch([ "images/img1.jpg", "images/img2.jpg"], { fade:750, duration:10000 }); make use of developer tools in browser (example: in google chrome f12 take dev tools) identify javascript errors. switch console tab see errors. , can click on link

questions about dir and import in python -

i have questions python's dir function >>>import urllib >>>dir(urllib) ['__builtins__', '__cached__', '__doc__', '__file__','__loader__','__name__','__package__', '__path__', '__spec__'] and when this >>>import urllib.request >>>dir(urllib) ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__','__package__', '__path__', '__spec__', 'error', 'parse', 'request', 'response'] why comes 3 more attributes? why request attribute doesn't in dir(urllib) @ first? i' appriciate help! urllib package, whereas in urllib.request , request module inside urllib package. when import package, not automatically import modules inside package, unless module imported __init__.py package. but __init__.py of urllib empty (its empty

sql - Understanding finding max value with index in postgreSQL -

i have following table: create table foo ( c1 integer, c2 text ) created follows: create indedx on foo(); insert foo select i, md5(random()::text) generate_series(1, 1000000) i; analyze baz; now, tried query: explain (analyze, buffers) select max(c2) foo; and got following plan: result (cost=0.08..0.09 rows=1 width=0) (actual time=0.574..0.574 rows=1 loops=1) buffers: shared read=5 initplan 1 (returns $0) -> limit (cost=0.00..0.08 rows=1 width=33) (actual time=0.570..0.571 rows=1 loops=1) buffers: shared read=5 -> index scan backward using foo_c2_idx on foo (cost=0.00..79676.27 rows=1000000 width=33) (actual time=0.569..0.569 rows=1 loops=1) index cond: (c2 not null) heap fetches: 1 buffers: shared read=5 what confused resulting cost 0.08.. 0.09 . why? i thought find max , if had index on column had perform index scan , read @ least 1 of index leafs. reading leafs in t

c - Why and in what sense is pthread_t an opaque type? -

posts here on suggest pthread_t opaque type, not number, not thread index, shouldn't directly compare pthread_t's, etc. etc. questions: why? there intent support systems no numeric ids threads? when pthread_t implementation typedef unsigned long int pthread_t; ? how? there's comment before above line, it's actually /* thread identifiers. structure of attribute type not exposed on purpose. */ typedef unsigned long int pthread_t; in pthreadtypes.h mean? attribute type? isn't index global table of threads? is there intent support systems no numeric ids threads? there different types serve numeric thread identifier. example, on systems limited resources 8-bit thread identifier used instead of unsigned long . the structure of attribute type not exposed on purpose. the comment not pthread_t definition, pthread_attr_t definition 1 line below: typedef union { char __size[__sizeof_pthread_attr_t]; long int __align; } p

vba - Convert a COUNTIF range recorded in an Excel macro to a variable range -

i'm looking converting countif range recorded in excel macro variable range. using excel vba manipulate monthly file has variable amount of records each month. i recorded macro modify , filter records , able convert of ranges variable ranges of site. however, struggling converting range variable range countif function shown below identifies duplicated id s in column color. column filtered color. range("a2").select range(selection, selection.end(xldown)).select selection.formatconditions.add type:=xlexpression, formula1:= _ "=countif($a$2:$a$7977,a2)>=2" selection.formatconditions(selection.formatconditions.count).setfirstpriority selection.formatconditions(1).interior .patterncolorindex = xlautomatic .color = 65535 .tintandshade = 0 end selection.formatconditions(1).stopiftrue = true range(“a1”).select selection.autofilter activesheet.range(“$a$1:$p$7977”).autofilter field:=1, criteria1:=rgb(255,255,0),operator:=xlfilter cell color

php - Laravel5 passing route args as middleware args -

i route argument passed middleware argument, this route::get('foo/{id}', ['middleware' => 'bar:{id}', function(){ }); how this? you can request variable: route::get('foo/{id}', ['middleware' => 'bar', function(){ }); public function handle($request, closure $next) { $id = $request->id; } https://laracasts.com/discuss/channels/general-discussion/how-to-get-url-parameters-at-middleware?page=1 the bar:id is used when want pass string id middleware.

android - GooglePlayServices is not working with the project -

i working on project have authenticate user google plus , did that. have shifted project 1 pc reasons. have made changes on developers console when try login google plus after launching, says "google play services not available. application close." why error comes when fine? gradle dependencies follows: dependencies { compile 'com.android.support:support-v4:+' compile 'com.google.code.gson:gson:1.7' compile 'com.google.android.gms:play-services:+' compile('com.crashlytics.sdk.android:crashlytics:2.5.2@aar') { transitive = true; } make sure device (or emulator) you're running app has google play services installed latest version (currently @ least 8.1.0), or set exact (earlier) version in build.gradle.

numeric - Matlab: diff(interp1(...'pchip')) produces strange results? -

Image
i have following arbitrary data: t=[0 1 2 3 4 5 6 7 8 9 10 12 14]; c=[0 1 5 8 10 8 6 4 3.0 2.2 1.5 0.6 0]; area=trapz(t,c); e=c./area; f=cumtrapz(t,e); when plotted, looks follows: now, want smoothen plots: t_int=[]; e_int=[]; f_int=[]; xmin=min(t); xmax=max(t); points=5000; stepsize=(xmax-xmin)/points; i=xmin:stepsize:xmax t_int=[t_int i]; e_int=[e_int interp1(t, e, i,'pchip')]; f_int=[f_int interp1(t, f, i,'pchip')]; end okay, here actual part problem is. in reality, have f plot , corresponding e plot. since f plot integral of e, e differentiated f plot. so then: dy=diff(f_int); dx=diff(t_int); dydx = dy./dx; plot(t_int(:,1:length(dydx)),dydx,t_int,e_int) legend('e (calculated)','e (actual)') why calculated e plot wonky?

php - Test third party shopping cart (Paypal) -

i trying test third party shopping cart api , empty string result. this code trying test: $ch = curl_init(); $params = array(); $params["cmd"]= "_cart"; $url = "https://www.sandbox.paypal.com/cgi-bin/webscr"; $params["upload"] = 1; $params["business"] = "my business email"; $params["item_name_1"] = "item name 1"; $params["amount_1"] = "1.00"; $params["shipping_1"] = "1.75"; $params["item_name_2"] = "item name 2"; $params["amount_2"] = "2.00"; $params["shipping_2"] ="2.50"; $params["currency_code"] = "usd"; curl_setopt($ch, curlopt_url, $url); curl_setopt($ch, curlopt_header, false); curl_setopt($ch, curlopt_ssl_verifypeer, false); curl_setopt($ch, curlopt_post, true); curl_setopt($ch, curlopt_returntransfer, true)