Posts

Showing posts from March, 2014

javascript - How to trigger different functions based on a radio button option? -

i'm having troubles trying trigger 2 different functions based on radio button option. i have autocomplete field, source must setted radiobutton option. can do? i have done this, far: var autocompleteone = [ "item 01", "item 02", "item 03", "item 04", "item 05" ]; var autocompletetwo = [ "item 01.2", "item 02.2", "item 03.2", "item 04.2", "item 05.2" ]; $('#options').blur(function(){ if(document.getelementbyid("optiona").attr(checked, true{ $("#autocompletecaseone").autocomplete({ source: autocompleteone }); } if(document.getelementbyid("optionb").attr(checked, true{ $("#autocompletecasetwo").autocomplete({ source: autocompletetwo }); } }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery...

datetime - PHP - Handling dates before and after christ -

im making biogram on site lists known historical figures. right now, im getting values database, , on many if statements, determine display. /* @var $bio \models\library\biography */ $birth = []; $death = []; $date = null; if($bio->getbirthmonth() != null) { if ($bio->getbirthday() != null) { $birth = [ $bio->getbirthday(), $bio->getbirthmonth(), $bio->getbirthyear(), ]; } else { $birth = [ $bio->getbirthmonth(), $bio->getbirthyear(), ]; } } else { $birth = [ $bio->getbirthyear(), ]; } if($bio->getdeathmonth() != null) { if ($bio->getdeathday() != null) { $death = [ $bio->getdeathday(), $bio->getdeathmonth(), $bio->getdeathyear(), ]; } else { $death = [ $bio->getdeathmonth(), $bio->getdeathyear(), ]; } } else { $death...

javascript - Functions In CoffeeScript -

i'm trying convert function javascript coffeescript. code: function convert(num1, num2, num3) { return num1 + num2 * num3; } but how can in coffeescript? i'm trying run function html source this: <script type="text/javascript" src="../coffee/convert.js"></script> <script type="text/javascript"> convert(6, 3, 10); </script> but won't work , error saying: referenceerror: can't find variable: convert how correct this? you need export convert function global scope. see how can coffescript access functions other assets? window.convert = (num1, num2, num3) -> num1 + num2 * num3

css - How to get Bootstrap Grid without gaps per row -

Image
attached screenshot of bootstrap grid. wondering how make divs in lower row sit underneath ones above without sitting on new row. this code snippet of each item <div class="col-xl-2 col-lg-3 col-md-4 col-sm-6 col-xs-12 thumb"> <a class="thumbnail" href="#"> <img class="img-responsive" src="<?php echo $row['productimage']; ?>" width="100%" alt=""> <div class="postcontent"><h3><?php echo $row['productname']; ?></h3><br> <p><?php echo $row['producttext']; ?></p> </div> </a> </div> thanks heaps place ones want have aligned vertically in same col , make width 100% . wrap in columns then. might want add top margin @ top , bottom simulate gutter

android - What difference between static and non static viewholder in RecyclerView Adapter? -

what advantages of approach (using static nested class in class myadapter extends recyclerview.adapter): static class myvh extends recyclerview.viewholder {...} and approach (using member inner class): class myvh extends recyclerview.viewholder {...} or doesn't affect performance , both approaches used? it more java question android question. recommended use static inner classes avoid memory leaks if take instances out of class. can have @ this awesome post explains memory leaks on inner classes. basically nyx says: if declare viewholder static can reuse in other adapters. anyway, not recommend it, create new separated class , use multiple places, make more sense. 1 class 1 purpose. in case of view holders, classes used inside adapter, instances should not go fragment or activity or elsewhere definition. means having static or non-static, in case of view holders, same. answering performance question, can have @ this answer. static 1 take less memor...

Smooks: Outputting EDI from Java -

inspired proposed solution in smooks edi writer , have following java code: // creates minimal edi message 1 field populated edifactv3d98amedpid edi = new edifactv3d98amedpid(); unbinterchangeheader header = new unbinterchangeheader(); unbinterchangeheader.s002senderidentification s002senderidentification = new unbinterchangeheader.s002senderidentification(); s002senderidentification.sete0004senderidentification("test"); header.sets002senderidentification(s002senderidentification); edi.setunbinterchangeheader(header); smooks smooks = new smooks("edi-output-smooks-config.xml"); // sets access exports specified in smooks config executioncontext executioncontext = smooks.createexecutioncontext(); exports exports = exports.getexports(smooks.getapplicationcontext()); result[] results = exports.createresults(); smooks.filtersource(executioncontext, new javasource(edi), results); list<object> objects = exports.extractresults(results, exports); javaresult.re...

Speech to text, java speech API, where to find it? -

Image
so wanted create small application laboratory @ home, , need speech recognition java speech api seems pretty solution problem of finding suitable api. have tried sphinx-4 api couldn't find jar-files in prealpha.zip package downloaded, find header files c projects... looked freetts api that's text speech , not other way around! so if can find java speech api glad if send me download link , not link oracle's webpage because have given amount of time , still have not found download link bin/lib folder full of jar-files... thanks help! please excuse english, comment question if don't understand part of it! :) search sphinx , pick jars in sphinx4-data , sphinx4-core . have added screen clarification. on right bottom select artifact tab instead of maven download button.

