Posts

Showing posts from April, 2015

ios - Autolayout UIView Proportional height with Minimum height requirement -

Image
i've created 1 tab bar bottom view proportional height related main superview. whereas, tab bar bottom view height in 6+ -> 59, in 6 -> 53, in 5 -> 45 & in 4s -> 38. it's working proportionally fine. if want tab bar view's height should minimum 46, @ maximum should work proportionally. so based on above heights on different devices, want achieve 6+ -> 59, 6 -> 53, 5 -> 46 & in 4s -> 46. so possible solution in auto layout achieve this. in advance. you should add height constraint more 46 , priority 1000.and set priority of top space constraint 750.

perl - Search a list file of files for keywords -

i have array of files. need cat each file , search list of keywords in file keywords.txt . my keywords.txt contains below aes 3des md5 des sha-1 sha-256 sha-512 10.* http:// www. @john.com john.com and i'm expecting output below file jack.txt contains aes:5 (5 line number) http://:55 file new.txt contains 3des:75 http://:105 okay here code use warnings; use strict; open stdout, '>>', "my_stdout_file.txt"; $filename = $argv[2]; chomp ($filename); open $fh, q[<], shift or die $!; %keyword = map { chomp; $_ => 1 } <$fh>; print "$fh\n"; while ( <> ) { chomp; @words = split; ( $i = 0; $i <= $#words; $i++ ) { if ( $keyword{ $words[ $i ] } ) { print "keyword found file:$filename\n"; printf qq[$filename line: %4d\tword position: %4d\tkeyword: %s\n], $., $i, $words[ $i ]; } } } but problem

python - FeatureUnion in scikit klearn and incompatible row dimension -

i have started use scikit learn text extraction. when use standard function countvectorizer , tfidftransformer in pipeline , when try combine new features ( concatention of matrix) have got row dimension problem. this pipeline: pipeline = pipeline([('feats', featureunion([ ('ngram_tfidf', pipeline([('vect', countvectorizer()),'tfidf', tfidftransformer())])), ('addned', addned()),])), ('clf', sgdclassifier()),]) this class addned add 30 news features on each documents (sample). class addned(baseestimator, transformermixin): def __init__(self): pass def transform (self, x, **transform_params): do_something x_new_feat = np.array(list_feat) print(type(x)) x_np = np.array(x) print(x_np.shape, x_new_feat.shape) return np.concatenate((x_np, x_new_feat), axis = 1) def fit(self, x, y=none): return self and first part of main programm data = load_files('ho_without_tag') grid_search = gridsea

rethinkdb all records are deleted instead of only records matching index -

