Stack Overflow

Subscribe to Stack Overflow feed
most recent 30 from stackoverflow.com 2017-11-22T13:16:57Z
Updated: 9 hours 4 min ago

Capitalize the first letter of each word using

9 hours 20 min ago

I'm doing a class on javascript this semester, and one of this week's exercises was to take a string of words, and capitalize the first letter of each word. I did that using .map(), the code is here :

let t1 = "hello how are you doing".split(" "); let t2 = t1.map(function(word) { return word[0].toUpperCase() + word.slice(1); }); console.log(t2.join(" "));

And it works perfectly fine. However, I was wondering why, when I try with forEach(), I can't make it work. Here is my code :

let t1 = "hello how are you doing".split(" "); t1.forEach(function(word) { word[0] = word[0].toUpperCase(); }) console.log(t1.join(" "));

My understanding of forEach() is that it cycles through every element of the table, much like a simple for loop. So then shouldn't my code take the first letter of each word, and replace it with the same letter, to which toUpperCase() is applied?

edit : I already know how to capitalize the first letter of each word, I was just asking about the different methods

What is the modulo return?

9 hours 32 min ago

In the following code, what is the !(X % Y) returning?

int count = 2; bool notprime = false; while (count < num) { if (!(num % count)) notprime = true; count++; }

In other words, does it mean that when ( num % count ) is 0, then the parenthesis will return true? Or will it return false? And what if negating ( ! ) it - as in the code? I'm having trouble understanding the flow...

Why is the content after the zero character not assigned?

9 hours 43 min ago
#include<iostream> #include<string> using namespace std; int main(){ string a; a="this is string\0 this part not assigned why?"; cout<<a; cout<<"sth"; cout<<endl; a.push_back('\0'); cout<<a; cout<<"sth"; }

Q: Why is the content after the \0 not assigned to the string a?

Is there a elegant way to only keep top[2~3] value for each row in a matrix?

9 hours 44 min ago
What I have

I have a user-user correlation matrix called matrixcorr_of_user like the one below:

userId 316 320 359 370 910 userId 316 1.000000 0.202133 0.208618 0.176050 0.174035 320 0.202133 1.000000 0.242837 0.019035 0.031737 359 0.208618 0.242837 1.000000 0.357620 0.175914 370 0.176050 0.019035 0.357620 1.000000 0.317371 910 0.174035 0.031737 0.175914 0.317371 1.000000 What I want

For every user, I just want to keep the 2 other users that are the most similar to him (the highest correlation values per row after excluding the elements of the diagonal). Like so:

Out[40]: userId 316 320 359 370 910 corr_user 316 NaN 0.202133 0.208618 NaN NaN 320 0.202133 NaN 0.242837 NaN NaN 359 NaN 0.242837 NaN 0.357620 NaN 370 NaN NaN 0.357620 NaN 0.317371 910 NaN NaN 0.175914 0.317371 NaN

I know how to achieve it, but the way I came up with is too complicated. Could anyone provide a better idea?

What I have tried

I first melt the matrix:

melted_corr = corr_of_user.reset_index().melt(id_vars ="userId",var_name="corr_user") melted_corr.head() Out[23]: userId corr_user value 0 316 316 1.000000 1 320 316 0.202133 2 359 316 0.208618 3 370 316 0.176050 4 910 316 0.174035

filter it row by row:

get_secend_third = lambda x : x.sort_values(ascending =False).iloc[1:3] filted= melted_corr.set_index("userId").groupby("corr_user")["value"].apply(get_secend_third) filted Out[39]: corr_user userId 316 359 0.208618 320 0.202133 320 359 0.242837 316 0.202133 359 370 0.357620 320 0.242837 370 359 0.357620 910 0.317371 910 370 0.317371 359 0.175914

and finally reshape it:

filted.reset_index().pivot_table("value","corr_user","userId") Out[40]: userId 316 320 359 370 910 corr_user 316 NaN 0.202133 0.208618 NaN NaN 320 0.202133 NaN 0.242837 NaN NaN 359 NaN 0.242837 NaN 0.357620 NaN 370 NaN NaN 0.357620 NaN 0.317371 910 NaN NaN 0.175914 0.317371 NaN

