Posts

Showing posts from July, 2014

visual studio 2013 - using for loop for a textbox in selenium C# -

for(int i=0;i<=10;i++) { driver.instance.find element(by.id("id of element")).send keys("auto"+i); } i used code not work 1 10 numbers printing in 1 attempt i searching code dynamically increment in each run out changing sendkeys values again , again your question not clear. trying enter value in 10 different edit boxes in single run or trying enter different values in same edit box in multiple runs (if can use random class generate random integers generate different values in different runs). random random = new random(); int = random.next(0, 10); driver.instance.find element(by.id("id of element")).send keys("auto"+i); you can increase bucket random.next(0, 10); random.next(0, 100); decrease probability of having same no in 10 runs.

objective c - SKEffectNode shader bug -

i'm developing game using sprite kit , liquid fun (google's implementation of box2d liquids). after applied threshold shader make liquid more real, stumbled in strange behavior can seen on video: current behavior the way should behave can seen on video: normal behavior i'm applying shader on skeffectnode contains particles ( skspritenodes ) that's code on threshold shader: void main() { vec4 color = texture2d(u_texture,v_tex_coord); if(color.w > 0.4) { color = vec4(18.0/255.0, 122.0/255.0, 232.0/255.0, 1.0); } else { color = vec4(0.0, 0.0, 0.0, 0.0); } gl_fragcolor = color; } does have clue of going on?

javascript - Hide referrer header in API request -

i need make requests google translate text-to-speech api. have enabled key keep getting blocked no access-control-allow-origin. i've posted more here: google translate api - no access control origin text speech the following sources, http://weston.ruter.net/2009/12/12/google-tts/ , request google text-to-speech api google returns 404 error if http request contains referer header other empty string. given request like: $.get('https://translate.google.com/translate_tts?key='+mykey+'&ie=utf-8&tl=en&q=hello+world', function (returned_data) { how hide or remove referrer header i'm not blocked? this source says put https://href.li/... in front. changed to: $.get('https://href.li/?https://translate.google.com/translate_tts?key='+key+'&ie=utf-8&tl=zh-cn&q=你好', and still blocked. server-side attempt: no response. this blog provides server-side script sets referrer empty string.

cloud code - Function not updating on Parse.com -

Image
i have function, working normally, on parse.com: parse.cloud.job ("mybgfunction", function(request, status) { console.log("entering mybgfunction."); }); but strange may seem, if update (saving , using parse deploy) usual following: parse.cloud.job ("mybgfunction", function(request, status) { console.log("entering mybgfunction (aaaa)."); }); the next time try execute, old function executed (in log), if update did go through, though got no error message after running: parse deploy has seen before? one more tiny question: there way clear old logs (on parse)? basic useful feature. looking bit more details @ happens classes, seems "all fine" except can see in log outdated. wrote earlier, logs previous versions. makes extremely difficult debug function, because trace-log becomes impossible. please go "cloudcode" section, , check if code same expected.

Displaying contents of String array in Swing component as iterations using Time delay. JAVA -

i have array of strings i'm trying display (one one) slideshow in java swing component. trying add delay time between iterations. i attempted using jtextarea, action listener added it. here code have right now: private class myactionlistener implements actionlistener { public void actionperformed(actionevent e) { // bunch of text processing //note: myinfo.getcontents() returns arraylist<mytype>. iterator<mytype> iterator = myinfo.getcontents().iterator(); int = 0; while (iterator.hasnext()) { mytextarea.settext(iterator.next().tostring()); // add time betweeen iterations wanted use thread // delay method. } } } my code not working because jtextarea doesn't have action listener. update note: many replies stated should use actionlistener jtextarea; however, eclipse not showing me jtextarea has method called addactionlistener. i'm kind of stuck here, which j

math - Why we use CORDIC gain? -