php - Symfony DomCrawler. Filter condition -

i have script in symfony 2: use symfony\bundle\frameworkbundle\controller\controller; use symfony\component\domcrawler\crawler; class mycontroller extends controller { .... foreach($crawler->filter('[type="text/css"]') $content){ /* make things */ } foreach($crawler->filter('[rel="stylesheet"]') $content){ /* make things */ } ¿can $crawler->filter accept various conditions , in 1 foreach? example: foreach($crawler->filter('[rel="stylesheet"] or [type="text/css"]') $content){ /* make things */ } the filter function takes using standard css selector, so: foreach ($crawler->filter('[rel="stylesheet"],[type="text/css"]') $content) { /* make things */ } should job.

excel - Avoiding Activate by saving files when using many workbooks -

i have special cases, cannot find way around activate considered bad (slow) coding in vba. in case looping on sheets of original workbook, copy contents sheets - under conditions - paste these contents new workbook , try save result csv-files. doing using following save-routine: private sub saveworksheet(pathx, wbkn, sheetn) path = pathx & ".csv" workbooks(wbkn).sheets(sheetn).activate workbooks(wbkn).saveas filename:=path, _ fileformat:=xlcsv, local:=true, createbackup:=false end sub if don't use activate error. there way avoid when saving files? edit: info on why activate considered bad: how avoid using select in excel vba macros excel select vs activate edit2: after research , testing, found out problem not save method itself, rather context of multiple workbooks being involved. not think can prevent activate when saving file another workbook or when running macro on another workbook, while doing stuff on 'original' base-workbook. can ...

java - How to extract content from a pdf having both text and images? -

i have pdf file has 2 types of pages, normal text pages , pages coming scanned documents. text content can extracted usin either pdfbox or tika. these libraries can't ocr , need tess4j . how can combine tess4j , pdfbox (or tika) in order extract content both text , scanned pages? edited:------ found solution follows doesn't work well for(pdpage page:pages){ pdpropertylist pagefonts = page.getresources().getproperties(); map<string,pdxobjectimage> img = page.getresources().getimages(); set<string> keys = img.keyset(); iterator iter = keys.iterator(); while(iter.hasnext()){ string k = (string) iter.next(); system.out.println(k); pdxobjectimage ci = img.get(k); ci.write2file(k); file imagefile = new file(k+".jpg"); tesseract instance = tesseract.getinstance(); try{ string result = instance.do...

c# - ".TextToColumns" with ".NumberFormat" -

i've got text file i'm trying save xlsx file. before saving , closing need perform texttocolumns , need column "h" remain in "text" format. the below code converts column "h" "text" format when ".texttocolumns" executes column "h" changes "custom" format changing the data. microsoft.office.interop.excel.application oxl; microsoft.office.interop.excel.workbook datab; microsoft.office.interop.excel.worksheet datas; string path = @"c:\users\fakename\desktop\extracted_formatted samplefile.csv"; oxl = new microsoft.office.interop.excel.application(); datab = oxl.workbooks.open(path, 0, false, 5, missing.value, missing.value, false, missing.value, missing.value, false, false, missing.value, false, false, false); datab.application.displayalerts = false; oxl.visible = true; datas = (microsoft.office.int...

ElasticSearch Percolator Scalability -

if documents indexed on tags , 100,000 users interested in documents specific tags, percolator evaluate 100,000 queries or querying on tags present in given document? as the docs say: after special query build based on terms in in-memory index select candidate percolator queries based on indexed query terms. these queries evaluated in-memory index if match. the selecting of candidate percolator queries matches important performance optimization during execution of percolate query can reduce number of candidate matches in-memory index needs evaluate. it means queries match specific field present in documents want percolate run. if have 100 000 queries field tag , yes, 100 000 queries run, must check if tags interested in present in array (if array).

python - modelling crowd movement with matplotlib -

i model basic crowd movement python. want show animation. have made following program test matplotlib : import numpy np import matplotlib.pyplot plt matplotlib import animation #size of crowd n = 100 def gen_data(): """ init position , speed of each people """ x = y = np.zeros(n) theta = np.random.random(n) * 360 / (2 * np.pi) v0 = 0.1 vx, vy = v0 * np.cos(theta), v0 * np.sin(theta) return np.array([x, y, vx, vy]).t def init(): line in lines: line.set_data([],[]) return line, def update_lines(i, lines, data): d, line in zip(data, lines): d[0:2] += d[2:4] if abs(d[0]) > 5: d[2] *= -1 if abs(d[1]) > 5: d[3] *= -1 line.set_data(d[0] ,d[1]) return lines fig = plt.figure() ax = plt.axes(xlim=(-5,5),ylim=(-5,5)) lines = [plt.plot([],[], 'ko')[0] in range(n)] data = gen_data() anim = animation.funcanimation(fig, update_lines, init_func=init, fargs=(lines, da...

Jquery mobile Multiselect with filterable selection issue after filteration is done -

i trying use jquery mobiles custom select filterable feature multiselect. it works great when dont filter options. when filter option selection not happening properly. it checks other option list. demo on jsfiddle in jsfiddle demo, once u open dropdown, apply filter , try select english , see issue below code <div class="page_1"> <!-- form starts --> <div class="form_wrap" id="form_wrapper"> <form method="post" name="frm_registration" autocomplete="off" style="margin:0px"> <div class="formfd_wrap "> <label>mother tongue</label> <select id="mother_tongue" name="mother_tongue" multiple="multiple" data-native-menu="false" class="filterable-select reg_inputdrpbox"> <option value="assamese" >assam...

video.js - Videos.js bypass embed video -

is possible bypass url link own-host name , video content actual host vimeo videojs. where edit in .js file or something? don't know how it. thank you! there vimeo plugin videojs: https://github.com/exon/videojs-vimeo this lets use videojs show vimeo videos.

Is it possible to provide write permissions for slave/standby servers in postgresql in a cluster? -

i have 2 servers on same network have live streaming master-slave structure. i'm not using tools slony or bucardo. it's simple replication process can accomplished changing parameters in .conf files. curently can accept read/write on master , read-only on slave. want master-master structure, wherein both servers can accept read write requests. possible in postgresql 9.3 or above? is possible provide write permissions slave/standby servers in postgresql no. it's simple replication process can accomplished changing parameters in .conf files so, postgresql's built-in streaming replication. however want master-master structure, wherein both servers can accept read write requests. possible in postgresql 9.3 or above? there's extension postgresql 9.4 adds multi-master, called bdr. see http://bdr-project.org/docs/stable/ , http://2ndquadrant.com/bdr . it's not ready widespread adoption new database users though - should pretty confi...

wpf - How to use passchar conditionally in c# login form -

i have created login form default shows text 'enter username' in user name text field when 1 clicks on password text field , vice versa shows 'enter password' when clicked on username text field now want use pwd.passchar = "*" here. password field doesn't shows 'enter password' text *****. should display text unless user starts typing actual password here code - public login() { initializecomponent(); if (pwd.text == "enter password") { // don't show $$ in password text field } else { pwd.passwordchar = '*'; } } private void textbox1_click(object sender, eventargs e) { uname.text = string.empty; if (string.isnullorwhitespace(pwd.text)) { pwd.text = "enter password"; } } private void textbox2_click(object sender, eventargs e) { pwd.text = ...

Enfore different order for reading files in logstash -

i have multiple log files written in descending order. i.e contents of xyz.log.5 written before contents of log xyz.log.4. number of log files unknown. so, i'm using wildcard read files input{ file{ path => "path/to/file/xyz.log.*" ...... ...... } } but reading files in ascending order. reading in descending order important because logs contain time based events span on multiple files , i'm calculating time intervals using elapsed filter. so, i'm getting incorrect time intervals reading order different. is there way force logstash read in descending order?

spring - Issue with Richfaces Datatable filter search -

here scenario have richfaces datatable have added filter concept below <rich:column width="250px" sortby="#{test.name}" filterexpression="#{fn:equalsignorecase(test.name, filtervalue)}" filtervalue="#{inventoryfilter.name}"> and bean initialized application-context.xml , scope of bean request edit:- <bean id="inventoryfilter" class="com.alu.ipprd.bsm.soa.portal.filter.inventoryfilter" scope="request" /> now when switching tab ,let suppose tab a tab b old search value still coming while each tab have defined switchtype="server" so mean when swtiching tabs request going server application should initialized inventoryfilter.java class. but not working please guide me doing wrong? edit:- tab code <rich:tabpanel id="tabpanel1" switchtype="server" selectedtab="#{panelmenubean.selectedtabname}" ...

C# Telegram Bot. Getupdate method -

telegram api uses this method return messages , offset update_id. how can last message properly? you should store last update_id in database , in next request pass telegram +1 using offset parameter in query.

Looking for a free video stream or Mjpeg stream to stream on local network -

do know of software can stream desktop or window video stream or mjpeg? i have tried vlc keeps crashing. you try ffmpeg - it's pretty versatile.

EPPlus - How to remove a comment from a cell? -

in epplus can add comments cell in worksheet using worksheet.cells[x, y].addcomment() but how remove comment given cell - there isn't worksheet.cells[i, j].removecomment() - need leave other comments in place thanks in advance suggestions one think simple :). check out: [testmethod] public void comment_test() { var existingfile = new fileinfo(@"c:\temp\temp.xlsx"); if (existingfile.exists) existingfile.delete(); using (var package2 = new excelpackage(existingfile)) { var ws = package2.workbook.worksheets.add("sheet1"); ws.cells[1, 1].addcomment("comment test 1", "me"); ws.cells[1, 2].addcomment("comment test 2", "me"); ws.cells[1, 3].addcomment("comment test 3", "me"); //alternate way add comment ws.comments.add(ws.cells[1, 4], "comment test 4", "me"); //remove middle comment ...

Get Django User group in HTML -

i trying django user's group in html if tag. tried: {% ifequal user.groups.all.0 'abc' %} {% endif %} but not working. other way there? try this: {% group in request.user.groups.all %} {% if group.name == 'abc' %}{% endif %} {% endfor %} or {% if request.user.groups.all.0.name == 'abc' %}{% endif %} you have access current user object request context variable. this, make sure django.template.context_processors.request in template settings. request.user.groups.all.0 returns group model object, have compare against name field.

java - javax.persistence.PersistenceException: Unable to locate persistence units -

i had maven project, converted jpa project works maven. persistence.xml follows: <?xml version="1.0" encoding="utf-8"?> <persistence version="2.1" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> <persistence-unit name="my-pu" transaction-type="resource_local"> <description>my persistence unit</description> <provider>org.hibernate.ejb.hibernatepersistence</provider> <class>model.entity.tweet</class> <class>model.entity.tweethashtag</class> <class>model.entity.tweeturl</class> <class>model.entity.user</class> <exclude-unlisted-classes>true</exclude-unlisted-classes> ...

nsdate - Objective-c timeIntervalSince1970 return 0 -

nsuinteger currenttime = [[nsdate date] timeintervalsince1970]; here current time 0. can tell me reason this? nsuinteger currenttime = [[nsdate date] timeintervalsince1970]; nslog(@"%d",currenttime); this gives me correct value of current time in milliseconds .

javascript - Press enter on form input to make it lose focus -

i have form input box , hidden submit field: <form action="javascript:void(0);"> <input type="text"> <input type="submit" style="display:none;"> </form> i make when click enter, input box loses focus. how can accomplish this? try out. please note need include jquery file work. <form action="javascript:void(0);"> <input type="text" id="txtfocus"> <input type="submit" style="display:none;" id="btnhidden"> </form> <script> $("#btnhidden").on('click', function() { $('#txtfocus').blur(); }); </script>

php - Pass a value and call previous, current and next values in order -

i'm using pdo. want able fetch 3 values 3 different rows using single query. i've got table below. itemid | item_name ____________________ 125 | apple 297 | lychee 851 | mango 005 | orange 1009 | strawberry i want able send item_name , sort table item_name , able call next item_name , previous item_name . how can this? e.g.: if $passeditem orange want output mango , orange , strawberry . if $passeditem mango want output lychee , mango , orange using on() operator did not work because 1 item_name passed on query. $sql = "select item_name itemstable item_name = :passeditem" order asc; $stmt = $con_db->prepare($sql); $stmt->execute(array(':passeditem'=>"orange")); $rslt = $stmt->fetchall(pdo::fetch_assoc); this solution based on mysql: conditionally selecting next , previous rows . $sql = "(select item_name itemstable item_name < ? order...

python - cosd and sind with sympy -

there seems no equivalent cosd , sind in sympy (ie cosine , sine arguments in degrees). there simple way implement functions ? for numpy, did : numpy.cosd = lambda x : numpy.cos( numpy.deg2rad(x) ) something : sympy.cosd = lambda x : sympy.cos( sympy.pi/180*x ) works evaluation, expression printed : cos(pi*x/180) which not great readability (i have complicated expression due 3d coordinates changes). there way create sympy.cosd function evaluates cos(pi/180 * x) prints cosd(x) ? sympy have radian converter , in mpmath module. sympy.cosd = lambda x : sympy.cos( sympy.mpmath.radians(x) )

portaudio - How to enable WASAPI exclusive mode in pyaudio -

i'm using these precompiled binaries of pyaudio wasapi support. want play wav file via wasapi. found index of default output device api: import pyaudio p = pyaudio.pyaudio() print p.get_host_api_info_by_index(3) >>{'index': 3, 'name': u'windows wasapi', 'defaultoutputdevice': 11l, 'type': 13l, 'devicecount': 3l, 'defaultinputdevice': 12l, 'structversion': 1l} then play wav file via device: import pyaudio import wave chunk = 1024 wf = wave.open('test.wav', 'rb') # instantiate pyaudio (1) p = pyaudio.pyaudio() # open stream (2) stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=wf.getframerate(), output_device_index=11, output=true) # read data data = wf.readframes(chunk) # play stream (3) while data != '': stream.write(data) data = wf.readframes(chunk) ...

JQuery - go down with selector name -

Image
i created code: $("input[name*='gridview1$ctl02']").each(function () { if(this.type == 'checkbox'){ if(this.checked == true){ alert("test") } else { alert("test2") } } }) its when write $("input[name*='gridview1$ctl02']") need array of ct101,ct102,ct103 i need this: $("input[name*='gridview1']").find("ct").each ... you can simple create selector match element name starts gridview1: $("input[name^='gridview1']").each(function () {if(this.type == 'checkbox'){if(this.checked == true){alert("test")}else{alert("test2")}}}) alternative if want text inputs: $("input[name^='gridview1'][type='text']").each(function () {if(this.type == 'checkbox'){if(this.checked == true){alert("test")}else{alert("test2")}}}) ...

java - Unable to see the output while recording the key strokes using jnativeHook -

i'm trying record keystrokes when ever perform key events left,right,move,press,release etc.initially when wrote code , compiled able record key strokes.however,when compiled after little bit of code indentation showing following statement process finished exit code 0 below posted code: public class key_logger implements nativekeylistener { public void nativekeypressed(nativekeyevent e) { system.out.println("key pressed: " + nativekeyevent.getkeytext(e.getkeycode())); if (e.getkeycode() == nativekeyevent.vk_escape) { globalscreen.unregisternativehook(); } } public void nativekeyreleased(nativekeyevent e) { system.out.println("key released: " + nativekeyevent.getkeytext(e.getkeycode())); } public void nativekeytyped(nativekeyevent e) { system.out.println("key typed: " + e.getkeytext(e.getkeycode())); } public static void main(string[] args) { try { globalsc...

html - append jquery with forms -

i trying append jquery form value table under ‍‍‍‍ <td> tags. however reason wont append or post value inside table. here's jquery: $(document).ready(function(){ $('form').submit(function(){ var fname= $('input#form_fname').val(), lname = $('input#form_lname').val(), email = $('input#form_email').val(), phone = $('input#form_phone').val(); $('tr').append('<td>'.fname.'</td>'); }); }); here's jsfiddle: https://jsfiddle.net/zbb6fqtc/ any idea? there 2 problems. in javascript string concatenation should use + operator not . . you don't prevent default action of event. page submitted/refreshed , don't see appended element. $('form').submit(function(event) { event.preventdefault(); var fname= $('input#form_fname').val(); // ... $('tr').append('<td>' + fname + '</...

Regex string: specific requirement -

i trying regex string right don't seem working should. i have numeric field should have 5 digits. digits can start 04xxx , 5xxxx this string not covering completly: /[05][0-9][0-9][0-9][0-9]/ it forces start 0 or 5 followed 4 digits, allows example 012345 any ideas? try regex pattern: ^(04|5\d)\d{3}$

c# - What is the proper way of using dbContext along with Repositories and Services -

i discovered used dbcontext badly. i tried have single instance of dbcontext per app , injected dbservcies , next repositories. var context = new dbentities(); simpleioc.default.register<ipaymentlogservice>(() => new paymentlogservice(context)); public paymentlogservice(installmentsentities context) { _context = context; _paymentlogrepository = new paymentlogrepository(context); } i have repository created follows: public paymentlogrepository(dbentities context) { _context = context; } when adding row via entity framework this: public int add(paymentlog entity) { _context.paymentlogs.add(entity); var affectedrows = _context.savechanges(); return numberofaddeditems; } my _context existed whole time new pending changes done e.g via setter therefore got additional updates in database. what pattern of using dbcontext. should instantiated per method/action, or per service/repository?

amazon web services - Loadbalancer for multiple web applications on single EC2 cluster -

this may seem obvious people have worked aws have lot of trouble figuring out on how set loadbalancer on 2 ec2 instances hosting multiple websites. we have 2 windows 2012 r2 machines set up, have created 1 elb , have read, know can point elb 1 location (assuming default site on servers). how go pointing other elbs create point other applications on server? (not sure if info relevant add : whole setup part of vpc, domain controller environment , web servers in public subnet. ) one way solve running applications in multiple iis websites. each of websites should have different site binding different host name. use dns name of load balancer each website. alternatively can use domain name configured in route53 , use record point load balancer.

Couchbase N1QL: index and query on array fields -

platform: couchbase server 4.0 beta, java client 2.1.3 i looking similar sql join. example have documents of form field2 embedded in document instead of in separate table have in relational db: {field1:" ..", field2:[{key:1, ...},{key:3, ...},..],...}. how can achieve this: select * bucket field2.key=3; and how can index key, hypothetical example: create index idx_key on bucket(field2.key); what if did this: select * `your-bucket-here` fields field in fields.field2 satisfies field.key = 3 end this way long 1 nested array item contains value, returned. in terms of creating index, looking create secondary index or primary index? this: create primary index index_name on `your-bucket-name-here` using gsi; create index index_name on `your-bucket-name-here` using gsi; let me know how goes! best,

arrays - How to create a customized matrix in R where first few columns are zero and rest are an Identity Matrix? -

suppose have matrix a of order k2*k k=k1+k2 such k1=k-k2 . characteristic of matrix a such first k1 columns 0 , remaining k2*k2 identity matrix. how create such customized matrix in r? note: for smaller dimensions of k1 , k2 , it's easy. looking automated command handling larger dimensions of k1 , k2 . k <- 20 k2 <- 15 k1 <- k - k2 diagonal <- diag(k2) zeros <- matrix(0, nrow = k2, ncol = k1) result <- cbind(zeros, diagonal)

Variable as the property name in a JavaScript object literal? -

this question has answer here: using variable key in javascript object literal 6 answers possible duplicate: how add property javascript object using variable name? use variable property name in javascript literal? is possible add variable property name of object in javascript, this: var myvar = "name"; var myobject = { {myvar}: "value" }; you can use [] syntax use expression property name (compared .prop , prop: value syntaxes treated strings): var myobject = {}; var myvar = "name"; myobject[myvar] = "value"; there no way use inside object literal, though. have create object first , assign each property separately. edit with es6, possible using computedpropertyname , manifests in form of following syntax: var myvar = "name"; var myobject = { [myvar]: "value...

Recreate/Destroy the view in ViewPager - Android -

i using viewpager show images custom adapter. when in particular image, able zoom image. leave image in zoomed state , move next image. when go previous image, still in zoomed state left it. there way destroy view or recreate it. wont left in zoomed view. in advance.

php - Bigcommerce Product SKU's -> Options -

having little trouble bigcommerce api when trying access product sku's 'options' array_object. i can access else within sku object, not options - doing print_r on $sku->options doesn't show returned data , var_dump shows '(bool)false' . here code: $filter = array('sku' => '940801db'); $skus = bigcommerce::getskus($filter); foreach ( $skus $sku ){ echo '<pre>'; print_r( $sku->options ); echo '</pre>'; } any ideas how access array/object? further info: if print_r($sku) get: array ( [0] => bigcommerce\api\resources\sku object ( [ignoreoncreate:protected] => array ( [0] => product_id ) [ignoreonupdate:protected] => array ( [0] => id [1] => product_id ) [fields:protected] => stdclass object ( [id] => 1 ...

math - Elliptic curve point addition over a finite field in Python -

in short, im trying add 2 points on elliptic curve y^2 = x^3 + ax + b on finite field fp. have working implementation on r, not know how alter general formulas ive found in order them sustain addition on fp. when p not equal q, , z sum of p , q: dydx = (q.y - p.y)/(q.x - p.x) z.x = dydx**2 - p.x - q.x z.y = dydx * (z.x - p.x) + p.y when p equals q, again z sum: dydx = (3 * (p.x)**2 + self.a)/(2 * p.y) z.x = dydx**2 - 2 * p.x z.y = dydx * (z.x - p.x) + p.y these same formules found here . needs modified? clarification: code above works elliptic curves on r. looking find needs changed work addition of points on finite field of order p. there couple of issues here. first have wrong formulas: formulas negation of sum, or equivalently third point of curve lies on line through p , q. compare formula linked on wikipedia, , you'll see have z.y negation of value have. a second issue formulas don't take origi...

scala - Spray Json `RootJsonFormat`'s Invariance? -

given following: scala> trait parent defined trait parent scala> case class boy(name: string) extends parent defined class boy scala> case class girl(id: int) extends parent defined class girl i tried define implicit formatter (de-serialization , serialization) them: scala> object formats extends defaultjsonprotocol { | implicit val format: rootjsonformat[parent] = jsonformat1(boy.apply) | implicit val girlformat: rootjsonformat[parent] = jsonformat1(girl.apply) | } but got compile-time errors: <console>:22: error: type mismatch; found : spray.json.rootjsonformat[boy] required: spray.json.rootjsonformat[parent] note: boy <: parent, trait rootjsonformat invariant in type t. may wish define t +t instead. (sls 4.5) implicit val format: rootjsonformat[parent] = jsonformat1(boy.apply) ^ <console>:23: error: type mismatch; found : spray.json.rootjso...

ios - Determine filetype of path string in Swift -

i need decide filetype of file filename in string. decided last 3 characters of string decide filetype is. how last 3 characters in string. example var filename = "test.pdf" i need pdf alone. is there other better way check file type other this. please suggest me also. because think, won able recognise if filetype comes in 4 characters "jpeg" , other stuff. in advance. i think looking : the path extension, if any, of string interpreted path. (read-only) declaration swift var pathextension: string { } discussion the path extension portion of last path component follows final period, if there one. extension divider not included. following table illustrates effect of pathextension on variety of different paths: receiver’s string value string returned “/tmp/scratch.tiff” “tiff” example : file.pathextension https://developer.apple.com/library/mac/documentation/cocoa/reference/foundation/classes/nsstring_class/index.html#//app...

c# - Entity Framework 6 - How to update entities with Collection child properties -

i'm new entity framework please bear me. i have these entities in dal public class timesheet { [key] public int timesheetid { get; set; } public datetime signin { get; set; } public datetime signout { get; set; } public virtual icollection<timesheetdetail> timesheetdetails { get; set; } } public class timesheetdetail { [key] public int timesheetdetailid { get; set; } public string description { get; set; } } and got following error (attaching entity of 'model' failed because entity of same type has same primary key value) when trying update record, update code below : public class timesheetservice : itimesheetservice { private readonly irepository<timesheet> _repo; private readonly irepository<timesheetdetail> _repo2; public void edittimesheet(timesheet obj) { _repo.update(obj); //update timesheet <-- error here //loop ...

Does running under local IIS limit the number of Signalr connections -

i testing mvc web app. it uses signalr. i running under local iis to test web client navigate page in chrome browser , open same web page in different tabs. the max number can open 2 tabs. if close 1 of these tabs , open same page on different pc not open. using safari browser on other pc. if connect if close other browser down on 1st pc. yet, if run same code on hosted server can have many may client connections. is limit amount of client connections can have running under local iis server or there setting need make somewhere? thanks ps post relevant code not think code issue. think has configuration. you can hit 2 limits - limits on server side , limits on browser side. here blog post containing limits on server side. can see limit depends on os version , iis version. can find browser limits in stackoverflow thread . note client can open more 1 concurrent requests (e.g. in case of long polling poll request active , data sent on separate request). ...

couchbase lite - update textview from couchdb using changelistener android -

i trying real time changes on document using changelistener, have refresh tha mobile app see change. here gist https://gist.github.com/mikekaraa/89416ea8b074c71d7153 please me out if have solution would tie changelistener() event time interval such e.g after every 3 or 5 seconds fired , triggers next sequence of events if @ document changed within time span. hope helps.

Alerting User to pauses in batch -

i creating long batch script run hours, , various purposes have included way users if pause in script in case of errors, need use machine else, or in case cannot watch time. i've been using pause wait on input, i'd have sort of way user explicitly told batch stopped, flashing icon on taskbar or something. is there simple way or require more few lines of code? msg console /time:3600 "the batch file waiting input" & pause

html - Get the Value from another PHP page -

hello have below form in page viewsensordata.php ... $refresh = ($_post['refresh']); $link_address="viewsensordata.php?view=".$view; ?> <form method="post" action="<?php echo $link_address;?>"> <select id="refresh" name="refresh"> <option value="-">select seconds</option> <option value="1">1 second</option> <option value="2">2 seconds</option> <option value="3">3 seconds</option> <option value="4">4 seconds</option> <option value="5">5 seconds</option> <option value="10">10 seconds</option> <option value="15">15 seconds</option> <option value="30">30 seconds</option> <option value="60">60 seconds</option> </select> <input type="su...

javascript - how to make items required when checkbox is ticked? -

i trying set textbox, , dropdownlist , textbox datepicker required if checkbox ticked. if checkbox not ticked fields not required, if ticked fields required. <table> <tbody> <tr> <td class="header">haz trained?</td> <td></td> <td> <asp:checkbox runat="server" id="chkhaztrained" onclick="updatevalidator();"/> </td> </tr> <tr> <td class="header">haz license no</td> <td></td> <td> <asp:textbox runat="server" id="txthazlicenseno"></asp:textbox> <asp:requiredfieldvalidator id="rfvhazlicenseno" controltovalidate="txthazlicenseno" errormessage="you must enter license no." runat="server" /> </td> </tr> <tr> <td...

php - phpseclib - exit callback? -

i'm using code ssh2 examples: <?php include('net/ssh2.php'); $ssh = new net_ssh2('www.domain.tld'); if (!$ssh->login('username', 'password')) { exit('login failed'); } function packet_handler($str) { echo $str; } $ssh->exec('ping 127.0.0.1', 'packet_handler'); ?> this working well, want quit stream after xx seconds. so i've amended follows : <?php include('net/ssh2.php'); $st = time(); $dur = 10; $ssh = new net_ssh2('www.domain.tld'); if (!$ssh->login('username', 'password')) { exit('login failed'); } function packet_handler($str) { global $st, $dur, $ssh; echo $str; $now = ceil(time() - $st); if ($now >= $dur) { $ssh->disconnect(); unset($ssh); } } $ssh->exec('ping 127.0.0.1', 'packet_handler'); ?> this works , exits packet handler, folllowing notices being shown: notice : connection c...

ios - Passing data between two ViewControllers (delegate) - Swift -

this question has answer here: passing data between view controllers 35 answers i have 2 viewcontroller's. firstvc - have label , button segue "modal" secondvc - have pickerview , button (back firstvc): @ibaction func bntback(sender: anyobject) { self.dissmissviewcontrolleranimatied(true, completion: nil) } and created delegate in secondviewcontroller as: protocol senddatadelegate { func senddata(text:string) } next: class secondvc: uiviewcontroller, uipickerviewdatasource, uipickerviewdelegate { var delegate: senddatadelegate! var firstvc = firstvc() var arr = ["first", "second", "third"] @iboutlet var pickview: uipickerview! override func viewdidload() { super.viewdidload() pickview.datasource = self pickview.selegate = self ...