i have table notifications . records inserted so: socket.on('set notif',function(data){ var user = socket.client.user; if(typeof user !== 'object' && user == '_srv'){ r.table('notifications').insert(data).run().then(function(res){ r.table('notifications').get(res.generated_keys[0]).run().then(function(data){ var user = data.user_id; io.sockets.in(user).emit('new notif',data); }); }); } }); when meeting declined user, must delete associated meeting notifications , send notification null meeting_id user notifying them other party has declined offer. socket.on('del meeting notifs',function(data){ var user = socket.client.user; if(typeof user !== 'object' && user == '_srv'){ r.table('notifications').getall(data.id,{index:'meeting_id'}).delete().run().then(function(){ }

reactjs - Prevent User From Triggering Multiple Scrolling -

i have homepagecontainers holds data ajax requests , pass down homepage component. homepage component composed via higher order function infinitescroll supports scrolling. the infinitescroll looks this: componentdidmount() { window.addeventlistener('scroll', this.onscroll.bind(this), false); } componentwillunmount() { window.removeeventlistener('scroll', this.onscroll.bind(this), false); } onscroll() { if ((window.innerheight + window.scrolly) >= (document.body.offsetheight - 200)) { const { scrollfunc } = this.props; scrollfunc(); } } i want code prevent scrolling once fired 1 , wait till data arrives request. like: ((window.innerheight + window.scrolly) >= (document.body.offsetheight - 200)) + //a new condition make sure scroll happens when data arrives or fails. note scrollfunc received homepagecontainers going update state according ajax request/responses. i can store scrolling state in homepagecontain

java - Suppress Jboss version details from HTTP error response -

my jboss verson jboss eap 6.3 when kind of error response sent jboss, adds server information response. following sample row response: http/1.1 400 bad request server: apache-coyote/1.1 content-type: text/html;charset=utf-8 content-length: 2391 date: tue, 19 jul 2016 09:30:46 gmt connection: close jboss web/7.4.8.final-redhat-4 - jbweb000064: error report jbweb000065: http status 400 - org.codehaus.jackson.map.jsonmappingexception: can not construct instance of mybean.type string value 'xyz': value not 1 of declared enum instance names @ [source: org.jboss.resteasy.core.interception.messagebodyreadercontextimpl$inputstreamwrapper@5e421c2b; line: 14, column: 26] (through reference chain: requestargs["request"]) jbweb000309: type jbweb000067: status report jbweb000068: message org.codehaus.jackson.map.jsonmappingexception: can not construct instance of mybean.type string value 'xyz': value not 1 of declared enum instance names @ [source: org.jboss

java - Correct way to add custom exception to Lexer/Parser files in antlr4 -

i have custom parsingexception(string message, int location, string offendingtext) i want parser throw exception when parsing / lexing error encountered. is correct ? @parser::members { @override public void notifyerrorlisteners(token offendingtoken, string msg, recognitionexception ex) { throw new parsingexception(msg,offendingtoken.getstartindex(),offendingtoken.gettext()); } } @lexer::members { @override public void recover(recognitionexception ex) { throw new parsingexception(ex.getmessage(),getcharpositioninline(),ex.getoffendingtoken().gettext()); } } i unhandledexception error this. you should override syntaxerror method of baseerrorlistener instead of notifyerrorlisteners , recover decribed here: handling errors in antlr4 .

Handle Twitter / Facebook Authentication in App -

i want users of app able authenticate twitter , facebook. way know real user. once they've authenticated once don't want have worry them logging out or re-authenticating unless explicitly so. i'm storing/displaying users avatar image. how might handle if user update on given platform? stored image url out of date correct? user have logoff , re-authenticate in order have data updated isn't ideal...

c++ - Determining the Parameter Types of an Undefined Function -

i've learned cannot: take address of undefined function take address of templatized function type fail compile for but i've learned can call decltype return type of said function so undefined function: int foo(char, short); i'd know if there's way can match parameter types types in tuple . meta programming question. i'm shooting decltypeargs in example: enable_if_t<is_same_v<tuple<char, short>, decltypeargs<foo>>, int> bar; can me understand how decltypeargs crafted? for non-overloaded functions, pointers functions, , pointers member functions, doing decltype(function) gives type of function in unevaluated context, , type contains arguments. so the argument types tuple, need lot of specializations: // primary function objects template <class t> struct function_args : function_args<decltype(&t::operator()> { }; // normal function template <class r, class... args> struct function_arg

checkout - how to set next payment date in Bluesnap -

i have create custom subscription plan, made transaction, transaction done next payment date set after month need set after year. i have tried code not works. <form method="post" action="https://www.bluesnap.com/jsp/buynow.jsp?"> <input type="hidden" name="contractid" value="xxxxxx"> <input type="hidden" name="currency" value="usd"> <input type="hidden" name="firstname" value="abc"> <input type="hidden" name="lastname" value=" na"> <input type="hidden" name="email" value="test@mailinator.com"> <input type="hidden" name="overrideprice" value="19.95"> <input type="hidden" name="overridename" value="my test product - invoice #1234"> <input type="hidden" name=&quo

postgreSQL sorting with timestamps -

Image
i have following sql statement: select * schema."table" "timestamp"::timestamp >= '2016-03-09 03:00:05' order "timestamp"::date asc limit 15 what expect do? giving out 15 rows of table, timestamp same , bigger date, in ascending order. postgres sends rows in wrong order. first item on last position. has idea why result strange? use order "timestamp" (without casting date).

How to increase the precision of float values to more than 10 in python? -

this question has answer here: python floating point arbitrary precision available? 4 answers daily_raw_consumption = float(daily_rate) * float(rep_factor) float(daily_raw_consumption) by default rep_factor getting converted precision of 10 values. ex: actual: 60.8333333333 what need : 60.833333333333333333 is possible modify precision without converting decimal consider using decimal instead of float from decimal import * daily_raw_consumption = decimal(daily_rate) / decimal(rep_factor) print(decimal(daily_raw_consumption))

linux - Can not connect to BLE device from Android 4.4.2 -

Image
i developing system there 2 application: first application on android, second application run on linux. must communicate via ble protocol on linux, have modified code of bluez 4.1(btgattserver.c). application on linux broadcast ble advertiser package, , wait connect android. on android, using api connect linux application: public bluetoothgatt connectgatt (context context, boolean autoconnect, bluetoothgattcallback callback) my problem is: on android 5, these applications can communicate normally. on android 4.4.2, android application can not connect linux application i have turned on option "enable bluetooth hci snoop" on android , got log file of hci on android 5. , android 4.4.2 compare. i found on android 5., request connect has psm sdp, request connect on android 4.4.2 has psm att. , connection on android 4.4.2 rejected linux application (please see attached image) please tell why android 4.4.2 create connect request psm att? , how resolve problem? bec

java - assign value to int[] array in do-while loop -

coming ruby/rails have lots of difficulties adopting java logic. question - how assign values (read stdin) arrays of integers in do-while loop use arrays later in later methods? here code snippet: void triangleperimeter() { //int[][] arrs; //int[] edge1, edge2, edge3 = new int[]; { system.out.print("x, y edge 1: "); int[] edge1 = {ch3ex.stdin.nextint(),ch3ex.stdin.nextint()}; system.out.print("x, y edge 2: "); int[] edge2 = {ch3ex.stdin.nextint(),ch3ex.stdin.nextint()}; system.out.print("x, y edge 3: "); int[] edge3 = {ch3ex.stdin.nextint(),ch3ex.stdin.nextint()}; int[][] arrs = {edge1,edge2,edge3}; if (!(trianglehelpers.inputvaliditychecker(arrs))) system.out.println("wrong input. retype."); } while(!(trianglehelpers.inputvaliditychecker(arrs))); triangle triangle = new triangle();

javascript - How to pass string variables to labels option in Morris.js -

i using morris.js rendering charts in rails project. there problem have no idea how pass values json string labels option in morris.js. below contents helper method: def worst_yield_chart_data(reports) start_time = reports.last.published_at end_time = reports.first.published_at datetime = report.where("config = ? , published_at between ? , ?", 'all', start_time, end_time).select("distinct(published_at)") datetime.map |date| { published_at: date.published_at.to_datetime.to_formatted_s(:long), # top1 worst yield rate & station name worst_accu_yield: report.group_accu_yield_by_date(date.published_at).first.try(:worst_accu_yield), worst_daily_yield: report.group_daily_yield_by_date(date.published_at).first.try(:worst_daily_yield), worst_accu_yield_station: report.group_accu_yield_by_date(date.published_at).first.try(:station_name) || 'no input', worst_daily_yield_station: report.group_daily_yiel

java - When should I return the Interface and when the concrete class? -

when programming in java practically always, out of habit, write this: public list<string> foo() { return new arraylist<string>(); } most of time without thinking it. now, question is: should always specify interface return type? or advisable use actual implementation of interface, , if so, under circumstances? it obvious using interface has lot of advantages (that's why it's there). in cases doesn't matter concrete implementation used library function. maybe there cases matter. instance, if know access data in list randomly, linkedlist bad. if library function returns interface, don't know. on safe side might need copy list explicitly on arraylist : list bar = foo(); list mylist = bar instanceof linkedlist ? new arraylist(bar) : bar; but seems horrible , coworkers lynch me in cafeteria. , rightfully so. what guys think? guidelines, when tend towards abstract solution, , when reveal details of implementation potential performance gains?

java - "...cannot be resolved to a variable." Why not? -

public int getentityindex(string name){ for(int = 0; < entities.length; i++){ if(entities[i].getname().touppercase().equals(name.touppercase())){ break; } } return i; } this code produces error: i cannot resolved variable. i'm guessing variables declared inside loop declaration outside scope of remainder of method, unable find information regarding problem specifically. after analyzing code while, starting see using bad idea (what if entities[i] never equals name ? method return entities.length - 1 , if match not found. think i'll use while(!found) approach instead. to clarify, i'm not asking how fix issue. i'm asking why error occurring. thanks! you cannot see i outside for loop. try this: public int getentityindex(string name) { for(int = 0; < entities.length; i++){ if(entities[i].getname().touppercase().equals(name.touppercase())){ return i; } } ret

r - substract subset of data frame from the same data frame -

i have data frame of following structure: have ana number of rows , columns v<-c("control", na, 1, 2, 4, "test", na, 1, 2, 4, "test", na, 1, 2, 4, "test", na, 1, 2, 4) df<- as.data.frame(t(matrix(v, nrow=5, ncol=4))) colnames(df)<-c("id", "g1", "g2", "g3", "g4") df id g1 g2 g3 g4 1 control <na> 1 2 4 2 test <na> 1 2 4 3 test <na> 1 2 4 4 test <na> 1 2 4 i subtract rows id==control other rows, giving me following result: result id g1 g2 g3 g4 1 test <na> 0 0 0 2 test <na> 0 0 0 3 test <na> 0 0 0 i tried sweep() function, tried putting through loops, nothing worked. it amazing if me. thank you! assuming there single "control", create logical index based on 'control' value ('i1'), subset 'df' 'id' not 'control&

javascript - Can't get property of objects I've created. Looks like problems with mongoose for MongoBD -

Image
upd. problem solved 1 line of code: .lean() axplanation here i have array of menu items after model.find(...blablabla : [ {"_id":"578763de6e8e0542195ef4e8", "text":"lists", "iconcls":"fa fa-group fa-lg", "classname":null, "menu_id":null}, {"_id":"578762146e8e0542195ef4e7", "iconcls":"fa fa-group fa-lg", "classname":"panel", "menu_id":"578763de6e8e0542195ef4e8", "text":"personal"}, {"_id":"578770aca59f4d173c948376", "text":"info", "iconcls":"xf007", "classname":null, "menu_id":null}, {"_id":"5787715aa59f4d173c94837c", "text":"cars", "classname":"panel", "menu_id":"578763de6e8e0542195ef4e8", "iconcls":"xf007&q

java - Why isn't my code working beyond printing the math.random? -

this question has answer here: how compare strings in java? 23 answers i'm new programmer , trying teach myself java doing random projects. below "rock, paper, scissors" game , issue i'm facing after printing "a", program ends , not continue onto if else statements below. can given appreciated. package com.company; import java.util.scanner; public class main { public static void main(string[] args) { system.out.println("hello & welcome rock, paper, scissors. what's name?"); scanner scan = new scanner(system.in); string userchoice = scan.nextline(); system.out.println("hello, " + userchoice + ". let's start game!"); scanner scan = new scanner(system.in); system.out.println("choose one: rock, paper, scissors"); string userfir

css - outline: none VS outline: 0 -

Image
i reading this question on disabling dashed borders around <a> links. some answers used outline: none , while some used outline: 0 is there difference between using outline: none , outline: 0 ? according mdn : the css outline property shorthand property setting 1 or more of individual outline properties outline-style , outline-width , outline-color in single declaration so when set outline none or 0 , telling browser set 3 properties ( outline-style , outline-width , outline-color ) i used firefox developer tools find out difference: as can see, both use default text color outline-color , , both have outline-style set none . difference outline-width : when outline 0 , outline-width 0px when outline none , outline-width medium that difference between two. can use either one, both display same way (since outline-style none , not matter how wide outline is).

c - Getting timestamp with date and time including microseconds -

for error-logbook want create timestamp date , time, including microseconds. should have form 2016.07.19 13:59:31:123.456 i found lot of examples of time_t , resolution seconds... you can use gettimeofday : #include <time.h> #include <sys/time.h> .... struct timeval tv; gettimeofday(&tv, null); where struct timeval defined as: struct timeval { time_t tv_sec; /* seconds */ suseconds_t tv_usec; /* microseconds */ }; you can use gmtime split seconds part: struct tm *ts = gmtime(&tv.tv_sec); where struct tm defined as: struct tm { int tm_sec; /* seconds */ int tm_min; /* minutes */ int tm_hour; /* hours */ int tm_mday; /* day of month */ int tm_mon; /* month */ int tm_year; /* year */ int tm_wday; /* day of week */ int tm_yday; /* day in ye

sql - Update a table using another table in SAS -

i have table t1 , t2, how can create table t3? want update var2 in t1 t1.key=t2.key, using data t2 while keeping else in t1 same. table t1 key var1 var2 1 aa 2 b bb 3 c cc 4 d dd 5 e ee table t2 key var1 var2 3 c xx 4 d yy 6 f ff table t3 key var1 var2 1 aa 2 b bb 3 c xx 4 d yy 5 e ee the following sas code give me errors: proc sql; update t1 set var2 = t2.var2 t1 inner join t2 on t1.key=t2.key; quit; thanks! you can use update statement in data step. update statements similar merge statements, except not replace populated values missing values unless specify. in addition, non-unique keys generate warning, helpful debugging. the general syntax updating tables , creating new 1 simultaneously: syntax data newtable; update mastertable transactiontable; key(s); run; in order update operation data, need make sure 2 datasets either sorted or indexed

c++ - What kind of declarator is this? -

so looking in c++ grammar syntax thing, came across grammar rule : declarator: direct-declarator ptr-operator declarator direct-declarator: declarator-id declarator-id: id-expression ::opt nested-name-specifier(opt) type-name <------- oo type-name: class-name enum-name typedef-name which made me wonder kind of declarator has typename in it? example help. thanks in form exists on older versions of c++ standard. guess there constructor definitions void someclass::someclass() {} i'd guess following wording a class-name has special meaning in declaration of class of name , when qualified name using scope resolution operator :: (5.1, 12.1, 12.4). is intended accompany specific part of grammar.

Getting "raise WebDriverException" running Selenium Python for Firefox on Windows 7 -

i continuously getting python errors while trying execute following simple selenium python code firefox on windows 7 system. from selenium import webdriver selenium.webdriver.common.keys import keys driver = webdriver.firefox() driver.get("http://www.python.org") i couldn't find previous questions related windows , i'm trying see if can me solve issue. i've uninstalled python 3.4 , installed latest python 3.5 no avail. here's error message in entirety: =============== restart: c:\pythonscripts\selenium\firefox.py =============== traceback (most recent call last): file "c:\pythonscripts\selenium\firefox.py", line 4, in driver = webdriver.firefox() file "c:\python35\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 78, in init self.binary, timeout) file "c:\python35\lib\site-packages\selenium\webdriver\firefox\extension_connection.py", line 51, in init self.binary.launc

php - Create a folder if it doesn't already exist -

i've run few cases wordpress installs bluehost i've encountered errors wordpress theme because uploads folder wp-content/uploads not present. apparently bluehost cpanel wp installer not create folder, though hostgator does. so need add code theme checks folder , creates otherwise. try this: if (!file_exists('path/to/directory')) { mkdir('path/to/directory', 0777, true); } note 0777 default mode directories , may still modified current umask.

c# - How to set my NumericUpDown on Database -

for example, item_quantity on table 50, numericupdown's minimum 1 , 50? im using c# , mysql , cant make work. edit: this code: string myconnectionstring = "server=localhost;port=3307;database=invpos;uid=root;pwd=''"; public void loadgrid() { mysqlconnection connection = new mysqlconnection(myconnectionstring); connection.open(); try { mysqlcommand cmd = connection.createcommand(); cmd.commandtext = "select * items"; mysqldataadapter adap = new mysqldataadapter(cmd); dataset ds = new dataset(); adap.fill(ds); } catch (exception) { throw; } { if (connection.state == connectionstate.open) { connection.clone(); } } } public void combobox() { mysqlconnection connection = new mysqlconnection(myconnectionstring);

node.js - nodejs upload file HTTP POST -

i want "client.js" read file, , upload folder via "server.js" using http post. when file size small(1kb), works. when file size bigger(maybe around 100kb), doesen't work. there no error, stored image less in size it's supposed be. don't know why. please help. 1.client.js var fs = require('fs'); var http = require('http'); postdata = null; postdata=fs.readfilesync("test.jpg") if(postdata!=null){ var options = { host: 'localhost', port: 10730, method: 'post' }; var clientrequest = http.request(options); clientrequest.end(postdata);} 2.server.js var http = require('http'); var fs = require('fs'); var server = http.createserver((req,res)=>{ req.on('data', (chunk)=>{ fs.writefile('testcopy.jpg',chunk)}) req.on('end', ()=>{ console.log("end") })}) server.listen(10730,'localhost'); thank in advance.

c++ - C# code to open regular HP QT457AA cashdrawer -

i got hp qt457aa cashdrawer connected rj-12 cable hp rp7800 (which has rj-12 slot). i have searched along time couldnt find helpful how open it( directly - without receipt printer) i downloaded pos sdk in thread: open cash drawer problem there examples how cashdrawer connected through com port, mine connected rj-12 , thats why im struggling but im rather clueless visual studio 2015. know i'm asking alot , thankful help. edit: forgot mention tested if opens automatically using test apps opos , microsoft pos sdk , worked after claiming , "opening" it download correct hp drivers computer's cash drawer port if opos drivers installed, can download hp opos logical name utility link above. can give whatever name want device can access calling name. don't need deal ports. search samples opos cash drawer control or use sample in microsoft point of service sdk. microsoft point of service .net v1.14 (pos .net)

qt - Simple ribbon: autosizing toolbars and tabs -

Image
i'm trying implement simple tabbed interface qt5. use qtabwidget qtoolbars placed inside tabs , add qactions qtoolbars: the toolbar , widget below within vertical layout. i'd toolbars autosize height enough high hold qtoolbuttons inside (the last ones can display icon, text or both of them (text under icon or on right side of it), affects height) , autosize width display many toolbuttons, fits parent tab width. i'd parent tabs automaticaly stretch or shrink height able display toolbars within. possible in qt? if yes, how? update1: horizontal autostretching has been done using toolbars tab widgets of qtabwidget. vertical 1 still missing. significant code (for qdesigner): <widget class="qwidget" name="central_widget"> <layout class="qvboxlayout" name="verticallayout"> <item> <widget class="qtabwidget" name="tabbed_tool_bar"> <property name="sizepolicy">

javascript - React Redux - call dispatch without connect (not from a react component) -

i have scheduled function fetches data server every x minutes , want update state response: api.fetchdata().then( (response) => { dispatch(actions.updateconfiguration(response)); } }; this function should not react component since doesn't render anything. however can't seem figure out how inject dispatch function without using connect , requires react component. thanks. we've similar thing (a recurring check on wether auth token still valid) , did following. in our little "util" function receive redux store parameter export function startsessiontimer(store) { const intervalid = setinterval(() => { if ( ... ) { store.dispatch( ... ); clearinterval(intervalid); } }, (15 * 60 * 1000)); } then, set our app , create store, kick-start timer. const store = configurestore( ... ); startsessiontimer(store);

javascript - jQuery stopPropagation not working on table/mobile -

i have submit form login looks this: handleloginsubmit: function() { $('#login-form, .login-form').submit(function (e) { e.stoppropagation(); var $form = $(this); $.ajax({ url: 'loginurl', type: 'post', data: $(this).serialize(), success: function (r) { if (r.redirect) { window.location = r.redirect; } else { //wrong username or password } } }); }); }, this works fine on computer, , other computers matter. seems work on android phone. i've tried both on ipad , iphone , neither works. the problem when submit form json data printed out on screen this: {"login":true,"redirect":"https://frontpageurl"} but supposed redirect front page url. so when logging in, on iphone or ipad, redirect front page not work. i first tried e.preventd

java - Convert JsonObject array to integer -

i getting following response server: {"subjectname":["irish","maths","english","science","religion","geography"], "subjectid":[1,2,3,4,5,6]} what need try separate response 2 separate arrays subjectname , subjectid. here have: try { jsonarray = jsonobject.getjsonarray("subjectname"); } catch (jsonexception e) { e.printstacktrace(); } subjectname = new string[jsonarray.length()]; (int = 0; < jsonarray.length(); i++) { try { subjectname[i] = jsonarray.getstring(i); } catch (jsonexception e) { e.printstacktrace(); } } try { jsonarray = jsonobject.getjsonarray("subjectid"); log.v("worked", "subjectid in "); } catch (jsonexception e) { log.v("fai

C++ reinterpret_cast object to string and back -

i discovered reinterpret_cast in c++ , trying learn more it. wrote code: struct human{ string name; char gender; int age; human(string n, char g, int a) : name(n), gender(g), age(a) {} }; int main() { human h("john", 'm', 26); char* s = reinterpret_cast<char*>(&h); human *hh = reinterpret_cast<human*>(s); cout << hh->name << " " << hh->gender << " " << hh->age << endl; } it works pretty well, expected. want convert char * std::string , string human object: int main() { human h("john", 'm', 26); char* s = reinterpret_cast<char*>(&h); string str = s; human *hh = reinterpret_cast<human*>(&str); cout << hh->name << " " << hh->gender << " " << hh->age << endl; // prints wrong values } does have idea overcome ? thank you.

Date +/- Function PHP -

i trying make function checks whether date holiday or not. such as, on 24/02/2016 added 2 days, function set date 28/02/2016. because 26 & 27 february holiday (in bangladesh). have been trying make did not way. can suggest, how task php? i think best way in php handle dates carbon php you that carbon::createfromdate(2016, 2, 24)->adddays(2);

I am using jupyter notebook, ipython 3 on windows. Whenever i am starting my python 3, i get the "Kernel Dead" message -

dead kernel kernel has died, , automatic restart has failed. possible kernel cannot restarted. if not able restart kernel, still able save notebook, running code no longer work until notebook reopened. the above message shown in notebook dashboard after start python3. [i 23:07:08.365 notebookapp] kernelrestarter: restarting kernel (4/5) warning:root:kernel 9938cea3-6528-4a27-b4c3-ee906d748bfb restarted traceback (most recent call last): file "c:\users\dharini\appdata\local\programs\python\python35-32\lib\runpy.py" , line 170, in _run_module_as_main "__main__", mod_spec) file "c:\users\dharini\appdata\local\programs\python\python35-32\lib\runpy.py" , line 85, in _run_code exec(code, run_globals) file "c:\users\dharini\appdata\local\programs\python\python35-32\lib\site-pack ages\ipykernel\__main__.py", line 3, in <module> app.launch_new_instance() file "c:\users\dharini\appdata\local\programs\python\python35-

stop unexpectedly my app when peress botton in emulator/android -

my code compiles , run on emulator when button pressed stops , shows message "the application stopped on unexpectedly" . i've searched lot , read related posts didn't help. me? got following message: "fatal exception:main"message main xml file <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context="com.example.testing.mainactivity" > <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world

Overcoming limitation with polymorphic type in haskell -

i have type so, data agentspec = agentspec { agent :: , events :: [bytestring] } deriving (show) and other types so, data java = java data php = php i trying create function of type, allevents :: [agentspec a] -> [bytestring] allevents aspec = concatmap events aspec but unable create values of type [agentspec a] if do, allevents [agentspec java ["event1, "event2"], agentspec php ["event3, "event4"]] it not typecheck , understandably so. doesn't type check because, agentspec java not agentspec a so understand why not work. not know how overcome limitation without writing lot of duplicate code. one alternatve manually construct list of type, allevents :: [bytestring] allevents = ["event1", "event2", "event3", "event4"]. but feel i'm rewriting things i've modelled in types. there way make use of existing types

linux - How to send data to all Epoll fds? -

i've been trying make server , client chat using epoll week. struggle since i'm newbie @ networking stuff. ended code. (note: connect server telnet now): http://textuploader.com/5e0ts how supposed send data registered fds in epoll instance? trying inside loop in main loop doesn't work. you should ensure of registered fds waiting epollin event. if when send data fds in loop, specific fd can "waked up", , receive data. you should use nonblocking io , because want broadcasting, epoll_wait function blocking function, , epoll model can process event 1 one, unless use thread pool. actually, can finish task using epollout event send data fds 1 one of epoll , instead of inside loop in epoll loop.

delete more than one id from SQL Server -

Image
how delete rows duplicate values " driverid "?. want remove duplicated entries if each record. please see below image, want query how this. use exists() delete yourtable p exists(select 1 yourtable pp p.driverid = pp.driverid , p.id > pp.id)

c# - How to throw exception from a method with generic return type -

while building extension method obtaining value of attributes have following method signature: public static ienumerable<tvalue> getattributevalues<tattribute, tvalue>( type type, string methodname, type[] parametertypes, func<tattribute, tvalue> valueselector, bool inherit = false) tattribute : attribute however, during testing i've found cannot usefully throw exception inside method. if throw instance of argumentexception execution process appears ignore it, i.e. , exception doesn't bubble up. try... catch in calling method catches nothing. if call gettype() on result of method call, type presented fully-qualified name of method. i can't step method while debugging. can explain why i'm unable stop application exception, if method throw exception? because extension method returning ienumerable<t> need call toarray or first on otherwise won't enumerate.

jquery - Javascript str.replace with dollar sign not working -

sample string being replaced: https://fw.adsafeprotected.com/rjss/bs.serving-sys.com/52023/7720220/burstingpipe/adserver.bs?cn=rsb&c=28&pli=1234567890&pluid=0&w=300&h=600&ord=[timestamp]&ucm=true&ncu=$${click_url_enc}$&adsafe_preview=${is_preview}` replacements i'm trying make: $${click_url_enc}$ --> $$${click_url_enc}$$ [timestamp] --> ${cachebuster} desired output: https://fw.adsafeprotected.com/rjss/bs.serving-sys.com/52023/7720220/burstingpipe/adserver.bs?cn=rsb&c=28&pli=1234567890&pluid=0&w=300&h=600&ord=${cachebuster}&ucm=true&ncu=$$${click_url_enc}$$&adsafe_preview=${is_preview} code i've tried: code: var v = $("textarea#creative-content").val(); v = v.replace(/\$\$\{click\_url\_enc\}\$/g, "$$${click_url_enc}$$"); v = v.replace("[timestamp]","${cachebuster}"); console.log(v); output: changed [timestamp] ${cachebuster}

c# - error when setting a value for a property between forms -

i'm getting error: cannot implicitly convert type decimal string when i'm setting value property , i'm not sure how remedy this. there 2 forms. i'm passing information 1 form other display it. error in form price form (calculator): public partial class calculator : form { decimal dorm = 0; decimal meal = 0; public calculator() { initializecomponent(); } public decimal _price { { return _price; } } private void getpricebutton_click(object sender, eventargs e) { decimal price = 0; getinput(); price = dorm + meal; price myprice = new price(); myprice._pricelabel = _price; myprice.showdialog(); } private void getinput() { if(allenradiobutton.checked) { dorm = 1500; } if(pikeradiobutton.checked) { dorm = 1600; } if(far

plist - Mac run shell script startup -

i have plist file should start shell script on startup. <?xml version="1.0" encoding="utf-8"?> <!doctype plist public "-//apple//dtd plist 1.0//en" "http://www.apple.com/dtds/propertylist-1.0.dtd"> <plist version="1.0"> <dict> <key>label</key> <string>com.app.localclient</string> <key>program</key> <string>~/documents/local_client/server.sh</string> <key>runatload</key> <true/> <key>keepalive</key> <true/> </dict> </plist> i've saved plist file com.app.localclient.plist , have tested shell script works fine. when try load script launchctl load com.app.localclient.plist , loads plist not start shell script. i've changed program parameter ~ /users/username/ , no succes. there way make plist start shell script , can done without knowing username of script saved (so using ~

subprocess - Running shell scripts under one process in Python -

this question has answer here: python threading multiple bash subprocesses? 3 answers i'm quite new shell scripting. have execute shell scripts using python. order of shell scripts important. here example python code import subprocess import os script1= "scripts/script1.sh" script2 = "scripts/script2.sh" script3 = "scripts/script3.sh" subprocess.call([script1]) subprocess.call([script2]) subprocess.call([script3]) the problem above code scripts executed separately 1 after other want run under 1 process. for example, script2 , script3 should executed while script 1 running. while op apparently refuses clarify question, left comment indicating looking subprocess.popen() . procs = [] cmd in ['scripts/script1.sh', 'scripts/script2.sh', 'scripts/script3.sh']: procs.append(subprocess.popen([c

php - Compare table field values to insert new value in database -

i inherited website existing database structure. have 1 table ( table1 ) has following structure: position_1_tags_permitted | position_2_tags_permitted | position_3_tags_permitted ---------------------------------------------------------------------------------- cd | en,cs | tech,cs table1 has structure 20 columns. i have table ( table2 ) stores selected value (also has 20 columns): pos1_sel_symbol | pos2_sel_symbol | pos3_sel_symbol | pos4_sel_symbol --------------------------------------------------------------------- | aapl | | aa i have tags selected variable in case tag variable cs . i'd find position in table1 has allowed tags , in table2 see if position has entry in it. in case identify position 3 column add entry , write new update statement add entry database. there easy way column format of database? edit: if there multiple tags variable i'd search permitted tags c

iOS - Complex string comparisons using NSPredicate -

i need compare strings such conditions met. conditions not patterns can match using regex rather "expression" conditions. for instance match string when number between 2 values: inputstring = "the price of flight paris 550$ , tomorrow go 150$" matchingcondition = "the price of flight paris expression( 500 < x < 600)$ , tomorrow go expression(100 < y < 200)$" i need run comparison on random texts don't input string in question. i.e. inputstring = "blah blah blah" i able compare using simple true/false function. i.e.: match(inputstring,matchingcondition) -> boolean examples: match(inputstring : "the price of flight 400$",matchingcondition : "the price of flight expression( 300$ < x < 401)$") -> true match(inputstring : "the price of flight 402$",matchingcondition : "the price of flight expression( 300$ < x < 401)$") -> false match(inputstring : &qu

python - 'Operation Denied' Error when deploying an Elastic Beanstalk app using awsebcli -

i'm trying deploy django application onto elastic beanstalk first time. i've been following 2 tutorials here , here assistance running issue tutorials not seem cover. the steps followed far installed awsebcli python3.4 virtual environment , cd projects directory. call eb init . prompted type in access keys. had saved them text file copy , pasted keys (ensuring no trailing white spaces) terminal. the problem error thrown back: error: operation denied. request signature calculated not match signature provided. check aws secret access key , signing method. consult service documentation details. the weird thing on subsequent attempts error pops earlier after enter region number deployment. still prompts me keys anyway: error: current user not have correct permissions. reason: operation denied. request signature calculated not match signature provided. check aws secret access key , signing method. consult service documentation details. here full output of e

java - select positions of value of string or int -

i'm trying select positions of value , print parts of value position in java when i'm working on android app. example if have number four-digit, 4375 if select 3rd 1 system print 7, 4th 1 system print 5.. you can select portion of string string.substring() methods. see https://docs.oracle.com/javase/7/docs/api/java/lang/string.html more help. hence, convert digit string , use substring() method part want. i provide solution suggestion: private string getsubdigit(int value, int postion){ // should check if value correct , ready processed. if(check(value)) { string temp = "" + value; return temp.substring(position,position+1); }else{ return ""; } }

php - regular expression, match all text within two characters -

i need ask because takes me time go on again , again every time needed, how match this: tom yorke(55555) when given this: cn=tom yorke(55555),ou=admins,ou=london,ou=users,dc=domain,dc=london,dc=local using php preg_match() only want first occurence of text within = , , try this. $result hold match, or null if there's not match $data = "...";//original string $pattern = '/=([^,]+)/'; $matches = []; preg_match($pattern, $data, $matches); $result = count($matches)? $matches[1]: null; // tom yorke(55555) live demo