i'm studying cordic. , found cordic gain. k=0.607xxx. from cordic, k_i = cos(tan^-1(2^i)). as know k approched 0.607xxx.when going infinity this value come k multiplying. i understand reason of exist each k. curioused used ? why use value k=0.607xx? the scale factor rotation mode of circular variant of cordic can established first principles. idea behind cordic take point on unit circle , rotate it, in steps, through angle u sine , cosine want determine. to end define set of incremental angles a 0 , ..., a n-1 , such a k = atan(0.5 k ). sum these incremental angles appropriately partial sum of angles s k , such s n ~= u . let y k = cos(s k ) , x k = sin(s k ). if in given step k rotate a k , have y k+1 = cos (s k+1 ) = cos (s k + a k ) x k+1 = sin (s k+1 ) = sin (s k + a k ) we can compute x k+1 , y k+1 x k , y k follows: y k+1 = y k * cos (a k ) - x k * sin (a k ) x k+1 = x k * cos (a k ) + y k * sin (a k ) considering may both

jquery - Simple Automatic Refresh using JavaScript in a Razor Page -

i want know how simple refresh of html table, without re-loading whole page. i timer set refresh every 5 seconds. the razor code is: <table class="table trim-list search-results" id="res"> <tbody> @foreach (record record in model.results) { var renditionuri = getrendition(record); <tr style="float:left;"> <td class="row-icon"> <div id="thumb_col" style="margin-right:10%;"> <img class="thumbnail" style="padding:3px;" src="~/record/@record.uri/recordrendition/@renditionuri"/> </div> </td> <td class="prop-val"> <label style="font-we

java - SQL syntax error in "insert into 'keys'(a,b,c,d,e) values(?,?,?,?,?)" -

string requiredkeyword = request.getparameter("keyword"); string textbookcode = request.getparameter("bookcode"); string pagenumbers= request.getparameter("pagenumbers"); string definition = request.getparameter("definition"); printwriter show = response.getwriter(); try { class.forname("com.mysql.jdbc.driver"); connection dbconnection=drivermanager.getconnection("jdbc:mysql://localhost:3306/main_data","root",""); system.out.println(" connection created "); preparedstatement prepst =(preparedstatement) dbconnection.preparestatement(" insert 'keys'(requiredkeyword,noofpages,textbookcode,pagenumbers,definition) values(?,?,?,?,?) "); system.out.println(" statement prepared "); int num=1,i=0; prepst.setstring(1,requiredkeyword); prepst.setint(2,num); prepst.setstr

delphi - How to change background color of margins in RichEdit? -

i used following code add margins richedit. how can change background color? procedure tform1.button1click(sender: tobject); var lrect: trect; begin lrect := richedit1.clientrect; inflaterect(lrect, -25, -25); richedit1.perform(em_setrect, 0, integer(@lrect)); end; em_setrect merely tells richedit rectangle allowed render text. change background color of margin reserving space for, have subclass richedit handle wm_paint messages directly, can draw whatever want in space.

javascript - Better way to Add fields up and display total -

i have xpage(see below), shows several rows number fields , 3 columns (regular, overtime, total). i have code on each field under regular , overtime (onblur): var reg1 = parsefloat(document.getelementbyid("#{id:reg1}").value) || 0; var over1 = parsefloat(document.getelementbyid("#{id:over1}").value) || 0; var total1 = reg1 + over1; document.getelementbyid("#{id:total1}").value = total1; document.getelementbyid("#{id:total1}").disabled = true eventually, i'll have more rows need add. best way add them can show total regular column , total overtime column? any comments on code above appreciated. see xpage: <?xml version="1.0" encoding="utf-8"?> <xp:view xmlns:xp="http://www.ibm.com/xsp/core" xmlns:xe="http://www.ibm.com/xsp/coreex"> <xp:this.data> <xp:dominodocument var="document1" formname="testhrs"></xp:dominodocument> </xp:thi

ios - How do I convert a UITextField to an integer in Swift 2.0? -

i'm beginner @ swift, , doing testing. tell truth, barely know i'm doing yet, please try explain clearly. making random number generator app & wanted add in uitextfield user can type in guess of next randomly generated number. keep getting error when trying use if statement compare randomly generated number number entered in text field. import uikit class viewcontroller: uiviewcontroller, uitextfielddelegate { @iboutlet weak var input: uitextfield! @iboutlet weak var infolabel: uilabel! // displayed before user clicks button first time. @iboutlet weak var numberlabel: uilabel! @ibaction func go(sender: anyobject) { // remove text under button infolabel.text = " " // generate random number let randomnumber = int(arc4random_uniform(11)) // change "number label's" text in order show randomly generated number user numberlabel.text = "\(randomnumber)" /

string - Python: Most frequent character counter -

i trying create program asks user input string , displays occurring characters in string. cannot use built in features such dictionary. think problem have infinite loop. how can fix this? here code: string = input('enter string:') #space popular character pop_char = '' #initialize number of times character appears num = 0 #initialize index index = 0 # pick 1 character @ time ch in string: #initialize character counter cc=0 #go through entire string , compare character string characters while index < len(string): #if same (converted lower case), tally 1 cc if ch.lower() == string[index].lower(): cc = cc + 1 index = index + 1 #if count greater or equal previous count, use #popular character if cc >= num: num = cc pop_char = ch else: index = index + 1 print('the occuring letter(s):', pop_char) i found problem: if cc &g

javascript - Construct HTML from JSON object with $.each and .append -

i'm calling web service api php , response in json formatted this: "hits": { "found": 23, "start": 0, "hit": [ { "id": "data_upload_20150608_97", "fields": { "district": "city name", "street": "street name", "building_name": "blue tower", "description": "some description text.", "latlon": "0.0,0.0", "website": "http:\/\/www.example.com/id" } } response retrieved $.getjson following: $("#myform").submit(function(event) { event.preventdefault(); var search_term = $("#search_txt").val() if(search_term.length > 0) { $.getjson("assets/php/search.php?query="+search_term, function(result) { process_result(result); }); } }); what i

r - Displaying multiple ggvis plots simultaneously? -

i have 2 ggvis plots display side side in r (shiny). in server.r file, have vis %>% bind_shiny("plot1") vis2 %>% bind_shiny("plot2") both vis , vis2 work when displayed individually, not together. ui.r code display them column(6,div(class='span12',align="center",textoutput("title")), ggvisoutput("plot1"),align=left), column(6,div(class='span12',align="center",textoutput("title")), ggvisoutput("plot2"),align=left) when used together, can't show.

android - dumpsys SurfaceFlinger output interpretation -

recently, have started using dumpsys surfaceflinger gather information android graphics. work on development board called odroid-xu3. display dell monitor connected board through hdmi cable. in last few lines of output of above command, have 2 displays, while expect have one. 1 of them display[0] , other 1 display[1] . type column of each of displays hwc or gles . times both hwc or gles , other times 1 hwc , other 1 gles. what difference between display[0] , display[1]? have tried find documentation understand how interpret output of aforementioned command, have not found useful. it have dumpsys output in question, can make couple of general observations. display[0] device's built-in display. display[1] "external" display, in case hdmi. these 2 indices hard-wired. (well, of kitkat; don't know if they've since un-hard-wired things.) virtual displays start @ index 2. the chunk of text below display hardware composer dump. displays laye

java - Why isn't Collections.binarySearch outputting consistently -

so trying write program school. point of make list of cds user has in collection. program needs show list of cds both in original order (cds) , in alphabetically sorted order (cdss). information has stored in array list. have make used able add , remove programs. when when enter song "beatles - abbey road", assumed output 1 collections.binarysearch, instead outputs -1 2 times outputs 1's. seems work other songs though. i cannot remove song creates error thanks help private void buttoninitializeactionperformed(java.awt.event.actionevent evt) { //this original songs added(when initialize button pressed) collections.addall(cds, "metric - fantasies", "beatles - abbey road", "pearl jam - ten", "doors - alive", "the rolling stones - gimme shelter"); collections.addall(cdss, "metric - fantasies", "beatles - abbey road", "pearl j

python - SQLAlchemy - Handling Constraint Failures -

with sqlalchemy, if have unique column in database eg, username: username = db.column(db.string(50), unique=true) when add row breaks constraint username i’m trying add exists, integrityerror thrown: integrityerror: (integrityerror) (1062, u"duplicate entry 'test' key 'username'") is possible instead map breaking of constraint custom exception? eg.usernameexistserror i want able catch individual constraint breaks, , send response user. eg: "this username in use" is possible? or next best thing? any guidance appreciated :) the next best thing might surrounding call try ... except , parsing error message, , notifying user constructed error message. along lines, try ... except error , return custom error code flask's custom error pages .

Excel INDEX isn't working with Table reference -

i using excel office 2010. trying values specific row (or, eventually, rows) in table, found running search. can identify row in table want output data from, index function not working when tell go row database. =index(outputtable[department];$f2) is giving me error, is: =index(outputtable;$f2;column(outputtable[department])) everything can google tells me 1 or other of these should work, excel keeps giving me error, telling me problem first argument of index: reference outputtable. i've typed in manually, , i've navigated select directly. $f2 holds calculated row number search. why tell me erroring? can't figure out look. edit =index(output!$a$2:$a$30;$f2) on impulse, went ahead , tried using simple $a$2:$a$30 reference instead of outputtable[department] . still errors out, telling me $a$30 problem. (not whole reference. that.) i'm more confused. are sure should using ; opposed , ? error that, , directs me $a$30 stated.

scala - From DataFrame to RDD[LabeledPoint] -

i trying implement document classifier using apache spark mllib , having problems representing data. code following: import org.apache.spark.sql.{row, sqlcontext} import org.apache.spark.sql.types.{stringtype, structfield, structtype} import org.apache.spark.ml.feature.tokenizer import org.apache.spark.ml.feature.hashingtf import org.apache.spark.ml.feature.idf val sql = new sqlcontext(sc) // load raw data tsv file val raw = sc.textfile("data.tsv").map(_.split("\t").toseq) // convert rdd dataframe val schema = structtype(list(structfield("class", stringtype), structfield("content", stringtype))) val dataframe = sql.createdataframe(raw.map(row => row(row(0), row(1))), schema) // tokenize val tokenizer = new tokenizer().setinputcol("content").setoutputcol("tokens") val tokenized = tokenizer.transform(dataframe) // tf-idf val htf = new hashingtf().setinputcol("tokens").setoutputcol("rawfeatures")

c# - Table border does not automatically fit into contents -

Image
i have invoice being constructed via itextsharp (4.1.2). my problem lies on part of invoice wherein display terms , conditions , payment terms. following image below shows problem. however, when dynamic rows not present (i mean no selected discounts, no shipping costs , no tax, subtotal , grand total), appearance similar image. bottom border falls down far bottom instead of within cell. constraints : upgrading not yet option there printing functionalities require itextsharp 4.1.2. using html pdf not yet option because of time constraints. i hope can me this. edit : revised question reflect output , code replication. protected void btnviewpdf_click(object sender, eventargs e) { // create document in memory default settings. var document = new document(); string path = server.mappath("pdfs"); // commit document disk. pdfwriter.getinstance(document, new filestream(path + "/paymentdetails.pdf&

sql - DB2 Group By but table 2 makes duplicates -

i'm trying query iseries db2 v6r1m0. test sql statements in system navigator before using them in ado.net. i've traced issue down this, i'm not sure how fix it. select a.id , a.otherstuff , max(a.date || ' ' || a.time) adatetime /* i'm sure it's not line */ , b.id , b.city , b.state , max(b.date || ' ' || b.time) bdatetime table1 inner join table2 b on a.id = b.id group a.id, a.otherstuff, b.id, b.city, b.state what happens shows of b.cities , b.states, though want b.city , b.state max value. a.id a.otherstuff a.adatetime b.id b.city b.state b.datetime a.dup1 a.dup1 a.dup1 b.dup1 san francisco ca 1-jan 1:00 a.dup1 a.dup1 a.dup1 b.dup1 sacramento ca 1-jan 2:00 a.dup1 a.dup1 a.dup1 b.dup1 other cities wa 11-jan 3:00 a.dup2 a.dup2 a.dup2 b.dup2 san francisco ca

Oracle sql convert timestamp into format -

i have timestamp column 'ts'. need convert format: 'dd-mon-yyyy hh24:mi' . i used complete requirement: to_char(ts, 'dd-mon-yyyy hh24:mi'). the problem returns string. using oracle apex , outputting in table. table allows sorting. when sort sorts column string , not date, sorting not accurate. how can convert timestamp format need while still being timestamp/date field (any type long accurately sort real dates). @sstan right. there 4 date formats can set @ workspace level, , @ application level: application date format, application date time format, application timestamp format, , application timestamp time zone format. way timestamp stays timestamp , sorts correctly. select application, click on edit application properties button (top rightish), click on globalization button (top leftish), , there can set date formats.

How do I set and check a boolean variable in a for loop in a windows batch file? -

i'm pretty new windows batch files i'm sure question has obvious answer i've been digging around online hours , haven't been able find it. when run following batch file, why doesn't output "it worked!" ? @echo off set /a _converted="0" set _converted if _converted==0 (echo worked!) else (echo didn't work) output: _converted=0 didn't work but (i'm not sure how reproduce), outputs: environment variable _converted not defined here's i've tried: set vs set /a quotes in different places ( set /a "_converted=0" vs. set /a _converted="0" ) "if use of logical or modulus operators, need enclose expression string in quotes." my problem in loop can reproduce issue outside of loop don't think delayed variable expansion or this question helps me though looked similar. put %'s around variable before checking value. use delayed expansion if in loop as @aacini mentione

Exception trying to post a link on Facebook page using grahp API for PHP -

i've searched among other questions here on stackoverflow , on other websites, couldn't find solution, because seems fb changes authentication method, old solutions no more valid. i'm using sdk4 , code have @ moment facebooksession::setdefaultapplication($app_id, $app_secret); $session = facebooksession::newappsession(); try { $session->validate(); } catch (facebookrequestexception $ex) { echo $ex->getmessage(); } catch (\exception $ex) { echo $ex->getmessage(); } if($session) { try { $response = (new facebookrequest( $session, 'post', '/me/feed', array( 'link' => 'www.mysite.it', 'message' => 'some text' ) ))->execute()->getgraphobject(); echo "posted id: " . $response->getproperty('id'); } catch(facebookrequestexception $e) { echo "exception occured, code: "

asp.net mvc 4 - MVC Returning to a view and showing the partial view that was there -

alright, working mvc 4 make web app. still new mvc , have hit road blocks , got past them, having trouble finding answer current problem. my main view, course, has several partial views, allcourses , currentcourses, user can switch between couple links. displays list of courses database mainly, links change display based on date. course view has button takes them entirely new view, details, displays content course. in details view there return link takes me previous view, course. what need return link take them previous view, display partial view showing when clicked view course details, aka if on allcourses partial view when return want partial view show , same if on currentcourses. edit:: my partial views in main view handled by: <ul id="view-options"> <li><a href="javascript:getall();">view </a></li> <li><a href="javascript:getcurrent();">view current</a></li> </ul> &l

windows - How do I delete files and folders in sub-directories but skip delete for certain file names in Ruby? -

i'm looking way delete files in sub-directories no matter depth keep exclusion list of files not delete. exclude list = [my.file] given folder structure (folders end /) one/ my.file two/ x.x x.x xxx/ xx my.file xxxx/ xx after delete (every file not in exclude list gets deleted, , folder gets deleted if there no children) one/ my.file two/ xxx/ my.file i've been using far doesn't go below first level inside(directory) fileutils.rm_rf dir.glob('*').reject { |f| whitelist.include?(f) } end filutils remove_dir removes recursively. require "fileutils" fileutils.remove_dir("the_dir") no weakhearted whitelists though - disappears.

Inconsistent match function, if I run twice works (R) -

i trying reorder numeric vector current_qty using name according vector trade_order . after simple match, give me weird arrangement. current_qty <- getquantity(trades) print(names(current_qty)) [1] "ivvb11" "lft20210301" "ltn20180101" "ntnb20200815" "pibb11" print(trade_order) [1] "pibb11" "ivvb11" "lft20210301" "ntnb20200815" "ltn20180101" current_qty <- current_qty[match(names(current_qty), trade_order)] print(current_qty) lft20210301 ltn20180101 pibb11 ntnb20200815 ivvb11 2.15 42.59 50.00 3.89 60.00 now funny part. if run same match function twice. works. current_qty <- getquantity(trades) print(names(current_qty)) [1] "ivvb11" "lft20210301" "ltn20180101" "ntnb20200815" "pibb11" print(trade_order) [1] "pibb11"

writing koa middleware for fluxible-router (async executeAction) -

i'm trying use koa fluxible-router. express examples use similar pattern use send() directly navigateaction. react.rendertostring() right props hen called in executeaction context. 'use strict'; var react = require('react'); var app = require('./app'); var navigateaction = require('fluxible-router').navigateaction; function render() { return function *render(next) { var context = app.createcontext( { req: this.request , xhrcontext: { _csrf: 'pino' } } ); var html = null; context.executeaction(navigateaction, { method: this.request.method , url: this.request.url }, function (err) { // function executed asyncronously console.log('1'); var html = react.rendertostring(context.createelement()); }); this.body = html; console.log('2'); yield* next; } } module.exports = render;

networking - ffmpeg , 2 network cards and multicast stream -

my knowledge of networks poor!!, newbie!! ;-) i have small server streaming ffmpeg installed on nginx 2 network interfaces p2p1 used wan provides http/ssh.... p4p1 used receive multicast data intranet. 192.168.0.1 public network gateway. 192.168.1.1 private network gateway (commented not have internet exit network) 239.0.0.*/24 multicast address. linux distribution 3.13.0-32-generic #57-ubuntu smp tue jul 15 03:51:08 utc 2014 x86_64 x86_64 x86_64 gnu/linux distributor id : ubuntu description: ubuntu 14.04.2 lts release : 14.04 codename : trusty my network interfaces config auto lo iface lo inet loopback # net1 auto p2p1 iface p2p1 inet static address 192.168.0.100 netmask 255.255.255.0 gateway 192.168.0.1 # net2 auto p4p1 iface p4p1 inet static address 192.168.1.100 netmask 255.255.255.0 ### gateway 192.168.1.1 now route table root@srv:# route tabla de rutas ip del núcleo destino pasare

