Posts

Showing posts from May, 2010

jquery - javascript issue on reloading data from div element -

i have <div id=x><textarea>data</textarea></div> data populated via ajax request. if change text (by typing in textarea) , if fire event on keypress/change old data value (alert displays old data)... $(function(){ $('#x').change(function(event){ xx=$('#x').html(); alert(xx); }) }); keydown , keypress fire before input's value updated. try keyup instead. also, change event fires once element loses focus, , @jinggoy mentioned, should attached inputs. jsbin: http://jsbin.com/vitomatocu/1/edit?html,js,console,output

batch file - How to send wild card attachment? -

this batch file ( date.bat ) copy file based on current date new folder: copy c:\test\output.csv c:\test2\output%date:~-4,4%_%date:~-10,2%_%date:~7,2%.csv this email.vbs script send attachment user: set objmessage = createobject("cdo.message") objmessage.subject = "test123" objmessage.from = "spartan@test.com" objmessage.to = "test123@test.com" objmessage.htmlbody = strhtml objmessage.addattachment "c:\test\output.csv" '==this section provides configuration information remote smtp server. '==normally change server name or ip. objmessage.configuration.fields.item _ ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'name or ip of remote smtp server objmessage.configuration.fields.item _ ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "spartan-dev" 'server port (typically 25) objmessage.configuration.fields.item _ ("http://schemas.microsoft....

string - how to convert "user_id" to "userId" in Java? -

this question has answer here: what simplest way convert java string caps (words separated underscores) camelcase (no word separators)? 17 answers convert string camelcase eg: "user_id" "userid" "user_name" "username" "country_province_city" "countryprovincecity" how in easy way? ps:"country_province_city" should "countryprovincecity" not "countryprovincecity" i use loop , stringbuilder . like string[] arr = { "user_id", "user_name", "country_province_city" }; (string str : arr) { stringbuilder sb = new stringbuilder(str); int pos; while ((pos = sb.indexof("_")) > -1) { string ch = sb.substring(pos + 1, pos + 2); sb.replace(pos, pos + 2, ch.touppercase()); } system.out.printf("%s...

python - Regex taking forever on short string. -

i'm looking through bunch of strings, trying match following pattern. location_pattern = re.compile( r""" \b (?p<location> ([a-z]\w*[ -]*)+[, ]+ ( [a-z]{2} | [a-z]\w+\ *\d ## ) ) \b """, flags=re.verbose) now regex runs ok on data set, takes forever (well, 5 seconds) on this particular string: ' javascript software architect, successful serial' there bunch of strings 1 (all caps, lots of space chars) @ point in input data , program slowed when hits it. tried taking out different parts of regex, , turns out culprit the \ *\d @ end of co...

Hamcrest matchers json subarray: is there a way to use hasItems to look for items in a subarray? -

for example, had following json response: { "0": { "field1" : 5 "field2" : 10 } "1": { "field1" : 1 "field2" : 10 } } is there way verify field1 has values 5 , 1? stuck @ .body statement here: .body("[0].field1", matchers.hasitems(1)); it totally possible not understand hasitems supposed do, since tried lots of combinations of [0], [*], , field names , none of them work. wish there usage article hamcrest , json didn't cover basic cases. know if asking possible? thanks reading. first of "json document" not valid. should this: { "0": { "field1" : 5, "field2" : 10 }, "1": { "field1" : 1, "field2" : 10 } } since you're targeting path matches single ...

r - Finding value that corresponds to same location in another matrix -

i trying factor scores each person. factors stored in dataframe factors need average of values in dataframe called data of values correspond factors , store in new column in data . apologize terrible explanation. hope example help, , happy answer questions! factors<-data.frame(c(na,2,na),c(na,3,1)) colnames(factors)<-c("v1","v2") row.names(factors)<-c("col1data","col2data","col3data") factors data<-data.frame(c(2,4,2),c(1,1,2),c(3,3,3)) colnames(data)<-c("col1data","col2data","col3data") row.names(data)<-c("person1","person2","person3") data #in dataframe factors row col2data present (i.e. not na) under factor v1 #go dataframe data each person , make new column called v1 holds value of col2data #do factor v2 , average values come 1 number each person. final result data<-data.frame(c(2,4,2),c(1,1,2),c(3,3,3),c(1,1,2),c(2,3,2.5)) colnames(data)<-...

perl - Creating an array of arrays for GD::Graph -

all right, i'm trying make array of arrays in perl use gd::graph module. , can't figure out why following not valid array of arrays gd::graph. my @t = (1, 2, 3, 4); @g = (2, 4, 5, 6); @data = (@t, @g); i've tried constructing data below, , still not it. my @data; push @data, @t; push @data, @g; i want keep values in seperate arrays , combine them use gd::graph, because i've found easiest way, if ugly. how go creating valid structure use gd::graph, created on fly? it complains here. my $gd = $graph->plot(\@data) or die $graph->error; looks @data single dimension array 8 elements. you can define array of arrays using anonymous array constructor [] my @data = ( [1, 2, 3, 4], [2, 4, 5, 6] );

What's preventing Android from finding a resource file in drawable? -

i'm working on bug of android application , occurs on galaxy nexus android version 4.2.2, works fine on nexus 5 4.4.2. basically it's not able find png file on device. the png file located in res/drawable , here structure of res folder: res/drawable res/drawable-de res/drawable-fr res/drawable-it res/drawable-hdpi res/drawable-ldpi res/drawable-mdpi res/drawable-xhdpi res/drawable-xxhdpi what preventing android fallback drawable folder in case? without knowing image hard say, image may large. alternatively, unless there's compelling reason not to, should put in *dpi folder anyway

java - Kafka consumer not receiving message -

i have found code kafka consumer. when send message producer, consumer in command prompt receives message consumer code not show message. have attached code below. public class simplehlconsumer { private final consumerconnector consumer; private final string topic; public simplehlconsumer(string zookeeper, string groupid, string topic) { properties props = new properties(); props.put("zookeeper.connect", zookeeper); props.put("group.id", groupid); props.put("zookeeper.session.timeout.ms", "500"); props.put("zookeeper.sync.time.ms", "250"); props.put("auto.commit.interval.ms", "1000"); props.put("auto.offset.reset", "smallest"); consumer = consumer.createjavaconsumerconnector( new consumerconfig(props)); this.topic = topic; } public void testconsumer() { map<string, integer> topiccount = new hashmap<string, intege...

tablet - Asus Memo Pad 10 (ME102A) - It is posible to hide navbar with Android Jelly Bean 4.2.2? -

i'm developing app needs fullscreen. i've tried coding without success makes me wonder if possible. if there way, how achieve this? if there not, suggest? thanks. it depends on target api. 4.4 or later might start https://developer.android.com/training/system-ui/immersive.html . otherwise try: public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); requestwindowfeature(window.feature_no_title); getwindow().setflags(windowmanager.layoutparams.flag_fullscreen, windowmanager.layoutparams.flag_fullscreen); setcontentview(r.layout.main); ...

python 2.7 - boto - What exactly is a key? -

as title says, key in boto? what encapsulate (fields, data structures, methods etc.)? how 1 access file contents files in aws bucket using key/boto? i not able find information on official documentation or on other third party website. provide info? here examples of usage of key object: def download_file(key_name, storage): key = bucket.get_key(key_name) try: storage.append(key.get_contents_as_string()) except: print "some error message." and: for key in keys_to_process: pool.spawn_n(download_file, key.key, file_contents) pool.waitall() in code example - key object reference unique identifier within bucket. think of buckets table in database think of keys rows in table reference key (better known object) in bucket. often in boto (not boto3) works this from boto.s3.connection import s3connection connection = s3connection() # assumes have .boto or boto.cfg setup bucket = connection.get_bucket('my_bucket_n...

numpy - Applying transformations to dataframes with multi-level indices in Python's pandas -

i'm trying apply simple functions numeric data in pandas. data set of matrices indexed time. wanted use hierarchical/multilevel indices represent , use split-apply-combine operation group data, apply operation, , summarize result dataframe. i'd result of these operations dataframes , not series objects. below simple example 2 matrices (two time points) represented multi level dataframe. want subtract matrix each time point, collapse data taking mean, , dataframe preserves original column names of data. everything try either fails or gives odd result. tried follow http://pandas.pydata.org/pandas-docs/stable/groupby.html since split-apply-combine operation, think, documentation hard understand , examples dense. how can achieved in pandas? annotated code fails along relevant lines: import pandas import numpy np t1 = pandas.dataframe([[0, 0, 0], [0, 1, 1], [5, 5, 5]], columns=[1, 2, 3], index=["a", "b",...

osx - Display an array of NSViewControllers horizontal in Swift -

Image
what best way display bunch of nsviewcontrollers horizontal side side inside horizontal scrollable view? each "row" must resizable own split view. i tests few ideas split view , scroll view can't starting point. thanks kick. ps. update here i've got: i add scrollview main view (coloumnmasterviewcontroller) border border. add second viewcontroller storyboard , named them "coloumn_view_controller" in coloumnmasterviewcontroller add coloumn_view_controller.view couple of times: class coloumnmasterviewcontroller: nsviewcontroller { @iboutlet weak var scrollview: nsscrollview! override func viewdidload() { in 1...10 { let vc: nsviewcontroller = self.storyboard?.instantiatecontrollerwithidentifier("coloumn_view_controller") as! nsviewcontroller vc.view.setframeorigin(nspoint(x: (130 * i), y: (i * 10))) println("set \(vc.view.bounds)") scrollview.addsubview(vc.view) } scrollv...

how can I delete the elements of array after read it in C++? -

array<personne> personnes; while (in) { personne newpersonne; in >> newpersonne; if (in.eof()) break; personnes.add(newpersonne); if (personnes.size() > 1) { (int = 0; < personnes.size() - 1; ++i) (int j = + 1; j < personnes.size(); ++j) { string typerelation = personnes[i].gettyperelation(personnes[j]); if (typerelation != "") cout << personnes[i].getnom() << " , " << personnes[j].getnom() << " " << typerelation << endl; if (j == personnes.size() -1){ personnes.delete(i); //doesn't work well, want delete first element when finishing copmarison withe other elements. } } } } i want delete first elements of array when second boucle reaching end a couple of killers in tableau::delete method: the function not comp...

c++ - Accessing a dynamic vector of vector -

here code: std::vector< std::vector<int> > v; v.push_back(std::vector<int>(2)); v[0].push_back(10); std::cout<<(v[0])[0]; but prints "0" instead of 10. i trying make dynamic vector holds vector fixed size. can me visualize what's happening? the code buggy: std::vector<int>(2) makes vector of size 2 initialized deault constructed int (which zero), pushing 10 makes vector of size 3 w/ 10 @ end (index 2).

Adding few images in Java JFrame -

i'm making 2d game. have background , character images. both of them .gif files. layout or need use set background behind character? tried ways either they're in row or nothing happens. i adding pictures that: url url = main.class.getresource("images/main.gif"); imageicon imageicon = new imageicon(url); jlabel background = new jlabel(imageicon); code background : first of copy background image , paste in src of code than set layout borderlayout this: setlayout(new borderlayout()); now add code: setcontentpane(new jlabel new imageicon(getclass().getresource("image.jpg")))); note: add image name here "image.jpg" now set layout flow layout this setlayout(new flowlayout()); and write code here

html - How can i retrieve the ordered products by user, and display them? using SESSION PHP -

Image
how can retrieve ordered products user, , display them? i have 2 tables: orders_good & users, if register wil go users, , if order product go in orders_good. everything working fine, except 1 thing. after user submit order, want see ordered products on page. so let want : if user logged in, search name in table: ('orders_good").. , if find name in table search if has products orders, if yes: show orders, row row, if no show: no orders yet ..... the table: orders_good, haves 2 columns: user_name & product_order i tyring this, user_name session working. but how can show users ordered products row row??? $sql = "select * orders"; $result = mysql_query($sql); if (!$result) { echo "could not run query ($sql) db: " . mysql_error(); exit; } if (mysql_num_rows($result) == 0) { echo "no rows found, nothing print exiting"; exit; } session_id($id); session_start(); echo $_session['user_name']; echo $row["product_...

c# - How do I check if items already exist in a ToolStripMenuItem DropDownItems? -

items = file .readlines(recentfiles) .select(line => new toolstripmenuitem() { text = line }) .toarray(); recentfilestoolstripmenuitem.dropdownitems.addrange(items); i want check if items exist in recentfilestoolstripmenuitem.dropdownitems if not exist add if exist don't add. you have 2 collections: items & recentfilestoolstripmenuitem.dropdownitems using linq , should able an except() where() add difference between 2 collections. this not tested. recentfilestoolstripmenuitem.dropdownitems.addrange(items.except(recentfilestoolstripmenuitem.dropdownitems)); this tested recentfilestoolstrip.dropdownitems.addrange( items .where(i => !recentfilestoolstrip.dropdownitems .oftype<toolstripmenuitem>() .select(t => t.text).contains(i.text) ).toarray() ); slaks comment refers doing following: recentfilestoolstripmenuitems.dropdownitems.clear(); recentfilestools...

amazon web services - How to scale out Tomcat on AWS EC2 instance? -

there number of questions on auto scaling. none of talks scaling out software stack installed on these servers. aws auto scaling scales out resources. not software on it. in case looking forward scale out tomcat server (and apache httpd server) installed on first instance part of new instance aws scaling service creates. i followed regular process establish scaling application on amazon web services ec2 instances. created snapshot existing instance exact configurations of running instance - success created ami above snapshot - success created auto scaling group , launch configuration - success scaling policy create new instance upon cpu >= 65% 2 times. - success the above procedure creates new instance not copy software stack present on image. how accomplish auto scaling in such way when aws auto scaling happens, tomcat server part of ami copied , started in new scaled out instance. do have use puppet/chef or such tools achieve this? or there option in aws using ...

if statement - Refactoring if elsif else in Ruby -

is there way refactor code , make cleaner? can use fewer booleans solve problem? def get_grade(grade_num) if grade_num > 100 return "please enter number between 0 , 100" elsif grade_num <=100 && grade_num >= 90 return 'a' elsif grade_num < 90 && grade_num >= 80 return 'b' elsif grade_num < 80 && grade_num >= 70 return 'c' elsif grade_num < 70 && grade_num >= 60 return 'd' elsif grade_num < 60 return 'f' end end what using range , case statement? def get_grade(grade) case grade when 90..100 'a' when 80...90 'b' when 70...80 'c' when 60...70 'd' when 0...60 'f' else 'please enter number between 0 , 100' end end

tfs - Easiest way to deploy my website using Visual Studio 2012 and IIS 6/7 -

what's easiest way deploy website part of build definition? i'm using visual studio 2012, tfs 2013. have powershell @ disposal , open making easy process. it nice if can pick target machine , build deploy in automated fashion. if have multiple environments in sequence, dev->qa->prod, might benefit release management tool orchestrates deployment pipeline. tfs has component called release management visual studio lets build pipeline , workflow approvals automate process. manage variables different between environments.

c++ - Passing vector of derived, templated class -

i'd define general function foo takes data, perhaps manipulates underlying class variables, , returns int . however, when attempt create separate function takes vector of foo objects, compiler fails deduce template parameter. following illustrates i've tried: #include <vector> template <typename t> class base { public: virtual int foo(const t& x) const = 0; }; template <typename t> class derived : public base<std::vector<t> > { // specialize vector data public: virtual int foo(const std::vector<t>& x) const { return 0;} }; template <typename t> int bar(const t& x, const std::vector< base<t> >& y) { if(y.size() > 0) return y[0].foo(x); } int main(int argc, char** argv) { std::vector<double> x; std::vector< derived<double> > y; bar(x, y); } this fails find matching function bar , notes: main.cc:16:5: note: template argument deduction/substitution failed: ma...

android - Difference between Environment.getExternalStorageDirectory() and Environment.getExternalStorageDirectory().getAbsolutePath() -

what's difference between environment.getexternalstoragedirectory() and environment.getexternalstoragedirectory().getabsolutepath() or environment.getexternalstoragedirectory().getcanonicalpath() or environment.getexternalstoragedirectory().getpath() i know getabsolutepath(), getcanonicalpath() , getpath() are. i see in examples environment.getexternalstoragedirectory() used this: getexternalstoragedirectory() + "/somefolder/anotherfolder/" what confuses me getexternalstoragedirectory() default refers , why in cases people use methods , when alright use getexternalstoragedirectory() without it? i know getabsolutepath(), getcanonicalpath() , getpath() are. then know answer original question ("what's difference between..."), since thing different calls. what getexternalstoragedirectory() default refers to it refers root of external storage. when user mounts android device via usb cable , gets drive letter or vo...

node.js - Getting id of worker from inside worker process -

using node.js cluster module, straightforward id of worker process. https://nodejs.org/api/cluster.html that be: cluster.on('fork', function (worker) { console.log('a worker', worker.id, 'was forked.'); }); but how can id of worker inside worker itself? how come cluster module doesn't give worker id when cluster forks worker? do have send worker it's cluster id master process? i looking akin to: process.id (as opposed process.pid) or process.worker.id in case, having trouble figuring out id of worker inside worker itself. var cluster = require('cluster'); if (cluster.ismaster) { console.log('i master'); cluster.fork(); cluster.fork(); } else if (cluster.isworker) { console.log('i worker #' + cluster.worker.id); } as in here

c# - How to validate textbox with checkbox in MVC? -

i have viewmodel : public string address { get; set; } [displayname("do want reward?")] public bool isreward { get; set; } [range(0,int.maxvalue,errormessage="please enter integer number")] [displayname("reward")] public int reward { get; set; } in view isreward property unchecked default, when user check isreward , post view, if reward text box empty show error message user "please enter reward". how can validate using dataannotation ? try following code. display error message if isreward true , reward textbox value zero. [rewardvalidation] public class rewardmodel { public string address { get; set; } [displayname("do want reward ؟")] public bool isreward { get; set; } [range(0, int.maxvalue, errormessage = "please enter integer number")] [displayname("reward")] public int reward { get; set; } } public c...

shell - replacing specific value (from another file) using awk -

i have following file. file1 a b 1 c d 2 e f 3 file2 x l y m z n i want replace 1 x @ time , save in file3 . next time 1 y , save in file4 . then files like file3 a b x c d 2 e f 3 file4 a b y c d 2 e f 3 once finished x , y , z 2 l , m , n . i start inserts not replace. awk -v r=1 -v c=3 -v val=x -f, ' begin{ofs=" "}; nr != r; nr == r {$c = val; print} ' file1 >file3 here's gnu awk script ( because uses multidimensional arrays, array ordering ) want: #!/usr/bin/awk -f begin { fcnt=3 } fnr==nr { for(i=1;i<=nf;i++) f2[i][nr]=$i; next } { fout[fnr][1] = $0 ff = $nf if(ff in f2) { for( r in f2[ff]) { $nf = f2[ff][r] fout[fnr][fcnt++] = $0 } } } end { for(f=fcnt-1;f>=3;f--) { for( row in fout ) { if( fout[row][f] != "" ) out = fout[row][f] else out = fout[row][1] print out > "file...

php - Uploading large (~80Mb) text file and saving to database? -

i need create web page person can use select , upload text file (eg: csv) , have file imported backend mysql database. this fine, , have php code - accept file upload, parse, save database. the problem need reliable method allow user upload large files, potentially around 30 - 80mb, without timing out or failing during upload or save database. other increasing upload limit , timeout settings, there other advice on how can ensure consistently reliable method ensure data uploaded? the dataset changes daily, , previous day's data in database needs cleared out , replaced new day's data - vital no data lost during new upload. i welcome advice of others how best achieve this, high degree of confidence data uploaded reliably , successfully, , how best clearing out of previous days data - ideally best check new data uploaded before clearing out , replacing previous data. all suggestions welcome! there stack overflow question confirm goleztrol's answer php t...

c# - How to cast generic parameter to generic interface? -

i want have extension method print contents of ienumerable< x > public static ienumerable<t> log_elements<t>(this ienumerable<t> collection, bool recursive = true) { form1.log("["); foreach (t in collection) if(recursive&&(i.gettype().getgenerictypedefinition()==typeof(ienumerable<>))) (ienumerable<>)i.log_elements();//this doesn't work else form1.log(i); form1.log("]"); return collection; } if contains ienumerable< y >, method should called too. i cannot add log_elements<t>(this ienumerable<ienumerable<t>>,bool) because ienumerable<t> matches t of original method. i'm sure, there should solution such simple problem in c#. change ienumerable<t> non generic ienumerable (which generic version inherits anyway). public static ienumerable<t> log_elements<t>(this ienumerable<t> collect...

backbone.js - Using Backbone Relational to handle JSON-API Data -

we've been using backbone relational model our orm relationship in front end instance: { id: 2 username: "bob" comments: [ { id:5, comment: "hi", user: { username: 'bob' } } ] } that has been working great using models such in front end: class user extends app.relationalmodel relations: [{ type: backbone.hasmany, key: 'comments', relatedmodel: 'comment', collectiontype: 'commentcollection' }] however our api has changed , respecting more of json-api spec data end encapsulated inside of 'data'. { data: { id: 2 username: "bob" data: { comments: [ { id:5, comment: "hi", user: { username: 'bob' } } ] }, meta: { } } } how can instruct backbone relational data 'comme...

sql - Optimising a VBA procedure that iterates over two different tables of data -

i have 2 sql tables pricetbl , paymenttbl . due fact prices item change everyday, need update paymenttbl prices of right time. if transaction made after date-effective of product's price, transaction price in paymenttbl same latest product's price (as long date-effective smaller transaction date). don't want limit myself here, want iterate on whole table make changes data every single transaction has proper price. pricetbl pid| price| date effective --------------------------- 1 | 10 | 01-12-2014 2 | 20 | 01-02-2015 3 | 20 | 02-12-2014 2 | 40 | 20-03-2015 1 | 50 | 02-03-2015 4 | 34 | 20-02-2015 1 | 40 | 25-05-2015 paymenttbl payid | pid | transdate | price -------------------------------- 1 | 1 | 02-12-2014| 05 2 | 1 | 04-03-2015| 10 3 | 2 | 21-04-2015| 35 4 | 3 | 03-12-2014| 15 expected table paymenttbl after running query payid | pid | transdate | price -------------------------------- 1 | 1 | 02-12-2...

ios - Custom Transition Animation Causing Navigation Bar to Animate -

i implementing custom transition animation between view controllers, reason navigation bar getting animated along transition animation. somehow auto layout issue? i'm not sure how be. here code using display , dismiss view controllers custom transition. i navigation bar not animated, ideas why happening? -(void)animatetransition:(id<uiviewcontrollercontexttransitioning>)transitioncontext { // grab , view controllers context uiviewcontroller *fromviewcontroller = [transitioncontext viewcontrollerforkey:uitransitioncontextfromviewcontrollerkey]; uiviewcontroller *toviewcontroller = [transitioncontext viewcontrollerforkey:uitransitioncontexttoviewcontrollerkey]; if (self.presenting) { fromviewcontroller.view.userinteractionenabled = no; [transitioncontext.containerview addsubview:fromviewcontroller.view]; [transitioncontext.containerview addsubview:toviewcontroller.view]; int frameheight = fromviewcontroller.view.fram...

c++ - R style subset/replace in Rcpp -

in r have loop runs through data frame of people coming , leaving site , assigns them parking lot until leave when releases spot. activity = structure(list(id = c(1, 2, 3, 3, 1, 2, 3, 2, 3, 1, 2, 1), lot = structure(c(1l, 3l, 6l, 6l, 1l, 3l, 2l, 5l, 2l, 4l, 5l, 4l), .label = c("a", "a", "c", "d", "f", "z"), class = "factor"), time = c(1, 3, 6, 7, 8, 9, 10, 12, 13, 14, 15, 21), dir = c(1, 1, 1, -1, -1, -1, 1, 1, -1, 1, -1, -1), here = c("no","no","no","no","no","no","no","no","no","no","no","no")), class = "data.frame", row.names = c(na, -12l), .names = c("id", "lot", "time", "dir","here")) lots = structure(c(30, 175, 170, 160, 300, 300, 35, 160, 85, 400...

javascript - How do I store persistent data? -

i'm making game uses cookies (nom nom nom cookies, not web browser cookies) currency. var cookies = 0; function cookieclick(number){ cookies = cookies + number; document.getelementbyid("cookies").innerhtml = cookies; } now need save number of cookies when user refreshes page number of cookies persist. how do this? storage the storage interface of web storage api provides access session storage or local storage particular domain, allowing example add, modify or delete stored data items. if want manipulate session storage domain, call window.sessionstorage method; if want manipulate local storage domain, call window.localstorage . https://developer.mozilla.org/en-us/docs/web/api/storage store value of cookies in window.localstorage make stay until user clears cache, or window.sessionstorage make stay until user closes browser window. update value on page load if exists. ( demo ) var cookies = 0; if(localstorage.cook...

c# - editorfor send value to template asp.net-mvc -

i have view has string variable , editorfor. i'd send string variable editorfor template partial view //parent view string message = "message"; @html.editorfor(m => m.someobject) //editor template @model someobject var message = messagefromparentview; <div>@message</div> //other inputs someobject how go doing this? you use viewbag this. set property on parent view or controller , access inside editor template code. parent view @{ viewbag.message= "message"; } editor template <div>@viewbag.message</div>

Using Python to keep track of deaths (Twitch bot) -

i working on command twitch bot keep track of deaths streamer experiences while playing game. trying have can !adddeath , death added counter. how tried it, , it's wrong because doesn't keep track of deaths spits out 0 + 1 is. need way '1' added death value everytime !adddeath executed. def command_adddeath(): death = 0 death2 = 1 sum = float(death) + float(death2) print('the sum of {0} , {1} {2}'.format(death, death2, sum)) send_message(chan, 'death counter has been updated!') thank ahead of time! you can define variable, called counter. then, add 1 counter every time function run: counter = 0 then, make function, , make sure bring variable scope using global keyword: def command_adddeath(): global counter counter += 1 print(counter) send_message(chan, 'death counter has been updated!') the reason function doesn't work setting variables every time run it. however, if have accumu...

javascript - Simple form that hides after sumbmiting -

as title says. when submit form dissapears second , after reload of browser shows again. css mess right i'm trying things out. <div id="new_user_form" style=" width: 400px; height: 200px; background-color: grey;"> <form onsubmit="hide_show()" style="display: block; margin: 0 auto; width: 100%;"> new nickname: <input type="text" required><br> new password: <input type="password" required> <br><input type="submit"> </form> </div> <script> function hide_show(){ document.getelementbyid("new_user_form").style.display="none"; } </script> if want submit form , after submit succeeds hide user without refreshing page, should submit through ajax. an informative example: https://scotch.io/tutorials/submitting-ajax-forms-with-jquery...

javascript that writes in the google chrome url bar -

i want try , right code guess default ip of router connected to. this, write bit of javascript code type google chrome url bar , attempt search it. instance: type 192.168.0.0 , 192.168.0.1, etc... largest problem have no idea how write code locate , type url bar, other user input. how this? url bar not part of window couldn't locate using javascript dom elements. to read , write url use window.location (more find here: https://developer.mozilla.org/en-us/docs/web/api/window/location ). if change window.location address, force browser load new content, in same way reloading page. remember loading new page lead discarding javascript code if loaded within website. another way use iframe , dynamically change url, here: dynamically set iframe src if want make tool iterates through possible addresses, recommend writing chrome extension. more , tutorial available here: https://developer.chrome.com/extensions

casting - F# cast / convert custom type to primitive -

i've designed app domain custom f# types, seems these custom types pita when want use data various tasks... i.e. writing values csv file, using other libraries rely on primitives, etc. for example, have custom type (which used building block other larger types): type ct32 = ct32 of float but code doesn't work: let x = ct32(1.2) let y = float x //error: type "ct32" not support conversion... let z = x.tostring() //writes out namespace, not value (1.2) i've tried use box/unbox , convert.tostring() , 2 f# casting operators none of them seem allow me access base primitive value contained types. there easy way primitive values in custom types because far they've been more of headache useful. your type ct32 discriminated union 1 case identifier ct32 of float . it's not alias float type couldn't cast float. extract value can use pattern matching (this easiest way). type ct32 = ct32 of float let x = ct32(1.2) let ct32tofloat = funct...

Android - create group by wifi direct p2p for multiple devices -

i want create group multiple devices wifi direct p2p protocol in specific manner. want gather data other devices 1 device. should make receiver device, group owner. example clicking button, should create group , send out broadcast others join group automatically. (i know device should accept connection @ first, assume don't need it.) i've searched lot, can't find clue. appreciate advice or comment on problem. basically, there no broadcasts available api. instead, use creategroup form group, create local service, , make sure peerdiscovery on (i'm rather sure device , local service visible others when api active) in others peer/service discovery , connect once find looking for. you workaround dialog, explained 2 ways in blog .

ios - ResearchKit headers not able to import in Xcode -

i making app using researchkit framework of apple. i have followed installation guide of researchkit on github , added files project. when trying import header files of framework, error: file not found what did: i created new project named creatingtasks.xcodeproj . then added researchkit files dragging researchkit.xcodeproj in navigation controller, , embedding researchkit framework in embedded binaries. now want create simple task in existing view controller unable import header files. you need build researchkit target once first. should able import researchkit. if doesn't help, please post project on github , give link.

Grails 3 war always in dev environment on Tomcat -

Image
i using grails 3.0.1 , have standard environments defined. when deploy app on tomcat 7 via jenkins, deploys in development mode , never in production since use grails 3. the thing have changed in build.gradle following line: provided "org.springframework.boot:spring-boot-starter-tomcat" this build config in jenkins. building , deployment works environment. know because not touches mysql @ , have in index.gsp shows me ${grails.util.environment.current.name} do have advice me? edit: i've tried until now: using "prod war" instead of "war" target

fiware - Can PEP proxy discriminate entities? -

can pep proxy (working idm keyrock) allow access entities of orion? example scenario: there 2 types of entities on orion classified entity_type: kitchen , bathroom user plumber can modify/comsume bathroom type entities. user cook can create/comsume kitchen type entities. user admin can modify/create/comsume all entities. as far know, neither reference implementation of pep proxy (wilma) or ti+d's version (steelskin) offer functionality (though suggested more once). using standard ngsi operations (updatecontext , querycontext), hard implement in wilma (i think) , require modify orion's plugins in steelskin. piece missing have support fine grained security (in steelskin case) add entity information frn used security. but if restrict convenience operations (that reflect ids , attributes in url), use security on rest resources restrict resources based on entity features (but imply work xacml , so). in case, both pep proxies used. edit: here c...

powershell - Add header to multiple CSV files -

i'm looking way add header line multiple csv files. problem code below add empty row @ end of each file. don't understand why there empty line need delete lines. $header="column1,column2,column3,column4,column5,column6" get-childitem .\ -recurse -filter *.csv| foreach-object { $header+"`r`n"+ (get-content $_.fullname | out-string) | set-content -path $_.fullname } the canonical way import files specifying headers , re-export them: $header = 'column1', 'column2', 'column3', 'column4', 'column5', 'column6' get-childitem .\ -recurse -filter '*.csv' | foreach-object { $file = $_.fullname (import-csv -path $file -header $header) | export-csv -path $file -notype } export-csv add double quotes around fields of csv, though. also, parsing data objects have performance impact. if don't want double quotes added or pressed performance solution suggested @petseral in comments que...

javascript - How to select/unselect picture on website? -

i have few images on site , want give user possibility select of them. i'm trying jquery: pic.attr('selected', 'selected'); pic.removeattr('selected'); my problem how check (properly) pictures (let's assume they're my-pic class) checked. you can try this: $('.mp-pic').each(function(i, obj) { if(obj.hasattribute('selected')) { // selected } else { // not selected } }); or check whether element has particular attribute or not try this: var attr = $(selector).attr('selected'); if (typeof attr !== typeof undefined && attr !== false) { // operation }

paw app - Receiving "kCFStreamErrorDomainSSL error -9841" error from Paw -

i'm attempting make request using paw , , i'm getting mysterious error: kcfstreamerrordomainssl error -9841 attempts execute same request using curl, other os x rest clients, etc... work no problem @ all. i've search references -9841 instance of error, , have turned nothing. as mentioned micha mazaheri , in previous comment, best way solve problem go paw preferences , choose different client library within http tab. not aware option.

java - GoogleAPIClient not connecting properly? -

i'm trying connect mgoogleapiclient, following this guide . when debug, little window popsup asking me googleplus account sign in as. select main account , click ok, stops there , absolutely nothing. no error messages, warnings, infos, no nothing. my source: public class mainmenu_activity extends activity implements googleapiclient.connectioncallbacks, googleapiclient.onconnectionfailedlistener { private button btnstart; private button btnsubmit; private button btnhof; private googleapiclient mgoogleapiclient; public static int request_leaderboard = 100; // request code use when launching resolution activity private static final int request_resolve_error = 1001; // bool track whether app resolving error private boolean mresolvingerror = false; private static final string state_resolving_error = "resolving_error"; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestat...

database - Revert backup table data to original table SQL -

i have created backup country table. create table country_bkp select * country; what sql should use restore country table it's original state? can do insert country select * country_bkp; but have duplicate entries , fail primary key same . is there sql command merge data back? last alternative be drop table country; create table country select * country_bkp; but want avoid grants/permissions lost this. other cleaner way be delete country ; insert country select * country_bkp; but looking more of merge approach without having clear data original table. instead of dropping table, which, noted, lose permission defitions, truncate remove data, , insert-select old data: truncate table country; insert country select * county_bkp;

vb.net - VB Get object name -

i'm working on visual basic project , ran problem. created 81 labels (by hand, without array) , need give them code. want accses label's properties, such name , text; don't want change code each 1 can like: this.name name of current label? teacher dosen't know how solve that. tried me.name returns name of form... , can't find documentation anywhere. please soon, sagi. if want name of label when label clicked, can use sender argument of click event. example here method handles click event of 2 labels. sub label_click(sender object, e eventargs) handles label1.click, label2.click dim thislabel label = ctype(sender, label) dim myname string = thislabel.name end sub

Customizing My Sites portlet in Liferay -

i want customize sites portlet (which out of box portlet) in liferay using ext. how do this? how source code sites portlet? following files structure my sites portlet in portal source: views: \portal-web\docroot\html\portlet\my_sites\ - view.jsp - site_action.jsp action: \portal-impl\src\com\liferay\portlet\myplaces\action\viewaction.java the initial view being rendered view.jsp of group_search.jsp (search field) , site_action.jsp (actions button). ensure action file, open \portal-web\docroot\web-inf\struts-config.xml , copy of struts_action value set parameter render / action urls appearing on view.jsp (lets /my_sites/view , /sites_admin/page ), find following mappings in struts-config.xml /my_sites/view <action path="/my_sites/view" type="com.liferay.portlet.myplaces.action.viewaction"> <forward name="portlet.my_sites.view" path="portlet.my_sites.view" /> </action> /sites_admin...

code editing on .htaccess file to point to https -

regarding .htaccess file, have edit on htaccess code direct https? i have read other q/a code seems larger those my website on wordpress directoryindex index.php # begin w3tc browser cache <ifmodule mod_deflate.c> <ifmodule mod_headers.c> header append vary user-agent env=!dont-vary </ifmodule> addoutputfilterbytype deflate text/css text/x-component application/x-javascript application/javascript text/javascript text/x-js text/html text/richtext image/svg+xml text/plain text/xsd text/xsl text/xml image/x-icon application/json <ifmodule mod_mime.c> # deflate extension addoutputfilter deflate js css htm html xml </ifmodule> </ifmodule> # end w3tc browser cache # begin w3tc page cache core <ifmodule mod_rewrite.c> rewriteengine on rewritebase / rewritecond %{http:accept-encoding} gzip rewriterule .* - [e=w3tc_enc:_gzip] rewritecond %{http_cookie} w3tc_preview [nc] ...

perl - How to get the "width" of a string to be used in a Tkx label -

i making simple application using perl tkx , allow user select directory. rather using text wrapping or stretching box ridiculous length show whole directory name, if name long truncate , append "..." end. the problem width of label defined arbitrary value (like 40). if value measurement of how many characters label fit truncate string 37 , append "..." doesn't seem case. does know -width of label using perl tkx measurement of? how can find amount of -width units string take can figure out appropriate point truncate it? edit: i found answer in tcl manual : database class: width specifies desired width label. if image or bitmap being displayed in label value in screen units (i.e. of forms acceptable tk_getpixels); text in characters. if option isn't specified, label's desired width computed size of image or bitmap or text being displayed in it. this should mean width of 40 truncate text should have truncate string ...

wpf - Trouble Parameterizing ValidationRules with Dependency Properties -

so have written following dp , validationrule: public class comparisonvalue : dependencyobject { public object comparisonobject { { return (object)getvalue(comparisonobjectprop); } set { setvalue(comparisonobjectprop, value); } } public static readonly dependencyproperty comparisonobjectprop = dependencyproperty.register("comparisonobject", typeof(object), typeof(comparisonvalue), new uipropertymetadata(null)); } public class objectcomparisonvalidator : validationrule { private comparisonvalue _objecttocompare; public comparisonvalue objecttocompare { { return _objecttocompare; } set { _objecttocompare = value; } } public override validationresult validate(object value, cultureinfo cultureinfo) { if (value != null) { if (!value.equals(objecttocompare.comparisonobject)) { ...

sql server - UPDATE from a DERIVED QUERY - SQL -

i have update query run final scalar value based on derived query. need make sure correct row updated in outermost query. how can join derived2 query on rxtransactionid outermost query in example? note: 'a.rxtransactionid' in clause not allowed. fact.adherence.rxtransactionid = a.rxtransactionid update fact.adherence set fact.adherence.last_mpr = ( select last_mpr ( select derived1.irxlocationid, derived1.rxnumber, derived1.refillnumber, derived1.rxtransactionid, derived1.clientid, derived1.completeddate, derived1.nextcompleteddate, last_mpr = nullif(cast(cast(coalesce(dayssupply, 0) decimal) / nullif(cast(coalesce(datediff(day, derived1.completeddate, derived1.nextcompleteddate), 0) decimal), 0)as decimal(12,4)), 0) (select [completeddate] [completeddate], nextcompleteddate = (select -- second recent complete date. top 1 aa.[completeddate] fact.rxtransaction aa aa.rxid = c.rxid , coalesce(a.refillnumber + 1,0) = aa.refillnumber , aa.rxid = c.rxid)...

java - configure SSL password like ${keystore.password} in tomcat server.xml -

i want configure ssl passwords ${keystore.password} in tomcat server.xml. tomcat 7, wrote code , it's working fine. in tomcat 8 it's not wokring because introspectionutils being moved tomcat-coyote.jar. if has done same thing in tomcat 8 please tell me how proceed. below code sample working in tomcat 7. run, create jar below code , in catalina.proerties add 2 lines: org.apache.tomcat.util.digester.property_source=com.sumit.logic.decrypt keystore.password=9gm4m64fg+jjhnbtk+buwg== code: package com.comviva.logic; import java.io.ioexception; import javax.crypto.cipher; import org.apache.tomcat.util.introspectionutils; import javax.crypto.spec.secretkeyspec; import org.apache.commons.codec.binary.base64; import org.apache.commons.logging.log; import org.apache.commons.logging.logfactory; import com.comviva.util.util; public class decrypt implements introspectionutils.propertysource { static log log = logfactory.getlog(decrypt.class); s...