Posts

Showing posts from April, 2013

mysqli - php using prepared statement within foreach loop -

according example prepared statements first bind parameters , set values parameters. let's assume have 2-dim array $alias $array1 = [ 'id' => 1, 'tstamp' => 123456789, 'alias' => '$alias', ]; $array2 = [ 'id' => 1, 'tstamp' => 123456789, 'alias' => '$alias2', ]; $alias = [$array1, $array2]; why code working $insert = 'insert abcdef values (?,?,?)'; $insertstmt = $conn->prepare($insert); foreach ($alias $array) { $insertstmt->bind_param('iis', $array['id'], $array['tstamp'], $array['alias']); $insertstmt->execute(); } and not? $insert = 'insert abcdef values (?,?,?)'; $insertstmt = $conn->prepare($insert); $insertstmt->bind_param('iis', $array['id'], $array['tstamp'], $array['alias']); foreach ($alias $array) { $insertstmt->execute(); } if have bind...

php - How to validate phone number in laravel 5.2? -

i want validate user input phone number number should 11 , started 01 , value field should number only. how do using laravel validation? here controller: public function saveuser(request $request){ $this->validate($request,[ 'name' => 'required|max:120', 'email' => 'required|email|unique:users', 'phone' => 'required|min:11|numeric', 'course_id'=>'required' ]); $user = new user(); $user->name= $request->input(['name']); $user->email= $request->input(['email']); $user->phone= $request->input(['phone']); $user->date = date('y-m-d'); $user->completed_status = '0'; $user->course_id=$request->input(['course_id']); $user->save(); return redirect('success'); } one ...

Is there a better way to make this mysql query using inner join commands? -