Getting floor division and remainder at same time in 2 separate variables

9 hours 54 min ago

Is there a python built-in (or just optimized) function to get the floor division and remainder at the same time in two separate variables?

Example:

a, b = 10 divided by 4

Desired results:

a = 2 b = 2

I need this to be an optimized solution.

Performance results:

First piece of code:

for i in range(10000000): a, b = divmod(i, 5) took 3.99 seconds to run

Second piece of code:

for i in range(10000000): a = i // 5 b = i % 5 took 2.56 seconds to run

Import Google Translation API to Android Studio

12 hours 44 min ago

I´ve registered for Google Cloud Services and activated the Google Cloud Translation API. Now I want to start an Android Studio Project, using this API. In the documentation they refer to Import the following librarys:

import com.google.cloud.translate.Translate; import com.google.cloud.translate.Translate.TranslateOption; import com.google.cloud.translate.TranslateOptions; import com.google.cloud.translate.Translation;

How to get these librarys for Java/Android Studio?

https://cloud.google.com/translate/docs/reference/libraries

On this page under 'Installing the client library' one can not find something for Java.

So how to use this API in Android Studio?

Kdb upsert with conditional syntax?

21 hours 7 min ago

Is there a way I can upsert in kdb where the following occurs: 1) If key is not present, insert values 2) If key is present, check if current value is greater A) If so, perform no action B) If not, update values

Something like: job upsert ([title: job1] time: enlist 1 where time > 1)

JavaScript: Setter for inner object

21 hours 7 min ago

I have a simple object and constructor in Traditional JavaScript as follows:

function Test() { } Test.prototype={ data: {}, set value() { }, get value(property) { return data[property]; } }; var test=new Test();

Inside the object is another object, initially with no own properties.

I would like to write a Setter for value which sets a property on the inner object (data).

test.value.whatever=23;

Is there any way I can do this?

I expect that the Setter function could then finish the job with something like this:

set value() { // how do I get property & value? data[property]=value; },

What to use for timeseries: datenum, datetime or timeseries

21 hours 7 min ago

I'm using timeseries all the time and using datenum only. I heard, that datetime is better to use or will be better in the future. There also are Time Series Objects.

What are your recommendations regarding usability and speed?

Philipp

Unchecked overriding (well, I seem to need my generics method)

21 hours 8 min ago

I've got generic interface Operand:

public interface Operand<T extends Operand<T>> { T add(Operand<T> op); T sub(Operand<T> op); T mul(Operand<T> op); T div(Operand<T> op); }

which is implemented by 2 classes:

public class DoubleOperand implements Operand<DoubleOperand> { ... } public class RationalOperand implements Operand<RationalOperand> { ... }

I've written "factory" interface implemented by DoubleOperandFactory and RationalOperandFactory classes:

public interface OperandFactory { <T extends Operand<T>> Operand<T> valueOf(String s); } public class DoubleOperandFactory implements OperandFactory{ @Override public Operand<DoubleOperand> valueOf(String s) { ... } } public class RationalOperandFactory implements OperandFactory { @Override public Operand<RationalOperand> valueOf(String s) { ... } }

In my program I use an enum which objects store instance of the particular Factory:

public enum OperandType { DOUBLE(new DoubleOperandFactory()), RATIONAL(new RationalOperandFactory()); private OperandFactory fact; OperandType(OperandFactory fact){ this.fact = fact; } public OperandFactory getFact() { return fact; } }

Now I'm getting message warning "Unchecked overriding" on both factory classes, due to unchecked conversion and I'm pretty confused about this. First thing which I tried is (as it was most commonly answered here in similar topics) to replace generic method with generic factory interface, but finally it turns into impossibility to use them with the enum which should return particular factory, without <?>, as I have to create a List of operands (of generic type T extends Operand<T> for now) and fill it with the objects produced by selected factory. What would be the best way to reorganize this code?

NHibernate Caching Issue

21 hours 8 min ago

I think this is related to caching, but I could be wrong about that.

I have an object that has a list of sub-objects. Both A and B are mapped in NHibernate, but there is no association set up. I have a flow that goes something like

  1. Insert/Update A
  2. Insert/Update B
  3. In memory, change property B of Object A
  4. Grab a new copy of B from the DB (to do change tracking)
  5. Run comparisons, then save B back to the DB.

For months this code has worked on a production environment without issue. A refactoring window is coming up for me and I was planning on changing this to clean up so many round trips to the DB, but unfortunately, it started breaking out of the blue (I think it's a versioning thing but that's beside the pointright now.)

With that background in mind, I am having an issue where at step 4, the "fresh" copy of B I am getting from NHibernate actually contains the changes I have made in-memory only. After confirming at my DB that the object doesn't exist in the DB at that point, I am baffled as to what is happening. It appears somehow that NHiberante is caching references to objects it has changed and is returning those references instead of making another round trip. I have seen similar issues pointing out Session.Evict(type) which I expected to solve my problem, but it has not.

Has anyone noticed similar unwanted intelligent caching happening in NHibernate/have any idea a technique to selectively disable or clear that cache? Or am I crazy and is there no cache?

save data from an LCD KeyPad Shield to an sd card

21 hours 8 min ago

I'm developing a project that requires save datas from a sensor that is connected in a lcd keypad shield, the information should be save in a file into sd card.

My code

#include <LiquidCrystal.h> #include <SD.h> LiquidCrystal lcd(8, 9, 4, 5, 6, 7); int buttons; File myFile; //name of the file char nombrefichero[12]; int i = 1; int exist = LOW ; void setup() { Serial.begin(9600); //check the sd card adapter Serial.print("Iniciando SD ..."); if (!SD.begin(53)) { Serial.println("No se pudo inicializar"); return; } Serial.println("inicializacion exitosa"); } void loop() { // use the buttons of the lcd keypand shield in analog 0 buttons = analogRead(0); //button right if(buttons < 50){ count ++; nuevo(); } //button select if(buttons < 790){ capturar(); } } void capturar(){ myFile = SD.open(nombrefichero, FILE_WRITE);//abrimos el archivo if (myFile) { Serial.print("Escribiendo SD: "); int sensor1 = analogRead(0); int sensor2 = analogRead(1); int sensor3 = analogRead(2); myFile.print(millis()); myFile.print(","); myFile.print(sensor1); myFile.print(","); myFile.print(sensor2); myFile.print(","); myFile.println(sensor3); myFile.close(); //cerramos el archivo Serial.print("Tiempo(ms)="); Serial.print(millis()); Serial.print(",sensor1="); Serial.print(sensor1); Serial.print(",sensor2="); Serial.print(sensor2); Serial.print(",sensor3="); Serial.println(sensor3); } else { // if the file didn't open, print an error: Serial.println("Error al abrir el archivo"); } delay(1000); } void nuevo(){ while (exist == LOW) { sprintf(nombrefichero, "M%d.txt",i); //generate autoincrement number of file if(SD.exists(nombrefichero)) { i = i+1; myFile = SD.open(nombrefichero, FILE_WRITE); if (myFile) { Serial.println("Archivo nuevo, Escribiendo encabezado(fila 1)"); myFile.println("Tiempo(ms),Sensor1,Sensor2,Sensor3"); myFile.close(); } else { exist = HIGH; Serial.println("Error creando el archivo"); } } } }

I need capture the information of the sensor when I pressed the select button and when the right button is press create a new file

in this method, in this line if(SD.exists(nombrefichero)) if I put the ! before SD.exist the files are created infinite but if I leave it as is without the ! the button does nothing

void nuevo(){ while (exist == LOW) { sprintf(nombrefichero, "M%d.txt",i); if(SD.exists(nombrefichero)) { i = i+1; myFile = SD.open(nombrefichero, FILE_WRITE); if (myFile) { Serial.println("Archivo nuevo, Escribiendo encabezado(fila 1)"); myFile.println("Tiempo(ms),Sensor1,Sensor2,Sensor3"); myFile.close(); } else { exist = HIGH; Serial.println("Error creando el archivo"); } } } }

I'm use arduino mega 2560 and SD card Adapter

Angualr4 UI slows down with large array of objects

21 hours 8 min ago

Shown above is the table used to show the array of objects. Item count usuall exceeds 50~60. At which point elements in the interface like transition animations and click event take time.

I've noticed however if I filtered the items which returns 1 or 2 items the UI speeds up again.

What's the practical approach to normalize the response time of my UI + make sure all items are visible to the user.

My backend is Firebase using AngularFire.

service proxy expose with https

21 hours 8 min ago

I would like to expose existing REST service - service has a lot of methods so I want to expose this service just adding some additional filters to URLs.

Is there any known solution or the best is existing code that I can add my logic? Example: mine - service1 existing - service2 Client call:

https://service1.com/METH1

I call real service adding some filters:

https://service2.com/METH1/filter

And return entire response to client.

Best regards

What is the `>>>` operator in JavaScript?

21 hours 9 min ago

I was looking at the polyfill for Array.prototype.map:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

if (!Array.prototype.map) { Array.prototype.map = function(callback/*, thisArg*/) { var T, A, k; if (this == null) { throw new TypeError('this is null or not defined'); } // 1. Let O be the result of calling ToObject passing the |this| // value as the argument. var O = Object(this); // 2. Let lenValue be the result of calling the Get internal // method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // 4. If IsCallable(callback) is false, throw a TypeError exception. // See: http://es5.github.com/#x9.11 if (typeof callback !== 'function') { throw new TypeError(callback + ' is not a function'); } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. if (arguments.length > 1) { T = arguments[1]; } // 6. Let A be a new array created as if by the expression new Array(len) // where Array is the standard built-in constructor with that name and // len is the value of len. A = new Array(len); // 7. Let k be 0 k = 0; // 8. Repeat, while k < len while (k < len) { var kValue, mappedValue; // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the HasProperty internal // method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then if (k in O) { // i. Let kValue be the result of calling the Get internal // method of O with argument Pk. kValue = O[k]; // ii. Let mappedValue be the result of calling the Call internal // method of callback with T as the this value and argument // list containing kValue, k, and O. mappedValue = callback.call(T, kValue, k, O); // iii. Call the DefineOwnProperty internal method of A with arguments // Pk, Property Descriptor // { Value: mappedValue, // Writable: true, // Enumerable: true, // Configurable: true }, // and false. // In browsers that support Object.defineProperty, use the following: // Object.defineProperty(A, k, { // value: mappedValue, // writable: true, // enumerable: true, // configurable: true // }); // For best browser support, use the following: A[k] = mappedValue; } // d. Increase k by 1. k++; } // 9. return A return A; }; }

exception handling loop not working correctly

21 hours 9 min ago

Hi I am writing a program to play a game of battleships with an ai, at one point of the program I am placing the ships on a grid made from arrays with the values set to 'O' and when the ship is placed that changes to 'S' The code to set my first ship is as followed.

//SCANNER FOR USER INPUT TO PLACE FIRST SHIP Scanner sc = new Scanner(System.in); System.out.println(""); System.out.println("Please Choose the Co-ordinates of your first ship (4)"); System.out.println("X = "); int x = sc.nextInt(); System.out.println("Y = "); int y = sc.nextInt(); System.out.println("To place the ship upwards type 'true'."); System.out.println("To place the ship upwards type 'false'."); //END OF SCANNER //TAKES RESULTS FROM SCANNER AND FILLS THE GRID WITH 'S' ACCORDING TO PLAYER CO-ORDINATES int retry = 1; do { try { boolean updown = sc.nextBoolean(); if (updown == true) { grid[x + 1][y] = 'S'; grid[x + 2][y] = 'S'; grid[x + 3][y] = 'S'; grid[x + 4][y] = 'S'; drawGrid(grid); } else if (updown == false) { grid[x][y + 1] = 'S'; grid[x][y + 2] = 'S'; grid[x][y + 3] = 'S'; grid[x][y + 4] = 'S'; drawGrid(grid); } } catch (Exception e) { System.out.println("Incorrect input please try again!"); } } while (retry == 2);

If you try to run this code and type anything other than true or false the 'Incorrect Input please try again!' will run over and over I am unsure why it is not looping back around as retry should now be set to 2. Does anyone have any ideas where I am going wrong? Thanks in advance (I have a separate method to call the grid in my code incase anyone tries to run this and gets an error add the code below)

public static void drawGrid(char[][] grid) { for (int outerLoopValue = 0; outerLoopValue < 10; outerLoopValue++) { System.out.println(""); for (int innerLoopValue = 0; innerLoopValue < 10; innerLoopValue++) { System.out.print(grid[outerLoopValue][innerLoopValue] + " "); } } }

Dragging shapes from a palette onto a Konvajs stage

21 hours 11 min ago

On the Konvajs chat stream someone recently asked for an example of drag-and-drop from a palette onto an HTML5 canvas fronted by the Konvajs library. There were no ready examples and I was curious about how to achieve it.

I answered the question in a codepen but decided to post here for (my own) future reference. See my answer below.

GIt: renaming a directory deletes all files from git

21 hours 14 min ago

I use git for a project of mine. In one of the directory there are some files. Now I need to rename the directory. After I renamed the directory, git shows all my files are deleted. So it means I have to add those files again as new file in git. But I don't want to add all those files as new in git again. Is there any way, to rename the directory instead of adding the whole directory and files as new in git?

Note sure if I was able to express myself completely. If not, let me know.

How to speed up readLine and make it more effecient?

21 hours 24 min ago

This is taking an exceptionally long time to run. Is there any reason why that it is taking so long? I am writing a program which takes in that amount of money a person has and then calculates how much they will have after they gift some money to other people.

The entire problems can be found at the link below.

http://train.usaco.org/usacoprob2?a=RX1a1QYsOyX&S=gift1

BufferedReader f = new BufferedReader(new FileReader("gift1.in")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("gift1.out"))); int ppl = Integer.valueOf(f.readLine()); HashMap<String, Integer> name = new HashMap<String, Integer>(); String[] names = new String[ppl]; for(int i = 0; i < ppl-1; ++i ) { String n = f.readLine(); names[i] = n; name.put(n, 0); } for (int i = 0; i < ppl; i++) { String person = f.readLine(); //String[] mon = f.readLine().split("\\s"); int mon_lost = f.read(); int ppl_given = f.read(); name.put(person, mon_lost%ppl_given-mon_lost); for(int j =0; j< ppl_given; i++) { name.put(f.readLine(), mon_lost/ppl_given); } } for(int i = 0; i < ppl; i++) { System.out.println(names[i]+" "+ name.get(names[i])); System.out.println(f); } out.close();

How to record accuracy for every iteration during sess.run in Tensorflow?

21 hours 37 min ago

I am following the code https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/multilayer_perceptron.py here to build a multilayer perceptron to solve MNIST problem.

In the following code,

with tf.Session() as sess: sess.run(init) # Training cycle for epoch in range(training_epochs): avg_cost = 0. total_batch = int(mnist.train.num_examples/batch_size) # Loop over all batches for i in range(total_batch): batch_x, batch_y = mnist.train.next_batch(batch_size) # Run optimization op (backprop) and cost op (to get loss value) _, c = sess.run([train_op, loss_op], feed_dict={X: batch_x, Y: batch_y}) # Compute average loss avg_cost += c / total_batch # Display logs per epoch step if epoch % display_step == 0: print("Epoch:", '%04d' % (epoch+1), "cost={:.9f}".format(avg_cost)) print("Optimization Finished!")

I want to record the accuracy for each iteration. But how could I do that while using sess.run? Can I get the accuracy of every iteration in it?

Pages