android - How to call a fragment from a fragment -

i making application. in application, have fragment contains listview. when click on item should start new fragment displays item website. listview fragment code : public class myfragment extends fragment { private listview mlistviewassociation; private listviewassociationadapter mlistviewassociationadapter; private arraylist<listviewassociations> mlistviewlist; private progressdialog progressdialog; public myfragment () { // required empty public constructor } @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { // inflate layout fragment view rootview = inflater.inflate(r.layout.fragment_mwl_associations, container, false); mlistviewassociation = (listview) rootview.findviewbyid(r.id.association_list); mlistviewlist = new arraylist<listviewassociations>(); string[] massciation_name ; final string webs[]; typedarray icons ; massciation_name

What is Replace Conditional with Polymorphism Refactoring? How is it implemented in Ruby? -

i came across replace conditional polymorphism refactoring while asking elimination of if..else conditional in ruby. the link can explain me how can implement same in ruby?(a simple sweet code do) the replace conditional polymorphism refactoring rather simple , pretty sounds like. have method conditional this: def speed case @type when :european base_speed when :african base_speed - load_factor * @number_of_coconuts when :norwegian_blue if nailed? 0 else base_speed(@voltage) end end and replace polymorphism this: class european def speed base_speed end end class african def speed base_speed - load_factor * @number_coconuts end end class norwegianblue def speed if nailed? 0 else base_speed(@voltage) end end you can apply refactoring again norwegianblue#speed creating subclass of norwegianblue : class norwegianblue def speed base_speed(@voltage) end end class nailednorwegianblue < norwegianblue def

javascript - How can I toggle texts and icons using jQuery? -

Image
i have accordion . when click on show details : the accordion content expand, the text change show details hide details the icon change + x click on again should toggle original state. i couldn't work. when click on it, stuck on hide details state forever. js $(".show-details-sk-p").click(function () { $(".show-details-txt-sk-p-r").text("hide details"); $(".icon-sk-p-r-toggle").attr("src", "http://s6.postimg.org/e9eydpbct/remove.png"); }); can please give me little push here ? i've put fiddle - in case needed. inspected aciton , element behavior, find #sk-p-r have class in decide whether collapsed or not. $(".show-details-sk-p").click(function () { var iscollapse = $('#sk-p-r').hasclass('in'); var text = iscollapse ? 'show details' : 'hide details'; var img = iscollapse ? 'http://s6.postimg.org/e9

regex - regular expression to find a number after a substring in python -

i have string: string = "tic_signal_12 ((task)(0))" by using regular expressions, want number after "(task)" substring not know how build expression use \d* match non-digit chars. >>> import re >>> string = "tic_signal_12 ((task)(0))" >>> re.search(r'\(task\)\d*(\d+)', string).group(1) '0'

jquery - Select element with same class and other class -

consider html: totaal: <input type="text" class="herd_buy total" name="herd_buy_total" /><br /> per animal: <input type="text" class="herd_buy peranimal" name="herd_buy_per_animal" /><br /> if user fills in total, should calculate per animal price, , other way around. the script should dynamic, since have more rows total/per animal properties. so started function. figured use class, , if selected element has class total , select peranimal class. got stuck... $(".herd_weight, .herd_buy").on('keyup', function() { var numanimals = $("[name=herd_num_begin]").val(); if( $(this).hasclass('total') ) { var s = $(this).attr('class'); $( "."+s+".peranimal" ).not(this).css('background-color', 'yellow'); } else if( $(this).hasclass('peranimal') ) { var s = $(this).attr(

Working datetime between php and mysql -

i'm want check if way correct or not. want calculate remaining time event. there 3 component it. the start datetime (in mysql datetime), retrieved mysql. the duration (minutes in integer), retrieved mysql. the current datetime, retrieved php function now(). to count: the remaining time (in time hh:mm:ss), formula (start + duration) - now my propose code is: $row = data->fetch_assoc(); $start = $row["start_time"]; // e.g: "2015-06-19 09:37:16" $duration = $row["duration"]; // e.g: 60 (minutes) $now = time(); // e.g: 1434648994 $start_dt = strtotime ($start); $remaining = ($start_dt + $duration * 60) - $now; echo "remaining time: ".$remaining. " seconds." is correct? your code calculates time until end of event. and if $start_dt lower $now negative value.

Are there performance drawbacks to using a delegated event handler in JavaScript and jQuery? -

i using delegated event handler (jquery) in javascript code stuff happens when dynamically added buttons clicked. i'm wondering there performance drawbacks this? // delegated event handler $(document).on('click', '#dynamicallyaddedbutton', function(){ console.log("hello"); }); how compare this, performance-wise? // regular event handler $("#regularbutton").on('click', function(){ console.log("hello again"); }); looking @ jquery documentation , seems events bubble way dom tree. mean further nested element is, longer event take work? edit: is there performance benefit using javascript's event delegation rather jquery's? asking similar question, , answer there useful. wondering difference between using regular event handler , delegated event handler. linked questions make seem events bubbling dom tree. delegated event handler event bubble top , down specified element? every time click prett

Understanding c++ regex by a simple example -

i wrote following simple example: #include <iostream> #include <string> #include <regex> int main () { std::string str("1231"); std::regex r("^(\\d)"); std::smatch m; std::regex_search(str, m, r); for(auto v: m) std::cout << v << std::endl; } demo and got confused behavior. if understood purpose of match_result there correctly, 1 1 should have been printed. actually: if successful, not empty , contains series of sub_match objects: first sub_match element corresponds entire match, and, if regex expression contained sub-expressions matched ([...]) the string passed function doesn't match regex, therefore should not have had the entire match . what did miss? you still entire match entire match not fit entire string fits entire regex . for example consider this: #include <iostream> #include <string> #include <regex> int main() { std::string str(&quo

html - Mailchimp different background colors for repeatable -

i'm having trouble figuring out how set mailchimp template repeatable table background colors can changed individually. currently have this .... /* @tab main event @section header @tip set background , text color main event */ .heading{ /*@editable*/background-color:#000000; /*@editable*/color:#ffffff; } .... <table border="0" class="heading padding-20" mc:repeatable> <tr> <td align="left" valign="top" width="70%"> <img src="http://placehold.it/200x40" mc:edit="logo"> </td> <td align="right" valign="top"> <a href="*|archive|*" class="view-in-browser" mc:editable>view in browser</a> </td> </tr> </table> as result can duplicate repeatable table in campaign editor. when change background color in design panel background colors of tables change, not want. understan

mysql - PHP: PDO Query returns no results, but the same query returns 4 results in phpmyadmin? -

i have written query return comments post, excluding blocked users post. have tested query in phpmyadmin , 4/5 possible comments given post (where 1 user blocked). the query looks like: $query = "select ent.entity_id, ent.profile_pic_url, ent.first_name, ent.last_name, ent.last_checkin_place, comments.content checkin_comments comments join entity ent on comments.entity_id = ent.entity_id left join friends f on ent.entity_id = :entityid comments.chk_id = :checkinid , f.category != 4 group comments.comment_id "; // bind parameters query $data = array(":checkinid" => (int)$checkinid, ":entityid" => (int)$userid); if run query on phpmyadmin values 1726 checkinid , 1517 userid expected outcome, in php 0 results. used var_dump print contents of data , shows as: array(2) { [":checkinid"]=> int(1726) [":entityid"]=

android - Sending key-value pairs payload to Google Analytics -

i'm trying send n amount of custom key-value pairs attached single hit. hit have own key category/action/label, i'm after defining own keys. i'm trying integrate google analytics application. i've followed configuration steps , works, i'm trying understand how event reporting works, , how can send own custom events off predefined key-value pairs. map<string, string> mymap = new hashmap<>(); mymap.put("hello", "world"); mymap.put("liek", "turtles"); googleanalytics analytics = googleanalytics.getinstance(context); analytics.setlocaldispatchperiod(1800); tracker tracker = analytics.newtracker(token); tracker.send(mymap); which unwelcomely received logcat error. w/gav4﹕ discarding hit. missing hit type parameter: tid=world, a=504324093 i'm experimenting other apis hitbuilders , set(), none provides clear key-value pair mapping. i think looking custom dimensions . first should create custom d