in database have several tables "many many" relationships referencing 1 another, , way taught make queries through embedded queries. i've been reading "many many" relationships, , how query them using "inner join" but, don't seem able find queries fit i'm looking for, , since database work big tables don't want code have performance issues. select salones.idsalon, salones.lat, salones.long, recursos.idrecurso, recursos.recurso salones, recursos, salones_has_recursos salones_has_recursos.salones_idsalon=salones.idsalon , salones_has_recursos.recursos_idrecurso=recursos.idrecurso , recursos.idrecurso in (select idrecurso salones_has_recursos idrecurso in (select idrecurso recursos recurso = 'audiovisual' ...

Eclipse indexing - what do the various options do -

when right-click > index on project there few options: rebuild freshen files update modified files re-resolve unresolved includes i've been hitting rebuild everytime i'm working on huge project , can't afford that; when modify file, whether it's .cpp or .h, need know 'index' operation do. for each of 'index' options: what precisely do? what cost (relative memory, cpu time)? documentation eclipse helpful searched , didn't find any.

c++ - Qt GUI doesn't work with std::thread as I expect -

the core of project independent of gui framework that's why prefer std::thread. qt gives me error when thread using. the inferior stopped because received signal operating system. signal name: sigsegv signal meaning: segmentation fault //mainwindow.h #ifndef mainwindow_h #define mainwindow_h #include <thread> #include <mutex> #include <qmainwindow> namespace ui { class mainwindow; } struct observer { virtual void notify() = 0; }; class core { public: std::thread *run() { std::thread thread(&core::runp, this); thread.detach(); return &thread; } void setobserver(observer *observer) { _observer = observer; } int ii() const { return _ii; } void nextii() { _ii++; } void lock() { _mutex.lock(); } bool trylock() { return _mutex.try_lock(); } void unlock() { _mutex.unlock(); } private: void runp() { (int = 1; <= 1000; i++)...

java - How to output files with a specific extension (like .csv) in Hadoop, using MultipleOutputs class -

i have mapreduce program uses multipleoutputs to output result multiple files. reducer looks this: private multipleoutputs mo = new multipleoutputs<nullwritable, text>(context); ... public void reduce(edge keys, iterable<nullwritable> values, context context) throws ioexception, interruptedexception { string date = records.formatdate(millis); out.set(keys.get(0) + "\t" + keys.get(1)); parser.parse(key); string filepath = string.format("%s/part", parser.getfileid()); mo.write(noval, out, filepath); } this similar example in book hadoop: definitive guide - however, problem outputs files plain text. want files outputted .csv files , haven't managed find explanation on in book or online. how can done? have tried iterate through output folder after completion of job object in driver rename files? as long emit in reducer (the text should line in csv values separated semicolon o...

Clone TFS-GIT repository to GIT repository (Linux) by using GIT -

we have redhat linux server, git installed on server , need create local repository. we have tfs-git project in tfs 2015, need clone tfs-git repository git repository on linux using git commands. for task, created empty local repository on linux, , configured basic authentication , configured ssl certification using server manager. still getting "fatal: authentication error" connecting tfs-git repository on windows server 2012 . tried in different ways still getting same error. am using basic credentials used server logins , have id , password everything. is there specific kind of passsord need use this? please advise me on this thanks in advance you have done should be. need copy public key of desired user unix server work. how setup ssh-key? # generate key (local machine) ssh-keygen -t rsa # copy generated key unix machine (server) # key in : %home%/.ssh/id_rsa.pub # in widows under user account: users/<user_name> other ways if ...

c# - Opening more than 150 ports on Azure VM using Azure SDK -

i need open more 150 public ports on single vm using azure sdk. right limited 150 ports, , when try open more using azure sdk, service error. there way around or way open more 150 ports using sdk? that problem addressed in 2014. https://feedback.azure.com/forums/216843-virtual-machines/suggestions/3995978-allow-to-open-more-ports-that-the-150-ports-limit introducing instnace-level public ip address provides virtual machine full port range opened default. http://azure.microsoft.com/en-us/blog/instance-level-public-ip-address/

spring - How to get alias.table from oracle database using HikariCP -

i came across issue recently. not sure if it's hikaricp or oracle or spring boot. when try use schema datasource.schema(application.yml/application.properties) getting error. hikaricp starts fails immediatly saying property schema doesn't exist. how supposed use schema in oracle databases? driver class name : oracle.jdbc.pool.oracledatasource - ojdbc-7 main] com.zaxxer.hikari.hikaridatasource : hikaripool-1 - started. main] com.zaxxer.hikari.util.propertyelf : property schema not exist on target class oracle.jdbc.pool.oracledatasource (i know can't set schema hikaricp! how now?) is @ possible connect oracle database using schema(alias) using hikaricp? for wondering wth hikaricp: https://github.com/brettwooldridge/hikaricp place learn. solution! hikaricp takes connectioninitsql property can set to: connectioninitsql =alter session set current_schema=xyz(your schema name) solution page public datasource datasource(datasourceproperti...

wpf - Dynamically generating 2D grid with row and column headers -

i'm starting out ireactivelist<icoordvm> where: interface icoordviewmodel { object x {get;} object y {get;} viewmodel viewmodel {get;} } i'd create grid list view each viewmodel located @ appropriate x/y coordinate. additionally, rows , columns must labeled according to, say, tostring() values of x , y. finally, i'd avoid redrawing entire grid new items added list. i'm deliberating whether use grid, datagrid, or else. using datatable/datagrid described in second solution here seems me row , header columns, seems i'll need inject new datatable , redraw screen every time item added. using gridhelpers described in this solution might give me way avoid redraw, there's no description how include row , column headers. anyone have creative ideas how tackle this? here's solution came with. this link helped tremendously; pirated xaml directly: <datatemplate x:key="datatemplatelevel2"> <cont...

javascript - Firebase querying when combining orderByChild startAt and limitToFirst -

i'm trying set firebase query implement pagination me. similar this: https://www.firebase.com/blog/2013-10-01-queries-part-one.html#paginate my problem when try combine 3 methods mentioned above. example, 1 of ref's looks this: userref = ref.child('users').orderbychild('email').startat(null, end.id).limittofirst(number(limit)) so have users list. want ordered alphabetically email. want new query start @ last entry of old query. lastly want limit amount of children returned number 4. now when combine 2 of these methods such startat , limittofirst in other lists, query works expected. unfortunately depends on list being presorted in firebase already. happens user query firebase returns first limit number of children always. it's ignoring startat part. i've tried hardcoding in keys , goes ignored. i know can tell firebase sort entries using indexon rules , if have reconstruct database last resort (i implemented indexon after made users). feel sh...

javascript - How to access the UIPrintInteractionController class with NativeScript -

i'm trying implement airprint printing , need instantiate uiprintinteractioncontroller . however, can't seem find class. how can access uikit class nativescript? function findprinter() { var printcontroller = uiprintinteractioncontroller.new(); console.log(printcontroller); } exports.findprinter = findprinter; use following syntax case : function findprinter() { var printcontroller = uiprintinteractioncontroller; console.log(printcontroller.isprintingavailable()); } exports.findprinter = findprinter; here more example objective-c js based on {n} documenation objective-c code nsmutablearray * array = [[nsmutablearray alloc] init]; class buttonclass = [uibutton class]; uibutton * button = [[buttonclass alloc] init]; [array setobject: buttonclass atindex: 0]; [array setobject: button atindex: 1]; nativescript code var array = new nsmutablearray(); var buttonclass = uibutton; var button = new buttonclass(); array.setobjectatindex(buttonc...

python - Does TensorFlow perform poorly for simple networks? -

i've been experimenting simple basic (intro tutorial-level) neural networks in various frameworks, confused performance i'm seeing in tensorflow . for example, simple network michael nielsen's tutorial (mnist digit recognition using l2 stochastic gradient descent in network 30 hidden nodes) performs worse (takes 8x long per epoch, same parameters) adapted (using vectorization mini-batch suggested in one of tutorial exercises ) version of nielsen's basic numpy code . does tensorflow, running on single cpu, perform badly? there settings should tweak improve performance? or tensorflow shine more complex networks or learning regimes, not expected such simple toy cases? from __future__ import (absolute_import, print_function, division, unicode_literals) import tensorflow tf tensorflow.examples.tutorials.mnist import input_data import time def weight_variable(shape): return tf.variable(tf.truncated_normal(shape, stddev=0.1)) def bias_variable(shape): ...

c - error when reading file gcc version 4.4.7 but not gcc 6.1 -

i trying read file using fscanf, segmentation fault when try fclose() or free char* writing contents of file to. here code: #include <stdlib.h> #include <stdio.h> #include <string.h> int main(int argc, char **argv){ file *fp = fopen(argv[1],"r"); if(fp == null){ fprintf(stderr, "error: file not found.\n"); return 1; } char* directive = malloc(9); while(fscanf(fp,"%s",directive) != eof){ printf("%s\n",directive); } //fclose(fp); seg fault //free(directive); free(): invalid next size (fast) return 0; } what more unusual when run code own computer gcc version 6.1 works fine, running on server gcc 4.4.7 doesn't work. edit: file trying read .byte 0000045d 00 .byte 00000457 09 .byte 00000458 09 .byte 00000141 0a .byte 00000183 0a .byte 000001ca 0a .byte 0000020d 0a .size 0800 .string "enter new char" .byte 0000...

javascript - Pass JSON-encoded PHP Variable to HighCharts -

i'm attempting insert json-encoded mysql results set php variable highcharts script. i have inserted mysql results list php variable highcharts in different instance, formatted highchart-acceptable data group concatenating commas , apostrophes in sql select statement (which dirty effective way it). goal make chart display metadata in tooltip, cannot work, think close have. -- here php script retrieve data mysql database , json encode it: $mysqli = new mysqli('localhost','username','password','database'); $myarray = array(); if ($result = $mysqli->query(" select time_minutes.minutes*60+time_seconds.seconds y, run_date.id id, run_date.date rundate, run_temp.temperature temperature, run_conditions.weather conditions, run_hydration.hydration_level hydration run_conditions, run_date, run_hydration, run_notes, run_temp, time_minutes, time_seconds run_date.id = run_conditions.id , run_date.id = run_hydration.id , run_date.id = run_note...

rxjs - Subscribe twice to Angular 2 Http? -

i have service calling api processes request , performs standard error handling on api requests. instance have apierrorsservice want call when api call gets error. want submit calls in standard way, i.e. setting content-type application/json , serializing request object. of course when subscribe observable returned http called once, , when return , caller subscribes called again. best way able listen results in 2 places without performing api call twice? can call .publish() or .share() , return that? need dispose of it? there timing issues may occur? if mock api call , return value work fine, or caller's subscription miss values? here's code have: post(path: string, data: any): observable<response> { var headers: headers = new headers(); headers.set("content-type", "application/json"); var s = data == null ? null : json.stringify(data, null, 2); var shared = this.http.post(path, s, { headers: headers }).share(); ...

How to convert json array to javascript array using specific values -

i want convert json array (string) javascript array using specific values. json array : [{"id":47,"libelle":"famille de test"},{"id":1,"libelle":"geolocalisation"},{"id":4,"libelle":"outils"},{"id":2,"libelle":"proprete"},{"id":3,"libelle":"urgence"}] and want ["famille de test", "geolocalisation", ...] using libelle values. tried use $.map didn't work out. the map implementation should work: var jsonstr = '[{"id":47,"libelle":"famille de test"},{"id":1,"libelle":"geolocalisation"},{"id":4,"libelle":"outils"},{"id":2,"libelle":"proprete"},{"id":3,"libelle":"urgence"}]'; var arr = json.parse(jsonstr); var libelle = arr.map(function(x) { retu...

c++ List class as Student type -

i trying use class student , declare list type. can pushback without changing list.h or node.h how can print data in list2? given print() function within list..h not work :( node.h #ifndef node_h #define node_h #include <string> #include <iostream> using namespace std; template <typename t> class node { private: t data; node<t>* next; public: node(t); virtual ~node(); // base class destructor must virtual template <typename u> friend class list; }; template <typename t> node<t>::node(t d) { data = d; next = null; } template <typename t> node<t>::~node() { } #endif /* strnode_h */ list.h #ifndef list_h #define list_h #include "node.h" // singly linked list template <typename t> class list { private: node<t>* head; // pointer first node node<t>* tail; // pointer last node int count; // number of nodes in list public: class outofrangeexception{ }; // empty inner class e...

ios - Testing connectivity / availability of IP Address in Objective C -

basically able check whether particular host on local network "up". the following line of code hangs when host unreachable, i'd perform check first before running it. [_outputstream write:[data bytes] maxlength:[data length]]; a similar query think answered in following link, think need use cfhostcreatewithaddress rather cfhostcreatewithname alternatives nshost in iphone app here attempt @ i'm trying do... boolean result; struct sockaddr_in address; address.sin_family = af_inet; address.sin_port = htons(80); inet_pton(af_inet, "192.168.1.31", &address.sin_addr); cfdataref sockdata = cfdatacreate(null, &address, sizeof(address)); cfhostref host = cfhostcreatewithaddress(null, sockdata); result = cfhoststartinforesolution(host, kcfhostaddresses, null); if (result == true) { nslog(@"resolved"); } else { nslog(@"not resolved"); } even when host not resolved. below attempt use reachability class. cod...

php - Use of ajax in Silex Framework -

i'm pretty new silex framework , wondering how make simple login (using securityserviceprovider) ajax request. works in code (see below) how can change html page returned boolean giving true or false wether login worked or not . app.php use symfony\component\debug\errorhandler; use symfony\component\debug\exceptionhandler; // register global error , exception handlers errorhandler::register(); exceptionhandler::register(); // register service providers $app->register(new silex\provider\doctrineserviceprovider()); $app->register(new silex\provider\twigserviceprovider(), array( 'twig.path' => __dir__ . '/../views', )); $app->register(new silex\provider\urlgeneratorserviceprovider()); $app->register(new silex\provider\sessionserviceprovider()); $app->register(new silex\provider\securityserviceprovider(), array( 'security.firewalls' => array( 'secured' => array( 'pattern' => '^/...

Reparse Page Selenium Web Driver - Python -

is possible reparse page using selenium? click button using function html changes because of javascript , want reparse page, not refresh it. the methods of get/refresh cause page reload isn't i'm looking for. it not "reparsing" actually. understand detecting changes made on page. that, should use webdriverwait , set of built-in expected conditions (or can write custom one ) wait change made on page. let's say, instance, element added page when click button. here how wait until element visible: from selenium.webdriver.common.by import selenium.webdriver.support.ui import webdriverwait selenium.webdriver.support import expected_conditions ec # ... button.click() wait = webdriverwait(driver, 10) wait.until(ec.visibility_of_element_located((by.css_selector, "#id-of-the-added-element"))) # page "re-parsed" print(driver.page_source) it wait up to 10 seconds checking state of expected condition every 500 milliseconds (by def...

php - Allow user to enter comma separated values into input and return unique items -

i using php amazon's product advertising api have user enter isbn number search form , have return product info. is there way allow user enter multiple isbn numbers, separated comma, , return product info each number entered? here have far works: //allow users enter multiple isbn, separated comma $myvalue = $_post['isbnnum']; $arrs = explode(", ", $myvalue); $similar = array( 'operation' => 'itemlookup', 'idtype' => 'isbn', 'itemid' => $myvalue, 'searchindex' => 'books', 'responsegroup' => 'medium' ); $result = $amazon->queryamazon($similar); $similar_products = $result->items->item; //arrays $aws_items = array(); //array counter $i = 0; foreach($similar_products $si){ $item_url = $si->detailpageurl; //get amazon url $img = $si->mediumimage->url; //get image url $title = $si->itemattrib...

android - activities/fragments' lifecycle methods called in the main thread? -

are activities/framgents' lifecycle methods called in main thread default? i'm implementing class checkes if app in foreground/background. i'm using activities' onpasue/onresume that. make sure don't have synchronize methods of class. yes, are. in general, if called off main thread documentation state so.

osx - Find newest file in folder via the terminal (seconds apart) -

i trying extract newest file in folder. tried this: ls -1t | head -1 but problem is, command doesn't seem differentiate in second file created - if multiple files created in the same, command give first file in minute. is there way make command more precise? you should add t argument options that: ls -1tt | head -1 see output when l argument added: ls -ttl -rw-r--r-- 1 user wheel 0 apr 23 17:54:27 2016 1 -rw-r--r-- 1 user wheel 0 apr 23 17:54:19 2016 3 -rw-r--r-- 1 user wheel 0 apr 23 17:54:12 2016 2

swift - Swiftyjson - JSON to table view with alphabetical sections -

once json http request through alamofire, following swiftyjson json object mentioned @ bottom of post. how can extract sections in format? var sections : [(index: int, length :int, title: string)] = array() length being number of contact under each section. title letter and how can extract each array of object under each letter? all of using swift. the objective create list of contacts tableview , alphabetical sections. please let me know if i'm not clear. json object: { "t" : [ { "location" : "shanghai", "firstname" : "user3", "id" : 3, "created_at" : "2016-04-19 12:54:23", "birthdate" : "2016-04-17", "email" : "user3@test.com", "profilephotopath" : "photos\/emptyprofilephoto.jpg", "updated_at" : "2016-04-19 12:54:23", "lastname" : ...

teamcity - Executing VSTest.Console.exe test via Powershell Invoke-Command -

so i'm trying kick off test runs via vstest.console.exe using powershell's invoke-command. i'm pretty new powershell, script looks this: $secpasswd = convertto-securestring “p@ssword01” -asplaintext -force $credentials = new-object system.management.automation.pscredential (“administrator”, $secpasswd) $sharename = "testruns" #script block execute on remote machine $scriptblock = { param($sharename, $testrunid, $mytestcontainers, $testcategory) $localfolder = "c:\$sharename\" + $testrunid $exepath = "c:\program files (x86)\microsoft visual studio 12.0\common7\ide\commonextensions\microsoft\testwindow\vstest.console.exe" $arglist = @() #add containers $mytestcontainers.split(",") | foreach { $arglist += "`"$localfolder\$_`" " } $arglist += "/logger:trx" $arglist += "/settings:$localfolder\remote.testsettings" $arglist += "/platform:x64" $arglist += "/framework:framewor...

python - Timed Window closure in pygame -

solved, missing gameexit definition. credit lpk. i have been working on game 3 days far , has gone far. have issue, time open program opens closes after. @ first thought death function triggering , cause close after commenting out code, found not problem. don't know what's wrong. #!/usr/bin/python3 import pygame #import file colors.py pygame.init() white = (255,255,255) #game display display_width = 800 display_height = 600 gamedisplay = pygame.display.set_mode((display_width,display_height)) pygame.display.set_caption('sound soul') clock = pygame.time.clock() #characterimg = pygame.image.load(' ') #functions #start of game loop def game_loop(): x = (display_width * 0.45) y = (display_height * 0.8) def character_display(x,y): gamedisplay.blit(characterimg,(x.y)) x_move = 0 y_move = 0 dead = false if dead == false: gameexit = false elif gameexit == true: pygame.quit() quit() #logic loop while not dead: event in pygame.eve...

Python selenium string to int -

i've tried of examples on stackoverflow can't find way. have 2 questions, how make string text.. posts = driver.find_elements_by_class_name("currency-chaos") numberofitems = 1 post in posts: numberofitems = numberofitems + 1 print(numberofitems) print(post.text) and how remove letter text, transfer int? you use regular expression remove non digit characters , parse number float : import re value = float(re.sub(r"[^\d.]", "", post.text)) print("value: %s" % value)

java - Quartz Scheduler worker threads not running jobs even with huge number of jobs in queue -

Image
we have 30 worker threads in quartz scheduler, , there 104k jobs in queue (they piled since quartz not processing fast enough , lots of bulk jobs submitted). can see in thread dump, of these threads waiting without working. why these worker threads not running jobs in queue missing fire time? could there bottlenecks before jobs distributed workers? see few jobs running @ time instead of upto 30 jobs @ once. i should note happens irrespective of 1 scheduler process or many. any pointers find why many (at 30) jobs not getting picked , executed @ once appreciated. quartz version: 2.1.3 (with oracle jdbc jobstore) config file #============================================================================ # configure main scheduler properties #============================================================================ org.quartz.scheduler.instancename = ****_scheduler org.quartz.scheduler.instanceid = auto #===================================================================...

ontology - Executing a SPARQL query -

i have created small ontology. has 1 class called methods , datatype property action_nb (integer). then created 2 individuals : ahp => action_nb = 20 electre => action_nb = 50 i want execute simple query . select method nb_action < 40 , results should give me el1. <?xml version="1.0"?> <!doctype rdf:rdf [ <!entity owl "http://www.w3.org/2002/07/owl#" > <!entity xsd "http://www.w3.org/2001/xmlschema#" > <!entity rdfs "http://www.w3.org/2000/01/rdf-schema#" > <!entity rdf "http://www.w3.org/1999/02/22-rdf-syntax-ns#" > <!entity untitled-ontology-77 "http://www.semanticweb.org/diabolico/ontologies/2016/3/untitled-ontology-77#" > ]> <rdf:rdf xmlns="http://www.semanticweb.org/diabolico/ontologies/2016/3/untitled-ontology-77#" xml:base="http://www.semanticweb.org/diabolico/ontologies/2016/3/untit...

sql server - Build json with variable key / json_modify variable 2nd parameter -

suppose have create schema tmp go create table tmp.properties ( parentid uniqueidentifier not null, propertyname nvarchar(20) not null, propertyvalue nvarchar(100) null, primary key (parentid,propertyname) ) go create table tmp.fulldata ( parentid uniqueidentifier not null, properties nvarchar(max) null, primary key (parentid) ) go declare @id1 uniqueidentifier = 'f1935d6a-d5a6-4fa1-acf4-ba3858804cec', @id2 uniqueidentifier = 'f1935d6b-d5a6-4fa1-acf4-ba3858804cec' insert tmp.properties values (@id1, 'firstname', 'luke'), (@id1, 'lastname', 'skywalker'), (@id2, 'firstname', 'han'), (@id2, 'lastname', 'solo') please consider that: properties dynamically created , cannot know in advance propertynames at moment parents table contains 1m , properties table contains 23m records how can fill tmp.fulldata with: parentid properties ------------...

Why does Servlet think my empty HTML file element has a file in it? -

i using java servlet handle html form , includes file input element: <input type="file" id="fileupload" name="file" multiple /> i used example code in this excellent answer process multiple files @ once. code i'm using is: list<part> fileparts = req.getparts().stream().filter(part -> "file".equals(part.getname())).collect(collectors.tolist()); // retrieves <input type="file" name="file" multiple="true"> (part filepart : fileparts) { string filename = filepart.getsubmittedfilename(); inputstream filecontent = filepart.getinputstream(); // stuff here } this code works great. problem is, when don't attach anything, code still thinks fileparts has part object in it. doing debugging, part object seem there, of course there no inputstream or submittedfilename get, since didn't upload files. why this? new lambda functions , collections, seems ...

read from file as parallel arrays in java -

this code read file , display in console try { bufferedreader readfile = new bufferedreader(new filereader("sales.txt")); string line = ""; while((line = readfile.readline()) != null) { string tmp[] = line.split(","); year = integer.parseint(tmp[0]); quarter = tmp[1]; sales = integer.parseint(tmp[2]); //system.out.printf("year: %s\tquarter: %s\tsales: %d\n",year,quarter,sales); } readfile.close(); } catch(ioexception e) { e.printstacktrace(); } userinput.close(); in file named "sales.txt" have this: 2012,q1,9300 2012,q2,10225 2012,q3,12420 2012,q4,13250 2013,q1,10500 2013,q2,10900 2013,q3,11340 2013,q4,14600 now stuck on how calculate average sales q4 in year 2012 , 2013 just case: float avg = 0; int counter = 0; try { bu...

python - Scipy basinhopping not respecting stepsize? -

running following code, on 7th print out of parameter being evaluated (x), parameter jumps 100 .01 despite initial stepsize being set .1 , interval being set 50. how basinhopping able make jump exceeds stepsize such large magnitude? import multiprocessing mp scipy.optimize import basinhopping def runenvironment(x): return x**2 def func(x): print "x:",x pool = mp.pool(processes=1) results=pool.apply(runenvironment,(x,)) pool.close() return results if __name__ == '__main__': x0=100 ret=basinhopping(func, x0, niter=100, t=1.0, stepsize=.1, minimizer_kwargs=none, take_step=none, accept_test=none, callback=none, interval=50, disp=false, niter_success=none) basinhopping iterative procedure uses local minimization, takes step in coordinate space (stepsize) local minimization again, different minimum. the stepsize parameter applies step in coordinate space. in example default local minimizer (bfgs think) finds globa...

iterator - How do I use std::transform in c++? -

i learning c++, , have created simple calculator program. pertaining this, have few questions: first, there can clean up, or make better? secondly, in code, use goto statement return start of program. have heard goto looked down upon many programmers because can create "spaghetti" code. there not use goto , rather llop of sort? lastly, coppied line of code internet: std::transform(returntomain.begin(), returntomain.end(), returntomain.begin(), ::toupper); can explain me does? understand transform , ::toupper but not .begin() , .end() here full code, , thank help: #include <iostream> #include <stdlib.h> #include <string> #include <cmath> #include <algorithm> using namespace std; void showmenu(); unsigned long facinput; //prototyping functions int getinput(); float additiongetinput(); float subtractiongetinput(); float multiplicationgetinput(); float divisiongetinput(); unsigned...

algorithm - Codility EvenSums Game -

Image
i'm trying finish codility challenge improve programming skills. details of challenge here . copy problem statment down here also. even sums game 2 players. players given sequence of n positive integers , take turns alternately. in each turn, player chooses non-empty slice (a subsequence of consecutive elements) such sum of values in slice even, removes slice , concatenates remaining parts of sequence. first player unable make legal move loses game. you play game against opponent , want know if can win, assuming both , opponent play optimally. move first. write function: string solution(vector< int>& a); that, given zero-indexed array consisting of n integers, returns string of format "x,y" x , y are, respectively, first , last positions (inclusive) of slice should remove on first move in order win, assuming have winning strategy. if there more 1 such winning slice, function should return 1 smallest value...

android - Gap between CardViews increases on scrolling -

Image
i'm using carviews recyclerview , looks fine when loaded once when list scrolled gap between cardviews increases , there shows 1 card in view @ time. here cardview.xml <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto"> <android.support.v7.widget.cardview android:id="@+id/conversationcard" android:layout_width="match_parent" android:layout_height="wrap_content"> <relativelayout android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="16dp"> <textview android:id="@+id/sender" android:layout_width="wrap_content" andr...