Posts

Showing posts from August, 2015

java - dofilter not giving pdf as output on response -

i trying show pdf output on browser. here code in dofilter class of servlet. getting byte array renders pdf correctly on line --> byte[] pdfarray = pdfconverter.converttodoc(bytes); see pdf file saved in --> file somefile = new file("c:\\log\\java2.pdf"); it's not outputting on servletresponse, mixed characters show up. appreciated. please inside dofilter method. have pdfconverter take whole site byte array , convert pdf. import java.io.bytearrayoutputstream; import java.io.ioexception; import java.io.printwriter; import javax.servlet.filter; import javax.servlet.filterchain; import javax.servlet.filterconfig; import javax.servlet.servletexception; import javax.servlet.servletoutputstream; import javax.servlet.servletrequest; import javax.servlet.servletresponse; import javax.servlet.writelistener; import javax.servlet.http.httpservletresponse; import javax.servlet.http.httpservletresponsewrapper; import org.slf4j.logger; import org.slf4j.loggerfactory;

java - Iterating over a json array of arrays -

i have json array comes this [{"item":"value"},{"item":"value"},{"item":"value"},{"item":"value"}] i attempting loop on array , grab "item" code such below, value never grabbed, can confirm array have values somehow returns null arraylist<arraylist<object>> mainlist = new arraylist<arraylist<object>>(); string json = getjson(url, null); jsonobject jsonobject = null; try { jsonobject = new jsonobject(json); int counter = 0; jsonarray itemarray = new jsonarray(); itemarray.put(jsonobject); while(counter < itemarray.length()){ //create inner array arraylist<object> innerlist = new arraylist<object>(); //grab contents of post jsonobject item = itemarray.getjsonobject(counter); //place items inner array innerlist.add(co

java - Zigzag conversion -

question : string "paypalishiring" written in zigzag pattern on given number of rows this: (you may want display pattern in fixed font better legibility) p h n p l s i g y r and read line line: "pahnaplsiigyir" i have written below code, appearantly works fine, might miss corner cases. me find corner cases question on answer? public static string zigzagconversion(string s , int rownum){ if (s == null){ throw new illegalargumentexception(); } if (rownum == 1){ return s; } stringbuilder str = new stringbuilder(); int step = 2 * rownum - 2 ; (int = 0 ; < rownum ; i++){ if( == 0 || == rownum -1){ (int j = ; j < s.length() ; j +=step){ str.append(s.charat(j)); } } else{ int step2 = 2* (rownum - - 1); int step3 = step - step2; int k = i; boolean fla

javascript - Display multiple markers, variable and array problems -

i try display multiple markers on map. put multiples location in adata-attribute trough php file. try grab information in javascript one. if directly paste coordinates, markers appear. if reference data-attribute don't. (the difference on line beginning var locations .) this code works: function googlemapsinit(){ settimeout(function initialize() { var emplacements = $('#iframecarte').attr("data-emplacements"); // emplacements returns [[45.5314817,-73.1835154], [45.570004,-73.448701] ] var mapoptions = { zoom: 12, center: new google.maps.latlng(45.5580421, -73.7303025) }; var map = new google.maps.map(document.getelementbyid('map-canvas'), mapoptions); var locations = [[45.5314817,-73.1835154], [45.570004,-73.448701] ]; var marker, i; var markers = new array(); (i = 0; < locations.length; i++) { marker = new google.maps.marker({ position: new google.maps.latlng(locations[i][

html - Font appears thinner in Firefox and Safari - fine in Chrome -

i'm trying font reasonably same across mac chrome, safari , firefox (will move on ie later). i've been playing with: -webkit-font-smoothing: subpixel-antialiased; the font looks same, safari , firefox looks @ least 1 weight thinner. i have tried: -webkit-font-smoothing: antialiased; and ff: -moz-osx-font-smoothing: grayscale also have on: text-rendering: optimizelegibility !important; this gets fonts pretty same it's not smooth subpixel antialiased. am missing property here? know not going 100% same across browsers think chrome , safari being both webkit browsers same. i'm using raleway google fonts if that's help. maybe font-weight light or lighter in code try changing font-weight normal font-weight:normal; or font-weight:400;

python - concatenate elements of list with PIPE Delimiter -

i require on below code. code following. execute sql query , output of sql query mix of strings,int , date. ie 10001,new york,corp,1,20151001 10002,new york,corp,1,20151001 etc. the expectation want concatenate each record of sql output , write file. 10001|new york|corp|1|20151001\n 10002|new york|corp|1|20151001\n below code. import cx_oracle import os result = cur.execute(qry) # -> execute sql query. le.extend(result) # output of le , le -> type list le = [(10001,u'new york','corp',1,20151001),(10002,u'new york','corp',1,20151001)] final_data = [] final_data.extend('|'.join(w) w in le) getting error above statement. typeerror: sequence item 1: expected string or unicode, int found i tried this final_data.extend('|'.join(str(w)) w in le) but not getting desired output, 10001|new york|corp|1|20151001\n highly appreciate if on this. thanks, bala final_data = ["|".join(map(unico

jquery - Weird output with packery used to randomly position div -

i'm having trouble inserting div (ad banner) randomly within bunch of other divs. i found working example i'm using question: insert div in random location in list of divs however, template being inserted within 1 of items/children, rather it's outer container/target. here's html: <div class="template" style="display: none;"> <a class="item advertisement"> <div class="item-inner-wrapper"> <img alt="image" src="http://placehold.it/525x765"> </div> </a> </div> <div class="listings"> <a class="item card" href="#"> <div class="item-inner-wrapper"> <img alt="" src="http://placehold.it/525x765"> </div> </a> <a class="item card" href="#"> <div class="i

list - Finding a substring within a string using an array? -

trying head around programming, cannot work out why doesn't work? using "not" , "in" incorrectly? i trying program print characters appear in both strings. correctly identifies them, can't print 1 set of characters if there more 1 occurrence. a = input("string1 :") b = input("string2: ") list1 = [] in a: j in b: if == j , not in list1: list1.append([i]) break print(list1) for example if print strings "alexander" , "alex" print characters a, l, e, x, a, e i know current method works if string1 inputted main string, interested why doesn't work. the problem instead of adding common letter list1, adding new list containing common letter list1. @ end have list of lists. @ same time checking if single letter in list of lists, false. you should add common letter "i" list using append: a = input("string1 :") b = input("string2: ")

linux - How to close or reset a pconnect() connection when using PHPRedis and PHP-FPM? -

using phpredis , apache php-fpm i'm using pconnect() call re-use connections - been helpful in past not let number of connections creep high. in case our primary redis node goes down - automatically promote slave master , old master becomes read-only. pconnect() still holding connection old maste - set() commands begin fail. what need way tear down persistent connections without killing process. ideas? persistent streams provided php internals, unwritten law exposes way create persistent stream should provide way destroy it. php redis breaks law, there no way destroy persistent stream userland. the course of action should pr implementation of required method. here's patch against php7 branch implements redis::pclose: https://gist.github.com/krakjoe/326eadc61bea38fdd6e6 note that, code pdisconnect based off of existing disconnect, both of these functions strange me , aren't honest return value. assume there tests or code somewhere relying on strangenes

php - How to get the Variation ID in a Woocommerce product -

i'm trying in plugin i'm writing variation id of products. here's wrote: class mass { public function __construct() { add_action('woocommerce_product_after_variable_attributes',array($this,'thfo_mass')); } public function thfo_mass() { $id = wc_product_variation::get_variation_id(); //$lenght = get_post_meta($id,'_length'); //$dimensions = wc_get_dimension(24750, 'cm'); var_dump($id); } i error: deprecated: non-static method wc_product_variation::get_variation_id() should not called statically, assuming $this incompatible context in path/to/plugins/thfo-raw-material-for-woocommerce/class/mass.php on line 19 notice: undefined property: mass::$variation_id in path/to/wp-content/plugins/woocommerce/includes/class-wc-product-variation.php on line 257 int(0) try this. <?php $product_obj = new wc_product_factory(); $product = $product_obj-&g

How to get text values of rules in MS Outlook using VBA? -

i trying text value(s) of conditions rule have set in ms outlook. i have created rule named "testrule" condition based on text in message body (it must have text "zzz" in it) , condition based on text in message header (it must have text "aaa" in it). (of course, rule never run, test whether can read conditions in rule.) rule , conditions enabled. here code using dim olrules outlook.rules dim olrule outlook.rule set olrules = application.session.defaultstore.getrules set olrule = olrules.item("testrule") debug.print olrule.conditions.body.text debug.print olrule.conditions.messageheader.text however, both debug.print lines give error of "type mismatch". how can read current value of conditions? (i have checked , double-checked: there is rule named "testrule".) gd drc, i've putten more effort problem , think i've figured out why type mismatch. you have added keywords "body"

vba - List excel pivot items of the second row field (multiple row fields) given a particular pivot item in the first row field -

i searched long time this, still inconclusive. have pivot table 2 row labels , 1 data variable looking like: rowlabel1 rowlabel2 sum of value 1 b 2 c 3 d d 4 e e 5 i want able list pivot items of rowlabel2 given particular rowlabel1 , "a"" b" "c" in loop, concat "abc" . whatever try, outputs of pivot items, "abcde" . since real data more complex, not possible manually. have 3 row labels rather 2 labels. don't know if solution can make use of values. example, return rowlabel2 items value <= 3 when " letter " "a" . thanks input!! sub getpiv() dim piv pivottable 'change whatever range , sheet names pivottable set piv = thisworkbook.sheets("secondtable_output").range("a3").pivottable dim r range dim dr pivotitem 'this captures first entry in rowlabe

javascript - Change $scope value when a ng-click function is triggered -

i tried change $scope variable in angular js's ng-click function. angular does not seem able that. below code on appcontroller: // appcontroller.js $scope email = "awesome@example.com"; $scope.emailinfo = "great@example.com"; //emailonclick() ng-click on dom. triggered when user click button, save email information $scope.emailonclick = function() { $scope.email = $scope.emailinfo; console.log($scope.email); //this print "great@example.com". }; console.log($scope.email); // print "awesome@example.com", //want print "great@example.com" triggered ng-click function //apply change. console.log($scope.emailinfo); //this print "great@example.com". what miss? thought? updated: $scope.emailonclick function assign $scope.emailinfo value $scope.email variable. if click in «send server» button you'll see new value has been sent in console. (function() { var app = angula

ios9 - WatchOS 2: ExternalAccessory/ExternalAccessory.h -

does externalaccessory framework exist watchos 2? managed create watchkit project uses , good. however moving os2, cfnetwork , other frameworks missing. can't select when picking frameworks (linked), if link (embedded binary) it, code can not see it. the framework available watch listed here: extensions built watchos 2 have access following system frameworks: clockkit framework contacts framework core data framework core foundation framework core graphics framework core location framework core motion framework eventkit framework foundation framework healthkit framework homekit framework image i/o collection mapkit framework mobile core services framework passkit framework security framework watch connectivity framework watchkit framework reference you can find information avaiable framework on apple site https://developer.apple.com/library/watchos/documentation/general/conceptual/applewatch2transitionguide/leveragesystemtechnologies.html

How to construct intersection in REST Hypermedia API? -

this question language independent. let's not worry frameworks or implementation, let's can implemented , let's @ rest api in abstract way. in other words: i'm building framework right , didn't see solution problem anywhere. question how 1 can construct rest url endpoint intersection of 2 independent rest paths return collections? short example: how intersect /users/1/comments , /companies/6/comments ? constraint all endpoints should return single data model entity or collection of entities. imho reasonable constraint , examples of hypermedia apis this, in draft-kelly-json-hal-07 . if think invalid constraint or know better way please let me know. example so let's have application has 3 data types: products , categories , companies . each company can add products profile page. while adding product must attach category product. example can access kind of data this: get /categories return collection of categories get /categories/9 retur

python 2.7 - Count how many times a word appears in a text file -

def paraula(file,wordtofind): f = open(file,"r") text = f.read() f.close() count = 0 in text: s = i.index(wordtofind) count = count + s return count paraula (file,wordtofind) def paraula(file,wordtofind): f = open(file,"r") text = f.read() f.close() count = 0 index = text.find(wordtofind) # returns index of first instance of word while index != -1: count += 1 text = text[index+len(wordtofind):] # cut text starting after word index = text.find(wordtofind) # search again return count paraula (file,wordtofind)

javascript - Elegant method to compare an array of strings to another array of strings -

question: how can elegantly compare array of strings array of strings returning array of non-matching strings var master = ['1','2','3','4'] var versioned = ['1a','2','3b','4'] var errorlog = [] var count = 0; //this loop doesn't work :( for(var = 0; < versioned.length - 1; ++i ){ for(var j = 0; j < master.length -1; ++j){ if(versioned[i] === master[j]){ console.log('cleared'); } if(count === master.length){ errorlog.push(versioned[i]); } } } loop return ['1a', '3b']; i feel filter() or map() or reduce() i'm unable wrap brain around properly. var master = ['1','2','3','4']; var versioned = ['1a','2','3b','4']; function diff(needle, haystack){ return needle.filter(function(item){ return !~haystack.indexof(item); }); } console.lo

html - floated divs are overlapping and the inner content is wrapping. How can I make more responsive? -

i'm trying following more responsive. seems 2 divs wrapping on each other , buttons flowing w/ content. how go getting 2 divs more responsive? here full page example: http://cssdeck.com/labs/full/eaerpuhb here code: http://cssdeck.com/labs/eaerpuhb <html> <head> <title> test </title> <style> .settings { max-width: 970px; display: block; border: 1px solid #ccc; padding: 3px; background-color: #f3f3f3; text-align: left; } .setting { margin: 5px 0; display: block; text-align: left; } .name { width: 200px; } .save { float: right; text-align: right; } .saveasnew, .cancel { margin-left: 4px; } .toprightlinks { display: block; float: right; } .dashboardsettings { margin-bottom: 20px; text-align: right; } .divsections { width: 400px; margin-top: 5px;

asp.net - Bootstrap horizontal forms don't work on localhost IIS -

this html horizontal form works fine on bootply, not on iis server. edit: instead of horizontal, on every other bootstrap horizontal form example on interweb, label appears left justified edge of page , input directly below it. happens in both chrome , ie11. ideas? <div class="form-horizontal" role="form"> <div class="control-group"> <label class="col-sm-2 control-label" for="txtfindclinician">find clinician</label> <div class="col-sm-10"> <input id="txtfindclinician" class="form-control" type="text" placeholder="enter name" name="search" /> </div> </div> </div> i'm assuming you're trying fetch relevant css, yes? can confirm (perhaps via chrome developer) they're coming through?

angularjs - My ng-repeat does not work -

i have little problem when generated ng-repeat, there nothing going on in html. does me settle problem? var myapp = angular.module('myapp', []) .controller('myctrl', function($scope){ list = []; $scope.generatealbum= function() { return { name : faker.name.firstname() }; }; $scope.generate= function(count) { count = count || 25; list; (var = 0; < count; i++) { list.push($scope.generatealbum()); } return list; }; $scope.generate(); }); and here html : <!doctype html> <html ng-app="myapp"> <head> <title></title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script> <script src="http://marak.com/faker.js/js/faker.js"></script> <script src="js/app.js" type="text/javascript"></scrip

perl - Filtering According To Second Element in a "Tuple" -

i trying zip list sum of each tuple within list, , filter tuples sum higher 0 in list. @ point, using test code given below, nothing prints after line "---- print random tuples above 0". missing? sub filter_random_4_toops_by_sum { ($toops, $thresh) = @_; @toops1 = (); @toops1 = $toops; @sorted_toops = (); @sortedreturn = (); @filtered_toops = (); @sorted_toops = map{[$_, sum(@$_)]} @toops1; @filtered_toops = grep {$_[1]> $thresh} @sorted_toops; @sortedreturn = map{$_->[0]} @filtered_toops; return \@sortedreturn; } the test code: sub test_step_4 { my($sn)= 1; $toops = gen_random_4_toops(1, 100, 5); print "---- random 4-toops:\n"; foreach(@{$toops}) { print "toop $sn:\t(@{$_});\n , sum = " . sum(@{$_}) . "\n"; $sn++; } $thresh = 55; print "\n---- random 4-toops filtered sum above $thresh:\n"; $filtered_toops = filter_random_4_toops_by_sum($toops, $thresh); $sn = 1; foreach(@{$filtered_toops}) { print &q

What is the best way to do C-struct in haskell? -

this question has answer here: avoiding namespace pollution in haskell 4 answers currently use data fields mimic c-struct. found unlike domain-driven way of programming object.property , in haskell property names dumped module namespace. creates problems when have more 1 such struct. example, if have 2 data types: data person = person { name :: text, address :: text } data dog = dog { name :: text, breed :: text } then ghc complain: multiple declarations of ‘name’ . have name "properties" prefixes: data person = person { getpersonname :: text, getpersonaddress :: text } data dog = dog { getdogname :: text, getdogbreed :: text } is necessary? or using wrong way define struct? you can use -xdisambiguaterecordfields extension. allows this: using same name of record label in multiple data declaration. however, should think whether needed.

lotus notes - LotusScript agent for WIA causes error when run on Domino server -

i have lotusscript agent runs after new mail arrives. agent returns: err 208 cannot create automation object when enabled on server, runs fine when changed run menu on selected docs using notes client. dim oimage variant dim oprocess variant dim lngh long, lngw long 'build object -- works notes client not server agent... set oimage = createobject("wia.imagefile") 'load oimage.loadfile sfilename lngh = oimage.height lngw = oimage.width the error occurs when trying createobject("wia.imagefile") the wiaaut.dll file resides in domino\data directory -- notes\data directory. not sure if or how permissions may need set. the lotusscript agent signed id listed in group in domino directory listed in server doc sign or run unrestricted methods , operations and security agent set allow restricted operations full administrator rights. this signing id working other agents performing restricted operations. i think er

Bootstrap Navbar troubleshooting: unexpected drop down menu behavior -

i'm having few issues here, main issue mobile responsiveness drop down menus. can't figure out i'm doing wrong. here html: <div class="navbar navbar-inverse"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button> </div><!--nav-header--> <div class="collapse navbar-collapse"> <ul class="nav nav-pills"> <li><a href="index.html">home</a></li> <li><a href="about.html">about</a></li> <li class="dropd

opencl - Local Memory Corruption -

i have question local memory usage across work items: i have workgroup 256 work items in it. assign k bytes of local memory per work item. so, create local byte array of size 256 * k, , assign 1 region of size k each work item. in code, each work item accesses own region in array. can guaranteed work items not somehow access work items region? given fact local memory shared across half wavefronts? the reason ask seeing sort of corruption, not sure if code bug, or problem design; i.e. using shared local array, shared among work items. given fact local memory shared across half wavefronts i not sure mean that, opencl spec states local memory shared across work-group . there no such concept "half wavefront" (nor wavefront) far standard concerned. any memory corruption may notice can have been introduced own code: responsibility kernels not exhibit data races.

radius - CoA request fails in FreeRadius -

i'm using freeradius 3.0.8. have following configuration in authenticate section of sites-enabled/default auth-type pap { pap if("%{sql:select radcheck.authstep `radcheck` radcheck.username = '%{user-name}' }" == 2){ update coa { user-name = "%{user-name}" packet-dst-ip-address = "72.23.170.105" } } } in radius debug log can see it's trying send coa request fails following warning. (1) warning: unknown destination 72.23.170.105:3799 coa request however when tried same using radclient worked. echo "user-name=ec-78-5f-df-8a-c8" | radclient 72.23.170.105:3799 coa testing123 only difference i'm sending client secret radclient command. have added configuration clients.conf client 72.23.170.105 { secret = testing123 ipaddr = 72.23.170.105 } i'm sure client configuration correct since auth-request client reach radius. am missing her

java - Runtime Exception in Dynamic Fragments -

i trying create activity load different fragments dynamically. how main activity like import android.os.bundle; import android.app.activity; import android.app.fragment; import android.app.fragmenttransaction; public class user_details extends activity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_fragment_loader); fragment fragment=new mail_fragment(); fragmenttransaction fragmenttransaction = getfragmentmanager().begintransaction(); fragmenttransaction.add(r.id.fragment_place, fragment); fragmenttransaction.commit(); } i getting following error during run time. please check error here the fragment this import android.app.fragment; import android.os.bundle; import android.view.layoutinflater; import android.view.view; import android.view.viewgroup; public class mail_fragment extends fragment { @override

xpath - Query using xquery and SQL on an sql table -

i have sql table 3 columns , 1 of columns xml . of elements in xml duplicates. how query table xml elements occur more once?? any appreciated. thanks. in case of: your table has primary key ( id here in sample) your xml data generated program (so no tab, space, carriage return inserted human) i think, can try use following query find duplicate : select * <table> t1 exists (select 1 <table> t2 t2.id <> t1.id , convert(nvarchar(max),t2.<xmlcol>) = convert(nvarchar(max),t1.<xmlcol>))

bash - Rsync only particular files and directory that contain those files -

supposed have directory structure src/ src/a/ src/a/1.ocf src/a/1.pdf src/a/1.txt src/b/ src/b/2.ocf src/b/2.pdf src/b/2.xls src/c/ src/c/3.doc src/c/3.ocf src/c/3.txt src/d/ then, want synchronize files extension *.txt. so, tried use command like: #rsync -avvh --include="*/" --include="*.txt" --exclude="*" src/ dst/ sending incremental file list ./ a/ a/1.txt b/ c/ c/3.txt d/ unfortunately, command not synchronize *.txt file directory. don't want directory 'b' , 'd' synchronized because not contain file *.txt is there simple way that? the option you're looking -m prune empty directories: rsync -avvhm --include="*/" --include="*.txt" --exclude="*" src/ dst/

c - How to create makefile in cooja? -

i trying make program rssi measurement in cooja. recently, found makefile must running programs, /contiki/examples has many examples different makefile contents. instance, "collect" uses apps in makefile. how understand apps , tools needed work? please explain. i'm afraid generic question answer here. you'll have spend time learn makefiles. google "writing makefiles". might want research, instead of letting others homework , come across https://github.com/contiki-os/contiki/wiki/contiki-build-system . oh, , before rssi-measurements in cooja want research on simulation of rssi-values - cooja in particular, too.

What can be the reason for attribute of domain class not being recognized in grails template? -

i have grails template _questionform.gsp . however, question (which attribute of question domain class) not being recognized in template. can reason? _questionform.gsp <g:form action="addquestions" controller="dashboard" method="post"> <br/> question: <g:textarea name="question" required="required" value="${questioninstance?.question}"/> <br/> //.question not recognized here <!--for options--> <g:each in="${(1..<5)}" var="i"> option ${i} : <g:textfield name="option${i}" required="required" class="options"/> <br/> </g:each> subject: <g:select name="questionsubject" from="${com.dwit.research.begnas.api.subject.list()}" optionvalue="subject" optionkey="id" noselection=

Python Max Recursion Reached with ujson, not cPickle -

when comparing ujson , cpickle serializing objects in python 2.7, why using ujson shown gives error overflowerror: maximum recursion level reached ? import ujson json sys.setrecursionlimit(10000) open(mypath, 'w') fp: json.dump(data, fp) however when using cpickle , same error not occur. import cpickle pickle sys.setrecursionlimit(10000) open(mypath, 'w') fp: pickle.dump(data, fp) why this?

why entity framework code first open close 4 different database connection for a single INSERT? -

i inserting row in table in ef code first scenarios, while m checking log, can see 4 different open/close connection , related activity. i think, it's default behavior of ef. could tell me more regarding this??? var ninja = new ninja { name = "sampsonsan", servedinoniwaban = false, dateofbirth = new datetime(2008, 1, 28), clanid = 1 }; using (var context = new ninjacontext()) { context.database.log = console.writeline; context.ninjas.add(ninja); context.savechanges(); } log 1. opened connection @ 10/3/2015 11:18:45 +05:30 select count(*) information_schema.tables t t.table_schema + '.' + t.table_name in ('dbo.clans','dbo.ninjaequipments','dbo.ninjas') or t.table_name = 'edmmetadata' -- executing @ 10/3/2015 11:18:45 +05:30 -- completed in 12 ms result: 3 closed connection @ 10/3/2015 1

python - use data from two or more columns when using .map to apply a function -

i want calculate difference between 2 dates in format yyyy-mm-dd. when write df["diff"] = df["date1"] - df["date2"] value 75 days can't sort. how can write such map function calc_diff(date1,date2) where def calc_diff(date1,date2): x = float(date2-date1) return x i.e. df["diff"] = df["date1"],df["date2"].map(calc_diff) when write following, get: df["until_payable"] = map(calc_diff, df["ex_div_date"], "date_payable") def calc_diff(d1,d2): y = pd.to_datetime(d1) x = pd.to_datetime(d2) return x-y error: <ipython-input-167-b151c936730f> in calc_diff(d1, d2) 39 y = pd.to_datetime(d1) 40 x = pd.to_datetime(d2) ---> 41 return x-y 42 43 #convert data in columns data types pandas/tslib.pyx in pandas.tslib._timestamp.__sub__ (pandas/tslib.c:17620)() typeerror: descriptor '__sub__' requires 'datetime.datetime' objec

c - How to make a function that iterates an isalpha function work? -

i have program compares each element in string using isalpha . input string , calls function cycle through array , check if characters letters. if yes, prints true , false otherwise. problem can't seem make work right. return false every time. #include <stdio.h> #include <string.h> int isalpha(char string[]); int main() { char str[100]; int bool; printf("enter string check: \n"); fgets(str, 100, stdin); bool = isalpha(str); if(bool != 0) { printf("true\n"); } else if(bool == 0) { printf("false\n"); } return 0; } int isalpha(char string[]) { int i, check, len = strlen(string); for(i = 0; < len; i++) { if(isalpha(string[i])) { check = 1; } else { check = 0; break; } } return check; } if user enters abc , returned string fgets abc\n\0 . in other words,

regex - What is the search flow of pattern match? -

my string is $s = "aaataatagcav"; pattern 1 $s =~m/at?.?a/g; here t? fails search. .? match string second character (a a a) a matches (aa a ) pattern 2 $s =~m/a.?t?a/g .? match second character. t? fails search. results same here doubt $s =~m/a.?t?aa/ from beginning a matches first character string .? matches 1 character match or not match string. match second character pattern 1 , pattern 2. t? match 1 character match or not match string. aa match aa character string. why above pattern won't match aataa or ataa . how search engine works.? why result aaa there's nice easy way see regex doing: use re 'debug'; e.g.: #!/usr/bin/env perl use strict; use warnings; use re 'debug'; $str = 'aaataatagcav'; $str =~m/a.?t?aa/; this print: compiling rex "a.?t?aa" final program: 1: exact <a> (3) 3: curly {0,1} (6) 5: reg_any (0) 6: curly {0,1} (10) 8: e

xcode - Pushing from ViewController to TabBarController takes delay -

in project, have viewcontroller login, when pressed login button show viewcontroller b have 4 buttons. when click button1, have showsegue direct tabbarcontroller , has 2 tabs. same button 2,3,4 have showsegue directs navigationcontroller. hierarchy of tabbarcontroller , navigationcontroller: click button 1 to: tabbarcontroller -> tab1 -> navigationcontroller -> viewcontroller1 tab2 -> navigationcontroller -> viewcontroller2 click button 2,3,4 to: navigationcontroller -> viewcontroller i used storyboard in project running swift 2, xcode 7. when click each buttons, takes 1-2 seconds delays on ipad real device. bad user experience. takes me time search answers sadly didn't found solution, that's why asked here.. thanks in advance. maybe should think using async method load controllers when press buttons. try use dispatch_async(dispatch_get_global_queue(dispatch_queue_priority_default, 0), { //background thread (get values - run requ

mysql - Using iconv to convert mysqldump-ed databases -

trying convert latin1 mysql db utf8, tried following: dump db run iconv -f latin1 -t utf8 on resulting file import fresh db utf8 default encoding this mostly works except... some letters converted wrong (an example: uppercase accented 'u' becomes garbled sequence starting question mark). conversion taking place (od query result shows 2 byte sequence latin1 byte was) , te latin1 version alright. while have far been unsystematic in isolating problem (late night; under deadline; etc.) weirdness of issue kills me: why fail on some letters , not all? client connection? column charset? why not getting diagnostics? i'm stymied. sure, can work on isolating issue , details, thought maybe ran , can recognize (admittedly rather poor) description. cheers the data may have been stored latin1 it's possible ever client used dump data has exported utf-8. open dump file in decent text editor (notepad++, textwrangler, atom) , check encoding allows character

haskell - wxWebView in wxHaskell -

i'm trying show web page inside wxhaskell based application mac. tried use htmlwindow , limited. according wxwidgets' documentation, have use wxwebview, capable process css , js. from http://docs.wxwidgets.org/trunk/classwx_html_window.html if want complete html/css support javascript engine, see instead wxwebview. exactly need! hoverer didn't find mentions of wxwebview in wxhaskell. and, also, miracle, google pretty silent it. makes me think, wrong. there way display reach (having html/css/js) pages using wxhaskell? how people that? i've got wxwidgets 3.0.2 installed brew: brew install wxwidgets and wxhaskell 0.92 cabal cabal install wx cabal install wxcore wxwebview not implemented in wxhaskell (yet); feel free create pull request expand wxhaskell. b.t.w. if ask questions @ wxhaskell-users mailing list , answer sooner.

c# - Change button style in Universal Windows Platform -

Image
i've tried make simple c# uwp application , don't know how remove gray background when mouse on button. how that? (remember: it's uwp windows 10 platform , not windows phone 8.1 or wpf) follow these steps: rightclick in solution explorer , add new item of kind "resourcedictionary" copy default style of button can find on webpage, need scroll down little bit: msdn then insert in resourcedictionary.xaml format should this: <resourcedictionary><style></style></resourcedictionary> 3. give style key this: <style x:key="mycustombutton"></style> 4. go app.xaml edit adding resource dictionary this: <application.resources> <resourcedictionary source="resources.xaml"></resourcedictionary> </application.resources> the source of resourcedictionary name of resourcedictionary file. then add style button this: <button style="{staticresource myc

php - Warning: mysql_fetch_array() expects parameters 1 to be resource, -

this question has answer here: mysqli_fetch_array()/mysqli_fetch_assoc()/mysqli_fetch_row() expects parameter 1 resource or mysqli_result, boolean given 33 answers ** this question has answer here: mysql_fetch_array() expects parameter 1 resource (or mysqli_result), boolean given 31 answers hi im trying write data database , code thats meant doing 2 of 'warning: mysql_fetch_array() expects parameter 1 resource, boolean given' , dont know why???? ** <?php $connection = mysql_connect("localhost", "root", ""); // establishing connection server $db = mysql_select_db("burger machine", $connection); // selecting database //mysql query read data $query = mysql_query("select * add", $connection); while ($row = mysql_fetch_array($query)) { echo "<tr>";

javascript - scrollbar insde one onther scroll bar -

hi all, making slider want thing below image. more in details vise in picture actualy 1 of slider slide got scroll bar .where want when user first scroll page first slider scoller should scroll , slider scroller end ,the page scroller should work normaly. i have no idea how in jquery seen kind of effect in many sites. please me , in advance

php - PDO FETCH_CLASS when fields and columns have different names -

from documentation fetchall , fetch_class : <?php class fruit { public $name; public $colour; } $sth = $dbh->prepare("select name, colour fruit"); $sth->execute(); $result = $sth->fetchall(pdo::fetch_class, "fruit"); var_dump($result); ?> it happens columns names different fields defined in classes. i'm wondering if there clean way fields of class populated when query fetches different columns names : $sth = $dbh->prepare("select f_name, f_colour fruit"); is there generic solution map columns name fiels ? tried several combinations fetch_mode, hoping 1 of them pass results constructor, none of them worked. it happens columns names different fields defined in classes. it shouldn't happen in first place. purpose of fetch mode make properties assignment simple, when column names considered match class properties. so, programmers make use same naming way through - sql table column names, html fo

java - Projectile damage not being cancelled -

Image
i'm trying cancel damage of arrow if player's name in list nopvp . @eventhandler public void playerdamageswhentoggledoff(entitydamagebyentityevent e) { player victim = (player) e.getentity(); player damager = (player) e.getdamager(); if (getter.nopvp.contains(victim.getname()) || getter.nopvp.contains(damager.getname())) { e.setcancelled(true); } else if (e.getcause() == damagecause.projectile && getter.nopvp.contains(victim.getname()) || getter.nopvp.contains(damager.getname())) { e.setcancelled(true); } } this doesn't seem work, when if statement fine. the reason why player takes projectile damage despite being in nopvp list way cast entities. note both e.getentity() , e.getdamager() return entity object , not player object. casting these variables you're telling plugin instances of player class without knowing kind of entity are, false because damager , damaged entity can other types of