问:
Linear regression with tensorflow
I trying to understand linear regression... here is script that I tried to understand:

```<code>'''
A linear regression learning algorithm example using TensorFlow library.
Author: Aymeric Damien
Project: https://github.com/aymericdamien/TensorFlow-Examples/
'''

from __future__ import print_function

import tensorflow as tf
from numpy import *
import numpy
import matplotlib.pyplot as plt
rng = numpy.random

# Parameters
learning_rate = 0.0001
training_epochs = 1000
display_step = 50

# Training Data
train_X = numpy.asarray([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,
                         7.042,10.791,5.313,7.997,5.654,9.27,3.1])
train_Y = numpy.asarray([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,
                         2.827,3.465,1.65,2.904,2.42,2.94,1.3])

train_X=numpy.asarray(train_X)
train_Y=numpy.asarray(train_Y)
n_samples = train_X.shape[0]

# tf Graph Input
X = tf.placeholder("float")
Y = tf.placeholder("float")

# Set model weights
W = tf.Variable(rng.randn(), name="weight")
b = tf.Variable(rng.randn(), name="bias")

# Construct a linear model
pred = tf.add(tf.multiply(X, W), b)

# Mean squared error
cost = tf.reduce_sum(tf.pow(pred-Y, 2))/(2*n_samples)
# Gradient descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

# Initializing the variables
init = tf.global_variables_initializer()

# Launch the graph
with tf.Session() as sess:
    sess.run(init)

    # Fit all training data
    for epoch in range(training_epochs):
        for (x, y) in zip(train_X, train_Y):
            sess.run(optimizer, feed_dict={X: x, Y: y})

        # Display logs per epoch step
        if (epoch+1) % display_step == 0:
            c = sess.run(cost, feed_dict={X: train_X, Y:train_Y})
            print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c), \
                "W=", sess.run(W), "b=", sess.run(b))

    print("Optimization Finished!")
    training_cost = sess.run(cost, feed_dict={X: train_X, Y: train_Y})
    print("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n')

    # Graphic display
    plt.plot(train_X, train_Y, 'ro', label='Original data')
    plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')
    plt.legend()
    plt.show()
</code>```

Question is what this part represent:

```<code># Set model weights
W = tf.Variable(rng.randn(), name="weight")
b = tf.Variable(rng.randn(), name="bias")
</code>```

And why are there random float numbers?

Also could you show me some math with formals represents cost, pred, optimizer variables?

答:
Variables allow us to add trainable parameters to a graph. They are constructed with a type and initial value:

```<code>W = tf.Variable([.3], tf.float32)
b = tf.Variable([-.3], tf.float32)
x = tf.placeholder(tf.float32)
linear_model = W * x + b
</code>```

The variable with type tf.Variable is the parameter which we will learn use TensorFlow. Assume you use the gradient descent to minimize the loss function. You need initial these parameter first. The rng.randn() is used to generate a random value for this purpose.

I think the Getting Started With TensorFlow is a good start point for you.

Title: Linear regression with tensorflow

Body:
I trying to understand linear regression... here is script that I tried to understand:

'''
A linear regression learning algorithm example using TensorFlow library.
Author: Aymeric Damien
Project: https://github.com/aymericdamien/TensorFlow-Examples/
'''

from __future__ import print_function

import tensorflow as tf
from numpy import *
import numpy
import matplotlib.pyplot as plt
rng = numpy.random

# Parameters
learning_rate = 0.0001
training_epochs = 1000
display_step = 50

# Training Data
train_X = numpy.asarray([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,
                         7.042,10.791,5.313,7.997,5.654,9.27,3.1])
train_Y = numpy.asarray([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,
                         2.827,3.465,1.65,2.904,2.42,2.94,1.3])

train_X=numpy.asarray(train_X)
train_Y=numpy.asarray(train_Y)
n_samples = train_X.shape[0]

# tf Graph Input
X = tf.placeholder("float")
Y = tf.placeholder("float")

# Set model weights
W = tf.Variable(rng.randn(), name="weight")
b = tf.Variable(rng.randn(), name="bias")

# Construct a linear model
pred = tf.add(tf.multiply(X, W), b)

# Mean squared error
cost = tf.reduce_sum(tf.pow(pred-Y, 2))/(2*n_samples)
# Gradient descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

# Initializing the variables
init = tf.global_variables_initializer()

# Launch the graph
with tf.Session() as sess:
    sess.run(init)

    # Fit all training data
    for epoch in range(training_epochs):
        for (x, y) in zip(train_X, train_Y):
            sess.run(optimizer, feed_dict={X: x, Y: y})

        # Display logs per epoch step
        if (epoch+1) % display_step == 0:
            c = sess.run(cost, feed_dict={X: train_X, Y:train_Y})
            print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c), \
                "W=", sess.run(W), "b=", sess.run(b))

    print("Optimization Finished!")
    training_cost = sess.run(cost, feed_dict={X: train_X, Y: train_Y})
    print("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n')

    # Graphic display
    plt.plot(train_X, train_Y, 'ro', label='Original data')
    plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')
    plt.legend()
    plt.show()

Question is what this part represent:

# Set model weights
W = tf.Variable(rng.randn(), name="weight")
b = tf.Variable(rng.randn(), name="bias")

And why are there random float numbers?

Also could you show me some math with formals represents cost, pred, optimizer variables?

Body:
Variables allow us to add trainable parameters to a graph. They are constructed with a type and initial value:

W = tf.Variable([.3], tf.float32)
b = tf.Variable([-.3], tf.float32)
x = tf.placeholder(tf.float32)
linear_model = W * x + b

The variable with type tf.Variable is the parameter which we will learn use TensorFlow. Assume you use the gradient descent to minimize the loss function. You need initial these parameter first. The rng.randn() is used to generate a random value for this purpose.

I think the Getting Started With TensorFlow is a good start point for you.


来源: stackexchange

问:
When does Java's Thread.sleep throw InterruptedException?
When does Java's Thread.sleep throw InterruptedException?  Is it safe to ignore it?  I am not doing any multithreading.  I just want to wait for a few seconds before retrying some operation.</p>

答: Methods like sleep() and wait() of class Thread might throw an InterruptedException. This will happen if some other thread wanted to interrupt the thread that is waiting or sleeping.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
How to automatically know the selected variable in stepAIC in R?
After running 'stepAIC', I have following result.

```<code> fit1=lm(y~ x1+x2+x3+x4+x5)
 fit2=stepAIC(fit1)
 coef=fit2$coefficients

 >coef
 >intercept, x1,  x3,  x5
       5      1,    3,   5
</code>```

I have another forecast vector z=(z1,...,z5). Because it's part of for loop, I want to compute the forecast y automatically using 'coef %*% z'.

I could think of two ways to make it happen:

1. make the unselected coefficients of stepAIC to be 0; so instead of

```<code>   coef=c(5,1,3,5)
</code>```

I have

```<code>   coef=c(5,1,0,3,0,5)
</code>```

find the selected coefficients and find the corresponding 'z_i'.

I have no idea how to implement this. Any help would be appreciated. Thanks in advance.

答:
step method / facility returns just another lm object, so you can apply any generic functions, including predict to it.

```<code>predict(fit2, newdata = a.data.frame)
</code>```

If the final aim is not prediction, but as your question title states, use attr(terms(fit2), 'term.labels').

Body:
After running 'stepAIC', I have following result.

 fit1=lm(y~ x1+x2+x3+x4+x5)
 fit2=stepAIC(fit1)
 coef=fit2$coefficients

 >coef
 >intercept, x1,  x3,  x5
       5      1,    3,   5

I have another forecast vector z=(z1,...,z5). Because it's part of for loop, I want to compute the forecast y automatically using 'coef %*% z'.

I could think of two ways to make it happen:

1. make the unselected coefficients of stepAIC to be 0; so instead of

   coef=c(5,1,3,5)

I have

   coef=c(5,1,0,3,0,5)

find the selected coefficients and find the corresponding 'z_i'.

I have no idea how to implement this. Any help would be appreciated. Thanks in advance.

Body:
step method / facility returns just another lm object, so you can apply any generic functions, including predict to it.

predict(fit2, newdata = a.data.frame)

If the final aim is not prediction, but as your question title states, use attr(terms(fit2), 'term.labels').


问:
Get all content from a folder with subfolder copied to another directory with bash
I have a directory that has many folders in it that have sub folders again and then there are some files. Can I write a bash script that copies all the files from the given directory into one single folder? So that I do not have to navigate through ever single folder and copy the content to another folder. </p>

答:
You could use find to list all files inside the folder:

```<code>find ./source -type f
</code>```

and then use the output as argument for cp, it would look like this:

```<code>cp $(find ./source -type f) destination
</code>```

There would be problem if there are some files within the original directory tree with conflicting name. In that case cp would refuse to copy additional files with the same name with error like:

cp: will not overwrite just-created destination/t22' with./source/test/t2/t22'

To make copies of files with same name, you can use backup option, like this:

```<code>cp --backup=numbered $(find ./source -type f) destination
</code>```

If you want to see what is happening use -v (verbose) option

```<code>cp -v --backup=numbered $(find ./source -type f) destination
</code>```

Body:
You could use find to list all files inside the folder:

find ./source -type f

and then use the output as argument for cp, it would look like this:

cp $(find ./source -type f) destination

There would be problem if there are some files within the original directory tree with conflicting name. In that case cp would refuse to copy additional files with the same name with error like:

cp: will not overwrite just-created destination/t22' with./source/test/t2/t22'

To make copies of files with same name, you can use backup option, like this:

cp --backup=numbered $(find ./source -type f) destination

If you want to see what is happening use -v (verbose) option

cp -v --backup=numbered $(find ./source -type f) destination


问:
Wix Project not available in VS 2017
I've installed WiX Toolset Visual Studio 2017 Extension but still cannot find the Wix in Other Project Types. Is there anything else I need to do?</p>

答: There's a VS 2017 update. Once installed Wix appeared.</p>

Title: Wix Project not available in VS 2017


问:
kotlin: Generic to different types
I need linear functions like this:

```<code>class Linear(val a : Double, val b : Double) {
    fun eval(in : Double) {
        return a*in + b
    }
}
</code>```

Then, I need the same thing for vectors.

```<code>class Vector3d(val a1 : Double, val a2 : Double, val a3 : Double) {
    // use operator overloading https://kotlinlang.org/docs/reference/operator-overloading.html to make +, -, /, *, etc. possible for vectors
}

class Linear(val a : Vector3d, val b : Vector3d) {
    fun eval(in : Vector3d) {
        return a*in + b
    }
}
</code>```

As you can see, the two Linear classes are identical (except for argument types). Now, I can not make the class generic, as Double and Vector3d do not have a common superclass.

If I want to write Linear just once, my only option is my own Double-type, which than has a common interface with Vector3d. However, this means I can not use 0 in the source code any longer, but I have to use MyDouble(0) everywhere. I could overload the constructor of Linear to accept Doubles, and create the MyDouble objects internally, however, I would need to do this for every single method in my API.

Is there a better solution?

答:
In fact, you technically can create a class using generics, but the class won't know how to multiplicate T with T, as it is a sub-class of Any, and Any doesn't support this operater. Through smart-casts you could evaluate, what kind of T is given:

```<code>class Linear<T>(val a: T, val b: T) {
    fun eval(c: T): Any {
        when {
            a is Double -> return a * c as Double + b as Double
            a is Double -> return a * c as Vector3d + b as Vector3d
            else -> return Unit
        }
}
</code>```

See generics on Kotlin-docs for more information.

I wouldn't consider this good practice, as the method doesn't have a clear (and type-save) return type and is very inflexible, but at least it provides type-safety for your arguments.

Another alternative would be to use Number (or Double) as a super-class for Vector3d and implement the methods as length. This also wouldn't be that much of a good practice, but at least you could use <Number> as generics.

Title: kotlin: Generic to different types

Body:
I need linear functions like this:

class Linear(val a : Double, val b : Double) {
    fun eval(in : Double) {
        return a*in + b
    }
}

Then, I need the same thing for vectors.

class Vector3d(val a1 : Double, val a2 : Double, val a3 : Double) {
    // use operator overloading https://kotlinlang.org/docs/reference/operator-overloading.html to make +, -, /, *, etc. possible for vectors
}

class Linear(val a : Vector3d, val b : Vector3d) {
    fun eval(in : Vector3d) {
        return a*in + b
    }
}

As you can see, the two Linear classes are identical (except for argument types). Now, I can not make the class generic, as Double and Vector3d do not have a common superclass.

If I want to write Linear just once, my only option is my own Double-type, which than has a common interface with Vector3d. However, this means I can not use 0 in the source code any longer, but I have to use MyDouble(0) everywhere. I could overload the constructor of Linear to accept Doubles, and create the MyDouble objects internally, however, I would need to do this for every single method in my API.

Is there a better solution?

Body:
In fact, you technically can create a class using generics, but the class won't know how to multiplicate T with T, as it is a sub-class of Any, and Any doesn't support this operater. Through smart-casts you could evaluate, what kind of T is given:

class Linear<T>(val a: T, val b: T) {
    fun eval(c: T): Any {
        when {
            a is Double -> return a * c as Double + b as Double
            a is Double -> return a * c as Vector3d + b as Vector3d
            else -> return Unit
        }
}

See generics on Kotlin-docs for more information.

I wouldn't consider this good practice, as the method doesn't have a clear (and type-save) return type and is very inflexible, but at least it provides type-safety for your arguments.

Another alternative would be to use Number (or Double) as a super-class for Vector3d and implement the methods as length. This also wouldn't be that much of a good practice, but at least you could use <Number> as generics.


问:
import matplotlib error on mac
Um... I wanted to import matplotlib in Python IDLE, but it said

```<code>>>> import matplotlib
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    import matplotlib
ModuleNotFoundError: No module named 'matplotlib'
</code>```

I've already tried pip thing and the conda thing in terminal.
It said

```<code># All requested packages already installed.
# packages in environment at /Users/Dan/anaconda:
</code>```

Then! what's the problem here?

答:
You may have installed Matplotlib to Python 2.7 and not Python 3.6. To install it to Python3 you need to use pip3:

```<code>pip3 install matplotlib
</code>```

Then open python3.6 from your terminal (not idle) and try importing matplotlib from there. This way you can use any text editor you wish, and run your code from the terminal.

Title: import matplotlib error on mac

Body:
Um... I wanted to import matplotlib in Python IDLE, but it said

>>> import matplotlib
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    import matplotlib
ModuleNotFoundError: No module named 'matplotlib'

I've already tried pip thing and the conda thing in terminal.
It said

# All requested packages already installed.
# packages in environment at /Users/Dan/anaconda:

Then! what's the problem here?

Body:
You may have installed Matplotlib to Python 2.7 and not Python 3.6. To install it to Python3 you need to use pip3:

pip3 install matplotlib

Then open python3.6 from your terminal (not idle) and try importing matplotlib from there. This way you can use any text editor you wish, and run your code from the terminal.


问:
issues with Java recursion
Let's say I have a data set of

```<code>Person    Friend
--------------------
FriendA   FriendB
FriendB   FriendC
</code>```

I want to traverse through the list and get the ultimate friend a file. I have tried this so far, it does not work, I get a stack overflow error when I try anything else.

```<code>public class Pair {

public String key;
public String value;

public Pair(String key, String value)
   {
      this.key = key;
      this.value = value;
   }
}

import java.io.*;
import java.util.*;

public class OpenFile
{

public static String checkFriend (String name, final ArrayList<Pair> pair)
{
    String new_friend_name = null;

    for (Pair p : pair)
    {
        if (p.key == name)
        {
            new_friend_name = (String) p.value;
        }
    }

    return new_friend_name;
}

public static String getUltimateFriend(String name, final ArrayList<Pair> pair)
{
    String friend = null;

    if (checkFriend(name, pair) == null) return name;
    while (checkFriend(name, pair) != null)
    {
        friend = checkFriend(name, pair);
    }

    return friend;
    //return new_friend_name;
}

public static void main(String[] args) throws Exception
{
    FileReader fr = new FileReader("C:\\Users\\Files\\Desktop\\Java Programs\\data\\data.txt");
    BufferedReader br = new BufferedReader(fr);

    String line = br.readLine();
    String[] var = null;
    ArrayList<Pair> pair = new ArrayList<Pair>();

    System.out.println("my pair output from a loop");
    for (Pair p : pair)
    {
        System.out.println(p.key + " is friends with " + getUltimateFriend(p.key,pair));
    }

    br.close();
    fr.close();

}
</code>```

}

I tried recursion, but I am getting StackOverflow error.

Any help would be appreciated.

答:
You don't use recursion because nowhere does a method call itself.
I guess your problem is in your loop:

```<code>while (checkFriend(name, pair) != null)
{
    friend = checkFriend(name, pair);
}
</code>```

Here you are doing the same thing endlessly.

Title: issues with Java recursion

Body:
Let's say I have a data set of

Person    Friend
--------------------
FriendA   FriendB
FriendB   FriendC

I want to traverse through the list and get the ultimate friend a file. I have tried this so far, it does not work, I get a stack overflow error when I try anything else.

public class Pair {

public String key;
public String value;

public Pair(String key, String value)
   {
      this.key = key;
      this.value = value;
   }
}

import java.io.*;
import java.util.*;

public class OpenFile
{

public static String checkFriend (String name, final ArrayList<Pair> pair)
{
    String new_friend_name = null;

    for (Pair p : pair)
    {
        if (p.key == name)
        {
            new_friend_name = (String) p.value;
        }
    }

    return new_friend_name;
}

public static String getUltimateFriend(String name, final ArrayList<Pair> pair)
{
    String friend = null;

    if (checkFriend(name, pair) == null) return name;
    while (checkFriend(name, pair) != null)
    {
        friend = checkFriend(name, pair);
    }

    return friend;
    //return new_friend_name;
}

public static void main(String[] args) throws Exception
{
    FileReader fr = new FileReader("C:\\Users\\Files\\Desktop\\Java Programs\\data\\data.txt");
    BufferedReader br = new BufferedReader(fr);

    String line = br.readLine();
    String[] var = null;
    ArrayList<Pair> pair = new ArrayList<Pair>();

    System.out.println("my pair output from a loop");
    for (Pair p : pair)
    {
        System.out.println(p.key + " is friends with " + getUltimateFriend(p.key,pair));
    }

    br.close();
    fr.close();

}

}

I tried recursion, but I am getting StackOverflow error.

Any help would be appreciated.

Body:
You don't use recursion because nowhere does a method call itself.
I guess your problem is in your loop:

while (checkFriend(name, pair) != null)
{
    friend = checkFriend(name, pair);
}

Here you are doing the same thing endlessly.


问:
Avoiding the rounding of double numbers
I'm trying to write a function that calculates the regression line from a data sheet with the least squares methode, but I encountered some serious problem with my code.

My first issue is that I don't know why my "linear regression" function is rounding the result of the iterations, even when I'm trying to use other "bigger" types.

My second issue is that the last part of my code is giving me the wrong results for the y intercept (b) and the slope (a), and I think that it could be a problem of conversion but I'm not really sure. If it is the case what should I do to avoid it?

```<code>void RegLin (const vector<double>& valuesX, const vector<double>& valuesY, vector<double>& PenOrd) {

unsigned int N=valuesX.size();

long double SomXi{0};
    for (unsigned i=0; i<N; ++i){
    SomXi+=valuesX.at(i);
    }

long double SomXiXi{0};
    for (unsigned i=0; i<N; ++i){              //Here is a problem (number rounded) Expected value: 937352,25 / Given value: 937352
    SomXiXi+=(valuesX.at(i))*(valuesX.at(i));
    }

long double SomYi{0};
    for (unsigned i=0; i<N; ++i){
    SomYi+=valuesY.at(i);
    }

long double SomXiYi{0};
    for (unsigned i=0; i<N; ++i){              //Here is the same problem Excepted value: 334107,41 / Given value: 334107
    SomXiYi+=(valuesX.at(i))*(valuesY.at(i));
    }

long double a=(SomYi*SomXiXi-SomXi*SomXiYi)/(N*SomXiXi-pow(SomXi,2)); //Bad result

long double b=(N*SomXiYi-SomYi*SomXi)/(N*SomXiXi-pow(SomXi,2)); //Bad result

PenOrd.push_back(a);
PenOrd.push_back(b);

return;
}
</code>```

Thank you in advance for your support

P.S: I'm using g++ and the 2011 C++ standard.

答:
It's entirerly possible that you are given error due to 2 possibilites:

1) long double == double on your compiler and you are getting wrong results

2) floating point arithmetic does not represent values with 100% accuracy and therefore '0.10 != 0.10 written as float/double

Depending on what kind of calculations you are doing, I would adivse you to increase values by a few power OR change the data to float and store values in double.

Title: Avoiding the rounding of double numbers

Body:
I'm trying to write a function that calculates the regression line from a data sheet with the least squares methode, but I encountered some serious problem with my code.

My first issue is that I don't know why my "linear regression" function is rounding the result of the iterations, even when I'm trying to use other "bigger" types.

My second issue is that the last part of my code is giving me the wrong results for the y intercept (b) and the slope (a), and I think that it could be a problem of conversion but I'm not really sure. If it is the case what should I do to avoid it?

void RegLin (const vector<double>& valuesX, const vector<double>& valuesY, vector<double>& PenOrd) {

unsigned int N=valuesX.size();

long double SomXi{0};
    for (unsigned i=0; i<N; ++i){
    SomXi+=valuesX.at(i);
    }

long double SomXiXi{0};
    for (unsigned i=0; i<N; ++i){              //Here is a problem (number rounded) Expected value: 937352,25 / Given value: 937352
    SomXiXi+=(valuesX.at(i))*(valuesX.at(i));
    }

long double SomYi{0};
    for (unsigned i=0; i<N; ++i){
    SomYi+=valuesY.at(i);
    }

long double SomXiYi{0};
    for (unsigned i=0; i<N; ++i){              //Here is the same problem Excepted value: 334107,41 / Given value: 334107
    SomXiYi+=(valuesX.at(i))*(valuesY.at(i));
    }

long double a=(SomYi*SomXiXi-SomXi*SomXiYi)/(N*SomXiXi-pow(SomXi,2)); //Bad result

long double b=(N*SomXiYi-SomYi*SomXi)/(N*SomXiXi-pow(SomXi,2)); //Bad result

PenOrd.push_back(a);
PenOrd.push_back(b);

return;
}

Thank you in advance for your support

P.S: I'm using g++ and the 2011 C++ standard.


问:
How to validate whether opened correct activity - Espresso
I created android UI test with espresso and done Button click and opening an Activity. Now I want to validate whether opened correct activity or not.</p>

答:
Use espresso-intents to validate that.

The usage is:

intended(hasComponent(NewActivity.class.getName()));

You can read this thread for more details on that:
Espresso - check which Activity is opened using intent on button press?


问:
php how to store monday to friday of the next 6 months begin from tomorrow in an array
I am making a page to let the clients choose a date for an appointment, so I need to build a list of the dates like this :

always begin from tomorrow, end by 6 months

always from Mondy to Saturday, no Sunday

the day of the week need to be in chinese, like "Monday" is "星期一", but the timezone is in France

Here is the php

```<code>date_default_timezone_set('Europe/Paris');

$tomorrow = date("Y年m月d日 l", time() + 86400);
$end = date("Y年m月d日 l", time() + 86400 * 7); // just 7 days for a try
$interval = new DateInterval('P1D');

$daterange = new DatePeriod($tomorrow, $interval, $end);

foreach ($daterange as $date) {
    echo $date . '<br/>';
}
</code>```

This code is not working.
I need to build an array, which store all the dates of next 6 months, begin from tomorrow, without Sunday, the days need to be in chinese and the timezone needs to be in Europe, is that possible?

答:
I think strtotime and array_push is what you are looking for. Try this:

```<code>$curDate = date('Y-m-d', strtotime('+1 day'));
$endDate = date('Y-m-d', strtotime('+6 months +1 day'));

$myArr = array();
while ($endDate >= $curDate) {
    if (date('w', strtotime($curDate)) !== '0') array_push($myArr, $curDate);
    $curDate = date('Y-m-d', strtotime($curDate . " +1 days"));
}

var_dump($myArr);
</code>```

For the Options, create an array from sunday to saturday.

```<code>$weekdays = array('Sunday', ..., 'Saturday');
echo date('Y/m/d', strtotime($curDate)) . ' ' . $weekdays[date('w', strtotime($curDate))];
</code>```

Body:
I am making a page to let the clients choose a date for an appointment, so I need to build a list of the dates like this :

always begin from tomorrow, end by 6 months

always from Mondy to Saturday, no Sunday

the day of the week need to be in chinese, like "Monday" is "星期一", but the timezone is in France

Here is the php

date_default_timezone_set('Europe/Paris');

$tomorrow = date("Y年m月d日 l", time() + 86400);
$end = date("Y年m月d日 l", time() + 86400 * 7); // just 7 days for a try
$interval = new DateInterval('P1D');

$daterange = new DatePeriod($tomorrow, $interval, $end);

foreach ($daterange as $date) {
    echo $date . '
';
}

This code is not working.
I need to build an array, which store all the dates of next 6 months, begin from tomorrow, without Sunday, the days need to be in chinese and the timezone needs to be in Europe, is that possible?

Body:
I think strtotime and array_push is what you are looking for. Try this:

$curDate = date('Y-m-d', strtotime('+1 day'));
$endDate = date('Y-m-d', strtotime('+6 months +1 day'));

$myArr = array();
while ($endDate >= $curDate) {
    if (date('w', strtotime($curDate)) !== '0') array_push($myArr, $curDate);
    $curDate = date('Y-m-d', strtotime($curDate . " +1 days"));
}

var_dump($myArr);

For the Options, create an array from sunday to saturday.

$weekdays = array('Sunday', ..., 'Saturday');
echo date('Y/m/d', strtotime($curDate)) . ' ' . $weekdays[date('w', strtotime($curDate))];


问:
Combine two classes in Java?
I don't know what the right way to ask this but I have two classes I get back from the API that both have name as the thing in common but also have another field that is separate from each other. What is the best way to "combine" them where my User class can get the name but can also get their own variables.

How would my User class look? I'm looking for the User class to have name in-common, the Alien class have alienVariable and the Human class have the humanVariable

My example of two classes

Alien

```<code>@AutoValue
public abstract class Alien implements Parcelable {
    public static Alien create(String alienVariable) {
        return new AutoValue_Alien(alienVariable);
    }

    public static Alien create(String name, String alienVariable) {
        return new AutoValue_Alien(name, alienVariable);
    }

    public static TypeAdapter<Alien> typeAdapter(Gson gson) {
        return new AutoValue_Alien.GsonTypeAdapter(gson);
    }

    @SerializedName("name")
    public abstract String name();

    @Nullable
    @SerializedName("alien_variable")
    public abstract String alienVariable();
}
</code>```

Human

```<code>@AutoValue
public abstract class Human implements Parcelable {
    public static Human create(String humanVariable) {
        return new AutoValue_Human(humanVariable);
    }

    public static Human create(String name, String humanVariable) {
        return new AutoValue_Human(name, humanVariable);
    }

    public static TypeAdapter<Human> typeAdapter(Gson gson) {
        return new AutoValue_Human.GsonTypeAdapter(gson);
    }

    @SerializedName("name")
    public abstract String name();

    @Nullable
    @SerializedName("human_variable")
    public abstract String humanVariable();
}
</code>```

User?

答:
What I was looking for was what Vahid suggested. I didn't want inheritance but polymorphism. (should've specified)

Just made an interface class that looks like this.

```<code>public interface Species {
    String name();
}
</code>```

And then just override it in each class, example for the Human class

```<code>@AutoValue
public abstract class Human implements Parcelable, Species {
    public static Human create(String humanVariable) {
        return new AutoValue_Human(humanVariable);
    }

    public static Human create(String name, String humanVariable) {
        return new AutoValue_Human(name, humanVariable);
    }

    public static TypeAdapter<Human> typeAdapter(Gson gson) {
        return new AutoValue_Human.GsonTypeAdapter(gson);
    }

    @SerializedName("name")
    public abstract String name();

    @Nullable
    @SerializedName("human_variable")
    public abstract String humanVariable();

    @Override
    public String name() {
       return name();
    }
}
</code>```

Title: Combine two classes in Java?

Body:
I don't know what the right way to ask this but I have two classes I get back from the API that both have name as the thing in common but also have another field that is separate from each other. What is the best way to "combine" them where my User class can get the name but can also get their own variables.

How would my User class look? I'm looking for the User class to have name in-common, the Alien class have alienVariable and the Human class have the humanVariable

My example of two classes

Alien

@AutoValue
public abstract class Alien implements Parcelable {
    public static Alien create(String alienVariable) {
        return new AutoValue_Alien(alienVariable);
    }

    public static Alien create(String name, String alienVariable) {
        return new AutoValue_Alien(name, alienVariable);
    }

    public static TypeAdapter<Alien> typeAdapter(Gson gson) {
        return new AutoValue_Alien.GsonTypeAdapter(gson);
    }

    @SerializedName("name")
    public abstract String name();

    @Nullable
    @SerializedName("alien_variable")
    public abstract String alienVariable();
}

Human

@AutoValue
public abstract class Human implements Parcelable {
    public static Human create(String humanVariable) {
        return new AutoValue_Human(humanVariable);
    }

    public static Human create(String name, String humanVariable) {
        return new AutoValue_Human(name, humanVariable);
    }

    public static TypeAdapter<Human> typeAdapter(Gson gson) {
        return new AutoValue_Human.GsonTypeAdapter(gson);
    }

    @SerializedName("name")
    public abstract String name();

    @Nullable
    @SerializedName("human_variable")
    public abstract String humanVariable();
}

User?

Body:
What I was looking for was what Vahid suggested. I didn't want inheritance but polymorphism. (should've specified)

Just made an interface class that looks like this.

public interface Species {
    String name();
}

And then just override it in each class, example for the Human class

@AutoValue
public abstract class Human implements Parcelable, Species {
    public static Human create(String humanVariable) {
        return new AutoValue_Human(humanVariable);
    }

    public static Human create(String name, String humanVariable) {
        return new AutoValue_Human(name, humanVariable);
    }

    public static TypeAdapter<Human> typeAdapter(Gson gson) {
        return new AutoValue_Human.GsonTypeAdapter(gson);
    }

    @SerializedName("name")
    public abstract String name();

    @Nullable
    @SerializedName("human_variable")
    public abstract String humanVariable();

    @Override
    public String name() {
       return name();
    }
}


问:
html2canvas not work in ie9
I want to convert div to canvas and in chrome it works good but in IE9 it convert it but not good- its cut the div content and change the order of div elements.

witch js should i download that work well in IE9 too?
Someone have any idea how can I resolve this resolution problem?
my js code:

```<code> $scope.canvastoimage = function () {
        html2canvas($("#mytryapp"), {
           proxy: "server.js",
            useCORS: true,
            onrendered: function(canvas) {
                document.body.appendChild(canvas);
                 $("#img-out").append(canvas);
                $("#mytryapp").hide();
                printthispage();

       }
        });
    }
</code>```

The result is attached:

Thanks!

答:
This code works well in all browsers </p>

```<code>html2canvas([document.getElementById(mytryapp)], {
 onrendered: function (canvas) {
   var imageData = canvas.toDataURL('image/png',1.0);
   document.getElementById('img-out')[0].innerHTML = imageData;
 }
});
</code>```

<p>Test it and see how it goes. The index 0 is used with jQuery objects to get "real" document element so if you are not using jquery change to this: </p>

```<code>html2canvas([document.getElementById(mytryapp)], {
     onrendered: function (canvas) {
       var imageData = canvas.toDataURL('image/png',1.0);
       document.getElementById('img-out').innerHTML = imageData;
     }
    });
</code>```

Title: html2canvas not work in ie9

Body:
I want to convert div to canvas and in chrome it works good but in IE9 it convert it but not good- its cut the div content and change the order of div elements.

witch js should i download that work well in IE9 too?
Someone have any idea how can I resolve this resolution problem?
my js code:

 $scope.canvastoimage = function () {
        html2canvas($("#mytryapp"), {
           proxy: "server.js",
            useCORS: true,
            onrendered: function(canvas) {
                document.body.appendChild(canvas);
                 $("#img-out").append(canvas);
                $("#mytryapp").hide();
                printthispage();

       }
        });
    }

The result is attached:

Thanks!

Body:
This code works well in all browsers

html2canvas([document.getElementById(mytryapp)], {
 onrendered: function (canvas) {
   var imageData = canvas.toDataURL('image/png',1.0);
   document.getElementById('img-out')[0].innerHTML = imageData;
 }
});

Test it and see how it goes. The index 0 is used with jQuery objects to get "real" document element so if you are not using jquery change to this:

html2canvas([document.getElementById(mytryapp)], {
     onrendered: function (canvas) {
       var imageData = canvas.toDataURL('image/png',1.0);
       document.getElementById('img-out').innerHTML = imageData;
     }
    });


问:
Join lines automatically using autohotkey
Long paragraphs in Adobe Acrobat results in a line break when text is copied to clipboard and pasted in Word.

To deal with this, I manually paste the copied-text in Notepad ++ > select all > ctrl+J (join lines) > select all > Copy...... and then paste it into my Word document.

I would like to automate this join line using autohotkey as I have a large body of documents to go through. I can't seem to find any examples online in dealing with this directly within autohotkey script.

Ex.

```<code>Data structures with labeled axes supporting automatic or explicit data alignment.
This prevents common errors resulting from misaligned data and working with
differently-indexed data coming from different sources.
</code>```

After manually joining in Notepad ++

```<code>Data structures with labeled axes supporting automatic or explicit data alignment. This prevents common errors resulting from misaligned data and working with differently-indexed data coming from different sources.
</code>```

答:
Try this:

```<code>#Persistent
return

    OnClipboardChange:
If WinActive("ahk_exe AcroRd32.exe")
{
    clipboard =
    Send, {Ctrl down}c{Ctrl up}{Esc}
        ClipWait
    clip := RegExReplace(clipboard, "(\S.*?)\R(.*?\S)", "$1 $2") ; strip line breaks and replace them with spaces
    clipboard = %clip%
    StringReplace clipboard, clipboard, % "  ", % " ", A         ; replace double spaces with single spaces
        ClipWait
    ControlClick, x0 y0, A
}
return
</code>```

EDIT

Or this:

```<code>#Persistent
return

    OnClipboardChange:
If WinActive("ahk_class AcrobatSDIWindow")
{
    clipboard := ""
    Send, {Ctrl down}c{Ctrl up}{Esc}
        ClipWait
    clip := RegExReplace(clipboard, "(\S.*?)\R(.*?\S)", "$1 $2") ; strip line breaks and replace them with spaces
    StringReplace clip, clip, % "  ", % " ", A         ; replace double spaces with single spaces
    clipboard := ""
    clipboard = %clip%
    ClipWait 2
    If !(ErrorLevel)
    {
        ToolTip, lines joined
        Sleep 500
        ToolTip
    }
}
return
</code>```

Body:
Long paragraphs in Adobe Acrobat results in a line break when text is copied to clipboard and pasted in Word.

To deal with this, I manually paste the copied-text in Notepad ++ > select all > ctrl+J (join lines) > select all > Copy...... and then paste it into my Word document.

I would like to automate this join line using autohotkey as I have a large body of documents to go through. I can't seem to find any examples online in dealing with this directly within autohotkey script.

Ex.

Data structures with labeled axes supporting automatic or explicit data alignment.
This prevents common errors resulting from misaligned data and working with
differently-indexed data coming from different sources.

After manually joining in Notepad ++

Data structures with labeled axes supporting automatic or explicit data alignment. This prevents common errors resulting from misaligned data and working with differently-indexed data coming from different sources.

Body:
Try this:

#Persistent
return

    OnClipboardChange:
If WinActive("ahk_exe AcroRd32.exe")
{
    clipboard =
    Send, {Ctrl down}c{Ctrl up}{Esc}
        ClipWait
    clip := RegExReplace(clipboard, "(\S.*?)\R(.*?\S)", "$1 $2") ; strip line breaks and replace them with spaces
    clipboard = %clip%
    StringReplace clipboard, clipboard, % "  ", % " ", A         ; replace double spaces with single spaces
        ClipWait
    ControlClick, x0 y0, A
}
return

EDIT

Or this:

#Persistent
return

    OnClipboardChange:
If WinActive("ahk_class AcrobatSDIWindow")
{
    clipboard := ""
    Send, {Ctrl down}c{Ctrl up}{Esc}
        ClipWait
    clip := RegExReplace(clipboard, "(\S.*?)\R(.*?\S)", "$1 $2") ; strip line breaks and replace them with spaces
    StringReplace clip, clip, % "  ", % " ", A         ; replace double spaces with single spaces
    clipboard := ""
    clipboard = %clip%
    ClipWait 2
    If !(ErrorLevel)
    {
        ToolTip, lines joined
        Sleep 500
        ToolTip
    }
}
return


问:
Do I need to use a shader for OpenGL 3.3 Core?
I am trying to make a triangle and I'm using GLEW, GLFW and GLM as extensions of OpenGL.

Here's the code I have:

```<code>#include <stdlib.h>
#include <stdio.h>
#include <gl\glew.h>
#include <GLFW\glfw3.h>
#include <glm\glm.hpp>
using namespace glm;

int main()
{
    if (!glfwInit())
    {
        fprintf(stderr, "Failed to initialize GLFW\n");
        return -1;
    }
    glfwWindowHint(GLFW_SAMPLES, 4); // 4x antialiasing
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // We want OpenGL 3.3
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //We don't want the old OpenGL

    // Open a window and create its OpenGL context
    GLFWwindow* window; // (In the accompanying source code, this variable is global)
    window = glfwCreateWindow(1024, 768, "Tutorial 01", NULL, NULL);
    if (window == NULL)
    {
        fprintf(stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n");
        glfwTerminate();
        return -1;
    }

    glfwMakeContextCurrent(window); // Initialize GLEW
    glewExperimental = true; // Needed in core profile
    if (glewInit() != GLEW_OK)
    {
        fprintf(stderr, "Failed to initialize GLEW\n");
        return -1;
    }
    // Ensure we can capture the escape key being pressed below
    glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);

    GLuint VertexArrayID;
    glGenVertexArrays(1, &VertexArrayID);
    glBindVertexArray(VertexArrayID);

    // An array of 3 vectors which represents 3 vertices
    static const GLfloat g_vertex_buffer_data[] = {
        -1.0f, -1.0f, 0.0f,
        1.0f, -1.0f, 0.0f,
        0.0f,  1.0f, 0.0f,
    };

    // This will identify our vertex buffer
    GLuint vertexbuffer;
    // Generate 1 buffer, put the resulting identifier in vertexbuffer
    glGenBuffers(1, &vertexbuffer);
    // The following commands will talk about our 'vertexbuffer' buffer
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    // Give our vertices to OpenGL.
    glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);

    do {
        // 1rst attribute buffer : vertices
        glEnableVertexAttribArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
        glVertexAttribPointer(
            0,                  // attribute 0. No particular reason for 0, but must match the layout in the shader.
            3,                  // size
            GL_FLOAT,           // type
            GL_FALSE,           // normalized?
            0,                  // stride
            (void*)0            // array buffer offset
        );
        // Draw the triangle !
        glDrawArrays(GL_TRIANGLES, 0, 3); // Starting from vertex 0; 3 vertices total -> 1 triangle
        glDisableVertexAttribArray(0);

        // Swap buffers
        glfwSwapBuffers(window);
        glfwPollEvents();

    } // Check if the ESC key was pressed or the window was closed
    while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS &&
        glfwWindowShouldClose(window) == 0);
}
</code>```

Edit

The code is not displaying the white triangle its just opens the window and shows empty black.
Also at first I added the code I messed around with, which is missing part of the code. However it still does not produce the white triangle.

答:
Do I need to use a shader for OpenGL 3.3?

You need to use a shader or you won't see anything. If you do see something then that is unspecified behavior. Which highly depend on each individual driver.

You could try fiddling with the clear color and clear the screen:

```<code>glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
</code>```

The tutorial was able to get a white triangle on a black background. On my computer the opposite was the case.

The tutorial also points out:

If you’re on lucky, you can see the result (don’t panic if you don’t)

So read the rest of the tutorial, it also includes a shader.

Body:
I am trying to make a triangle and I'm using GLEW, GLFW and GLM as extensions of OpenGL.

Here's the code I have:

#include <stdlib.h>
#include <stdio.h>
#include <gl\glew.h>
#include <GLFW\glfw3.h>
#include <glm\glm.hpp>
using namespace glm;

int main()
{
    if (!glfwInit())
    {
        fprintf(stderr, "Failed to initialize GLFW\n");
        return -1;
    }
    glfwWindowHint(GLFW_SAMPLES, 4); // 4x antialiasing
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // We want OpenGL 3.3
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //We don't want the old OpenGL

    // Open a window and create its OpenGL context
    GLFWwindow* window; // (In the accompanying source code, this variable is global)
    window = glfwCreateWindow(1024, 768, "Tutorial 01", NULL, NULL);
    if (window == NULL)
    {
        fprintf(stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n");
        glfwTerminate();
        return -1;
    }

    glfwMakeContextCurrent(window); // Initialize GLEW
    glewExperimental = true; // Needed in core profile
    if (glewInit() != GLEW_OK)
    {
        fprintf(stderr, "Failed to initialize GLEW\n");
        return -1;
    }
    // Ensure we can capture the escape key being pressed below
    glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);

    GLuint VertexArrayID;
    glGenVertexArrays(1, &VertexArrayID);
    glBindVertexArray(VertexArrayID);

    // An array of 3 vectors which represents 3 vertices
    static const GLfloat g_vertex_buffer_data[] = {
        -1.0f, -1.0f, 0.0f,
        1.0f, -1.0f, 0.0f,
        0.0f,  1.0f, 0.0f,
    };

    // This will identify our vertex buffer
    GLuint vertexbuffer;
    // Generate 1 buffer, put the resulting identifier in vertexbuffer
    glGenBuffers(1, &vertexbuffer);
    // The following commands will talk about our 'vertexbuffer' buffer
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    // Give our vertices to OpenGL.
    glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);

    do {
        // 1rst attribute buffer : vertices
        glEnableVertexAttribArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
        glVertexAttribPointer(
            0,                  // attribute 0. No particular reason for 0, but must match the layout in the shader.
            3,                  // size
            GL_FLOAT,           // type
            GL_FALSE,           // normalized?
            0,                  // stride
            (void*)0            // array buffer offset
        );
        // Draw the triangle !
        glDrawArrays(GL_TRIANGLES, 0, 3); // Starting from vertex 0; 3 vertices total -> 1 triangle
        glDisableVertexAttribArray(0);

        // Swap buffers
        glfwSwapBuffers(window);
        glfwPollEvents();

    } // Check if the ESC key was pressed or the window was closed
    while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS &&
        glfwWindowShouldClose(window) == 0);
}

Edit

The code is not displaying the white triangle its just opens the window and shows empty black.
Also at first I added the code I messed around with, which is missing part of the code. However it still does not produce the white triangle.

Body:
Do I need to use a shader for OpenGL 3.3?

You need to use a shader or you won't see anything. If you do see something then that is unspecified behavior. Which highly depend on each individual driver.

You could try fiddling with the clear color and clear the screen:

glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);

The tutorial was able to get a white triangle on a black background. On my computer the opposite was the case.

The tutorial also points out:

If you’re on lucky, you can see the result (don’t panic if you don’t)

So read the rest of the tutorial, it also includes a shader.


问:
C++ shared_ptr return this from derived method
I have been using this:

```<code>struct Bar;

struct Foo
{
   virtual Bar * GetBar() { return nullptr; }
}

struct Bar : public Foo
{
   virtual Bar * GetBar() { return this; }
}

Foo * b = new Bar();
//...
b->GetBar();
</code>```

I used this instead of slow dynamic_cast. Now I have changed my code to use std::shared_ptr

```<code>std::shared_ptr<Foo> b = std::shared_ptr<Bar>(new Bar());
</code>```

How can I change GetBar method to return std::shared_ptr and get the same functionality as with raw pointers (no need for dynamic_cast) ?

I have tried this:

```<code> struct Foo : public std::enable_shared_from_this<Foo>
 {
     virtual std::shared_ptr<Bar> GetBar() { return nullptr; }
 }

struct Bar : public Foo
{
    virtual std::shared_ptr<Bar> GetBar() { return shared_from_this(); }
}
</code>```

But it wont compile

答:
std::enable_shared_from_this<Foo>::shared_from_this() returns a shared_ptr<Foo>. So you need an explicit pointer downcast.

```<code>virtual std::shared_ptr<Bar> GetBar() {
    return std::static_pointer_cast<Bar>(shared_from_this());
}
</code>```

Body:
I have been using this:

struct Bar;

struct Foo
{
   virtual Bar * GetBar() { return nullptr; }
}

struct Bar : public Foo
{
   virtual Bar * GetBar() { return this; }
}

Foo * b = new Bar();
//...
b->GetBar();

I used this instead of slow dynamic_cast. Now I have changed my code to use std::shared_ptr

std::shared_ptr<Foo> b = std::shared_ptr<Bar>(new Bar());

How can I change GetBar method to return std::shared_ptr and get the same functionality as with raw pointers (no need for dynamic_cast) ?

I have tried this:

 struct Foo : public std::enable_shared_from_this<Foo>
 {
     virtual std::shared_ptr<Bar> GetBar() { return nullptr; }
 }

struct Bar : public Foo
{
    virtual std::shared_ptr<Bar> GetBar() { return shared_from_this(); }
}

But it wont compile

Body:
std::enable_shared_from_this<Foo>::shared_from_this() returns a shared_ptr<Foo>. So you need an explicit pointer downcast.

virtual std::shared_ptr<Bar> GetBar() {
    return std::static_pointer_cast<Bar>(shared_from_this());
}


问:
Copy conditional formatting based on cell content to other rows
I have a sheet which contains all usernames and email addresses of my database

In another sheet i have a column saying "username", in here I want to enter usernames, if a username entered here is already in the list on the other sheet the field content should change color to red.

I figured out how to do conditional formatting on the cell, so I made this formula:

```<code>=COUNTIF('Usernames and emails'!A5:A1450;$A$7)>0
</code>```

This formula works great for the cell in A7.

However when I drag A7 all the way to the bottom of my table, the conditional formatting formula is not copied. When i for example type in the same username in A8 as i did in A7, the A7 field would turn red but A8 would remain unchanged.

I need this formatting on about 1000+ fields, so making a rule for every single one of them cannot be the solution?

Example:

Worksheet : Usernames and emails:

```<code>test1
test2
test3
</code>```

Worksheet : i have to enter usernames in every row in the A column, so i enter them like this:

```<code>A1 : test
A2 : test1
A3 : test4
A4 : test3
</code>```

in this example, A2 and A4 should be colored in red since they have a value that corresponds to a value in my "usernames and emails" worksheet list

答:
Select the range you want to apply the conditional formatting to. In this case it seems to be A7:A1007. A7 should be the 'active cell'.

Use this formula to create the Conditional Formatting Rule:

      =countif('Usernames and emails'!$A$5:$A$1450; $A7)

  Note $A$5:$A$1450 instead of A5:A1450 and $A7 instead of $A$7.

Body:
I have a sheet which contains all usernames and email addresses of my database

In another sheet i have a column saying "username", in here I want to enter usernames, if a username entered here is already in the list on the other sheet the field content should change color to red.

I figured out how to do conditional formatting on the cell, so I made this formula:

=COUNTIF('Usernames and emails'!A5:A1450;$A$7)>0

This formula works great for the cell in A7.

However when I drag A7 all the way to the bottom of my table, the conditional formatting formula is not copied. When i for example type in the same username in A8 as i did in A7, the A7 field would turn red but A8 would remain unchanged.

I need this formatting on about 1000+ fields, so making a rule for every single one of them cannot be the solution?

Example:

Worksheet : Usernames and emails:

test1
test2
test3

Worksheet : i have to enter usernames in every row in the A column, so i enter them like this:

A1 : test
A2 : test1
A3 : test4
A4 : test3

in this example, A2 and A4 should be colored in red since they have a value that corresponds to a value in my "usernames and emails" worksheet list


问:
Trying to list a JSON value using Javascript to my website
I have a rather large JSON file which contains rating, comments etc for different movies. The syntax is like this:

```<code>reviews_object={"2396": {"xyz001": {"reg_date": null, "object": 2396, "rating": 3, "mod_date": "2008-11-17", "comment": "", "username": "xyz001"}}, "1107": {"xyz001": {"reg_date": null, "object": 1107, "rating": 4, "mod_date": "2006-11-26", "comment": "", "username": "xyz001"}
</code>```

Javascript code

```<code>var ratingList = document.querySelector("rating");

function averageRating () {
var reviews = reviews_object;
var reviewList = []; // Array of reviews

for (var i in reviews) {
    reviewList.push(reviews[i])
    console.log(reviewList);
}
</code>```

}

```<code>function displayRating (reviewList) {
for (var i = 0; i < reviewList.length; i++) {
    var li = document.createElement("li")
    li.innerHTML = reviewList[i].rating;
    rating.appendChild(li);

}
</code>```

}

Obviously it doesn't work and I am kinda stuck about what do to next. This JSON file is only for ratings and comments, and I also have one which is about the movie itself (title, length etc). Both the JSON objects has the object ID as you can see in the JSON code i posted.
What I want to do is to parse through the JSON rating object and list out specifically the rating key and its value to its corresponding object ID from the other JSON file.

Probably a bad explanation of what I want do to, but ask if you wanna know more

答:
That json represents an object with properties "2396", "1107", not an array.
Your javascript should work, just fix the return from your backend so you get an actual array.

It would need 2 new properties

```<code>    [{
        "PROPERTY1": "2396",
        "PROPERTY2": "xyz001",
        "reg_date": null,
        "object": 2396,
        "rating": 3,
        "mod_date": "2008-11-17",
        "comment": "",
        "username": "xyz001"
    },{
        "PROPERTY1": "1107",
        "PROPERTY2": "xyz001",
        "reg_date": null,
        "object": 1107,
        "rating": 4,
        "mod_date": "2006-11-26",
        "comment": "",
        "username": "xyz001"
    }]
</code>```

If you want to have it grouped you should use

```<code>[{
    "PROPERTY1": "2396",
    "data":[{
        "PROPERTY2": "xyz001",
        "reg_date": null,
        "object": 2396,
        "rating": 3,
        "mod_date": "2008-11-17",
        "comment": "",
        "username": "xyz001"
    },{...}]

}
,{...}]
</code>```

You would have to iterate throught the data property for each node.

Body:
I have a rather large JSON file which contains rating, comments etc for different movies. The syntax is like this:

reviews_object={"2396": {"xyz001": {"reg_date": null, "object": 2396, "rating": 3, "mod_date": "2008-11-17", "comment": "", "username": "xyz001"}}, "1107": {"xyz001": {"reg_date": null, "object": 1107, "rating": 4, "mod_date": "2006-11-26", "comment": "", "username": "xyz001"}

Javascript code

var ratingList = document.querySelector("rating");

function averageRating () {
var reviews = reviews_object;
var reviewList = []; // Array of reviews

for (var i in reviews) {
    reviewList.push(reviews[i])
    console.log(reviewList);
}

}

function displayRating (reviewList) {
for (var i = 0; i < reviewList.length; i++) {
    var li = document.createElement("li")
    li.innerHTML = reviewList[i].rating;
    rating.appendChild(li);

}

}

Obviously it doesn't work and I am kinda stuck about what do to next. This JSON file is only for ratings and comments, and I also have one which is about the movie itself (title, length etc). Both the JSON objects has the object ID as you can see in the JSON code i posted.
What I want to do is to parse through the JSON rating object and list out specifically the rating key and its value to its corresponding object ID from the other JSON file.

Probably a bad explanation of what I want do to, but ask if you wanna know more

Body:
That json represents an object with properties "2396", "1107", not an array.
Your javascript should work, just fix the return from your backend so you get an actual array.

It would need 2 new properties

    [{
        "PROPERTY1": "2396",
        "PROPERTY2": "xyz001",
        "reg_date": null,
        "object": 2396,
        "rating": 3,
        "mod_date": "2008-11-17",
        "comment": "",
        "username": "xyz001"
    },{
        "PROPERTY1": "1107",
        "PROPERTY2": "xyz001",
        "reg_date": null,
        "object": 1107,
        "rating": 4,
        "mod_date": "2006-11-26",
        "comment": "",
        "username": "xyz001"
    }]

If you want to have it grouped you should use

[{
    "PROPERTY1": "2396",
    "data":[{
        "PROPERTY2": "xyz001",
        "reg_date": null,
        "object": 2396,
        "rating": 3,
        "mod_date": "2008-11-17",
        "comment": "",
        "username": "xyz001"
    },{...}]

}
,{...}]

You would have to iterate throught the data property for each node.


问:
Unable to locate the specified class: Session.php in Codeigniter
The browser:

Unable to locate the specified class: Session.php

This is my Controller:

```<code><?php

class Chat extends CI_Controller {

    public function __construct() {

        parent::__construct();
        $this->load->model('Chat_model');
    }

    public function index() {

        $this->view_data['chat_id'] = 1;
        $this->view_data['student_id'] = $this->session->userdata('student_id');
        $this->view_data['page_content'] = 'chat';
        $this->load->view('chat');
    }

    public function ajax_addChatMessage() {

        $chat_id = $this->input->post('chat_id');
        $student_id = $this->input->post('student_id');
        $bericht = $this->input->post('chat_id', TRUE);

        $this->Chat_model->addChatMessage($chat_id, $student_id, $bericht);
    }
}
</code>```

When I put my model in comment in the parent::__construct(); // $this->load->model('Chat_model'); the error is gone.

This is my Chat_model:

```<code><?php

class Chat_model extends CI_Controller {

    public function Chat_model() {
        parent::__construct();
    }

    public function addChatMessage($chat_id, $student_id, $bericht) {

        $query = "INSERT INTO tbl_chatberichten (chat_id, student_id, bericht) VALUES (?,?,?)";
        $this->db->query($query, array($chat_id, $student_id, $bericht));

    }

}
</code>```

答:
If you use Codeigniter Modular Extensions HMVC this error can occur if you forget to change your class to extend MX_Controller instead of CI_Controller

So in your case you would start your class with:

```<code>class Chat extends MX_Controller {}
</code>```

Instead of:

```<code>class Chat extends CI_Controller {}
</code>```

Body:
The browser:

Unable to locate the specified class: Session.php

This is my Controller:

<?php

class Chat extends CI_Controller {

    public function __construct() {

        parent::__construct();
        $this->load->model('Chat_model');
    }

    public function index() {

        $this->view_data['chat_id'] = 1;
        $this->view_data['student_id'] = $this->session->userdata('student_id');
        $this->view_data['page_content'] = 'chat';
        $this->load->view('chat');
    }

    public function ajax_addChatMessage() {

        $chat_id = $this->input->post('chat_id');
        $student_id = $this->input->post('student_id');
        $bericht = $this->input->post('chat_id', TRUE);

        $this->Chat_model->addChatMessage($chat_id, $student_id, $bericht);
    }
}

When I put my model in comment in the parent::__construct(); // $this->load->model('Chat_model'); the error is gone.

This is my Chat_model:

<?php

class Chat_model extends CI_Controller {

    public function Chat_model() {
        parent::__construct();
    }

    public function addChatMessage($chat_id, $student_id, $bericht) {

        $query = "INSERT INTO tbl_chatberichten (chat_id, student_id, bericht) VALUES (?,?,?)";
        $this->db->query($query, array($chat_id, $student_id, $bericht));

    }

}

Body:
If you use Codeigniter Modular Extensions HMVC this error can occur if you forget to change your class to extend MX_Controller instead of CI_Controller

So in your case you would start your class with:

class Chat extends MX_Controller {}

Instead of:

class Chat extends CI_Controller {}

ContentLicense: CC BY-SA 4.0


问:
PHP to view PDF on web page and disable user to download
I'm going to write a site that lets users to view pdf files but I don't want them to save the files to their own hard drive due to the copy right law. I'm researching how to view it by using PHP, but I have no idea how to disable user not to download the files.

Actually, I want to use JavaScript to disable this action, but I get suggestions from other people not to do so because it's annoying to user.

So any suggestion or help would be very much appreciated.

答:
USE CSS opacity: 1.0 with a
 positioned over your content...

You could output the pdf using <object> or , then place a  with absolute position and use z-index to cover your pdf.  Use the css opacity: 1.0.

Now when users try to click or copy, they get nothing because they are really clicking on a blank
!!!!

Its a hack, but it works!  The user will be able to read the content, they could take a screen shot, but they won't be able to actually copy the text and paste it anywhere.

Body:
USE CSS opacity: 1.0 with a <div> positioned over your content...

You could output the pdf using <object> or <iframe>, then place a  with absolute position and use z-index to cover your pdf.  Use the css opacity: 1.0.

Now when users try to click or copy, they get nothing because they are really clicking on a blank <div>!!!!

Its a hack, but it works!  The user will be able to read the content, they could take a screen shot, but they won't be able to actually copy the text and paste it anywhere.


问:
How to encrypt connection string without app.config
Assume that app.config is, for whatever reason, not an option.

How is possible to store an encrypted connection string, either in the assembly itself or another app.config like XML file?

(I don't think it matters, but this is for an COM add-in for Excel 2003.)

答:
Sounds like a good use for ProtectedData class.

http://msdn.microsoft.com/en-us/library/system.security.cryptography.protecteddata.aspx

Calling Protect and passing in a byte array containing your connection string will return a byte array of encrypted data (which can then be converted to base64 and stored in a local file.

Calling Unprotect and passing in a byte array containing encrypted connection string will return a byte array containing the plaintext connection string.  Then simply use Convert to ASCII or UTF-8 etc.

Obviously if the attacker gains access to the user account running the app they will be able to recover the string but it provides a little more security than storing encryption string in assembly (which can allow recovery without gaining access to user account).


问:
Apache Storm tries localhost zookeeper connection instead of specified list of zookeeper servers
```<code>Storm 1.0.3
URL https://git-wip-us.apache.org/repos/asf/storm.git -r eac433b0beb3798c4723deb39b3c4fad446378f4
Branch (no branch)
Compiled by ptgoetz on 2017-02-07T20:22Z
From source with checksum c78e52de4b8a22d99551d45dfe9c1a4b

[root@storm-nimbus-prod]/opt/storm/logs# java -version
openjdk version "1.8.0_121"
OpenJDK Runtime Environment (build 1.8.0_121-b13)
OpenJDK 64-Bit Server VM (build 25.121-b13, mixed mode)
</code>```

env

```<code>export STORM_HOME=/opt/storm
export STORM=/opt/storm/bin
export STORM_CONFIG=/opt/storm/conf
</code>```

conf/storm.yaml

```<code>storm.zookeper.servers:
  - "10.138.0.8"
  - "10.138.0.9"
  - "10.138.0.16"

storm.zookeeper.port: 2181

nimbus.seeds: ["localhost"]

storm.local.dir: "/var/log/storm"
supervisor.slots.ports:
  - 6700
  - 6701
  - 6702
  - 6703

worker.childopts: "-Xmx768m"
nimbus.childopts: "-Xmx512m"
supervisor.childopts: "-Xmx256m"
</code>```

The problem

When I run ./storm nimbus I'm getting weird messages in opt/storm/logs/nimbus.log

```<code>2017-04-02 05:21:26.782 main o.a.s.s.o.a.c.f.i.CuratorFrameworkImpl [INFO] Starting
2017-04-02 05:21:26.789 main o.a.s.s.o.a.z.ZooKeeper [INFO] Initiating client connection, connectString=localhost:2181 sessionTimeout=20000 watcher=org.apache.storm.shade.org.apache.curator.ConnectionState@10afe71a
2017-04-02 05:21:26.802 main-SendThread(localhost:2181) o.a.s.s.o.a.z.ClientCnxn [INFO] Opening socket connection to server localhost/127.0.0.1:2181. Will not attempt to authenticate using SASL (unknown error)
2017-04-02 05:21:26.805 main-SendThread(localhost:2181) o.a.s.s.o.a.z.ClientCnxn [INFO] Opening socket connection to server localhost/0:0:0:0:0:0:0:1:2181. Will not attempt to authenticate using SASL (unknown error)
2017-04-02 05:21:26.808 main-SendThread(localhost:2181) o.a.s.s.o.a.z.ClientCnxn [INFO] Opening socket connection to server localhost/127.0.0.1:2181. Will not attempt to authenticate using SASL (unknown error)
2017-04-02 05:21:26.892 main-SendThread(localhost:2181) o.a.s.s.o.a.z.ClientCnxn [WARN] Session 0x0 for server null, unexpected error, closing socket connection and attempting reconnect
java.net.ConnectException: Connection refused
        at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
        at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
        at org.apache.storm.shade.org.apache.zookeeper.ClientCnxnSocketNIO.doTransport(ClientCnxnSocketNIO.java:361)
        at org.apache.storm.shade.org.apache.zookeeper.ClientCnxn$SendThread.run(ClientCnxn.java:1081)
2017-04-02 05:23:03.252 main-SendThread(localhost:2181) o.a.s.s.o.a.z.ClientCnxn [INFO] Opening socket connection to server localhost/0:0:0:0:0:0:0:1:2181. Will not attempt to authenticate using SASL (unknown error)
2017-04-02 05:23:03.353 main o.a.s.s.o.a.z.ZooKeeper [INFO] Session: 0x0 closed
2017-04-02 05:23:03.353 main o.a.s.s.o.a.z.ZooKeeper [INFO] Initiating client connection, connectString=localhost:2181 sessionTimeout=20000 watcher=org.apache.storm.shade.org.apache.curator.ConnectionState@10afe71a
2017-04-02 05:23:03.354 main-EventThread o.a.s.s.o.a.z.ClientCnxn [INFO] EventThread shut down
2017-04-02 05:23:03.356 main-SendThread(localhost:2181) o.a.s.s.o.a.z.ClientCnxn [INFO] Opening socket connection to server localhost/127.0.0.1:2181. Will not attempt to authenticate using SASL (unknown error)
2017-04-02 05:23:03.356 main-SendThread(localhost:2181) o.a.s.s.o.a.z.ClientCnxn [WARN] Session 0x0 for server null, unexpected error, closing socket connection and attempting reconnect
java.net.ConnectException: Connection refused
</code>```

so it seems it tries to connect to localhost:2181 for Zookeeper, while I have listed 3 IPs I can't find in logs at all.

I don't have local zookeeper up&running, but all 3 Zookeeper IPs are OK:

```<code>[root@storm-nimbus-prod]/opt/storm/logs# echo stat | nc 10.138.0.8 2181
Zookeeper version: 3.4.10-39d3a4f269333c922ed3db283be479f9deacaa0f, built on 03/23/2017 10:13 GMT
Clients:
 /10.138.0.10:60690[0](queued=0,recved=1,sent=0)
 /10.138.0.14:44242[1](queued=0,recved=4421,sent=4421)

Latency min/avg/max: 0/0/24
Received: 5268
Sent: 5272
Connections: 2
Outstanding: 0
Zxid: 0xf00000193
Mode: leader
Node count: 54
[root@storm-nimbus-prod]/opt/storm/logs# echo stat | nc 10.138.0.9 2181
Zookeeper version: 3.4.10-39d3a4f269333c922ed3db283be479f9deacaa0f, built on 03/23/2017 10:13 GMT
Clients:
 /10.138.0.13:51812[1](queued=0,recved=4536,sent=4543)
 /10.138.0.10:44096[0](queued=0,recved=1,sent=0)

Latency min/avg/max: 0/0/18
Received: 5310
Sent: 5320
Connections: 2
Outstanding: 0
Zxid: 0xf00000193
Mode: follower
Node count: 54
[root@storm-nimbus-prod]/opt/storm/logs# echo stat | nc 10.138.0.16 2181
Zookeeper version: 3.4.10-39d3a4f269333c922ed3db283be479f9deacaa0f, built on 03/23/2017 10:13 GMT
Clients:
 /10.138.0.10:34488[0](queued=0,recved=1,sent=0)

Latency min/avg/max: 0/0/18
Received: 973
Sent: 984
Connections: 1
Outstanding: 0
Zxid: 0xf00000193
Mode: follower
Node count: 54
</code>```

Any ideas?

答:
Ok the problem was that storm.zookeper.servers missed 'e', it should have been

storm.zookeeper.servers

Body:
Storm 1.0.3
URL https://git-wip-us.apache.org/repos/asf/storm.git -r eac433b0beb3798c4723deb39b3c4fad446378f4
Branch (no branch)
Compiled by ptgoetz on 2017-02-07T20:22Z
From source with checksum c78e52de4b8a22d99551d45dfe9c1a4b

[root@storm-nimbus-prod]/opt/storm/logs# java -version
openjdk version "1.8.0_121"
OpenJDK Runtime Environment (build 1.8.0_121-b13)
OpenJDK 64-Bit Server VM (build 25.121-b13, mixed mode)

env

export STORM_HOME=/opt/storm
export STORM=/opt/storm/bin
export STORM_CONFIG=/opt/storm/conf

conf/storm.yaml

storm.zookeper.servers:
  - "10.138.0.8"
  - "10.138.0.9"
  - "10.138.0.16"

storm.zookeeper.port: 2181

nimbus.seeds: ["localhost"]

storm.local.dir: "/var/log/storm"
supervisor.slots.ports:
  - 6700
  - 6701
  - 6702
  - 6703

worker.childopts: "-Xmx768m"
nimbus.childopts: "-Xmx512m"
supervisor.childopts: "-Xmx256m"

The problem

When I run ./storm nimbus I'm getting weird messages in opt/storm/logs/nimbus.log

2017-04-02 05:21:26.782 main o.a.s.s.o.a.c.f.i.CuratorFrameworkImpl [INFO] Starting
2017-04-02 05:21:26.789 main o.a.s.s.o.a.z.ZooKeeper [INFO] Initiating client connection, connectString=localhost:2181 sessionTimeout=20000 watcher=org.apache.storm.shade.org.apache.curator.ConnectionState@10afe71a
2017-04-02 05:21:26.802 main-SendThread(localhost:2181) o.a.s.s.o.a.z.ClientCnxn [INFO] Opening socket connection to server localhost/127.0.0.1:2181. Will not attempt to authenticate using SASL (unknown error)
2017-04-02 05:21:26.805 main-SendThread(localhost:2181) o.a.s.s.o.a.z.ClientCnxn [INFO] Opening socket connection to server localhost/0:0:0:0:0:0:0:1:2181. Will not attempt to authenticate using SASL (unknown error)
2017-04-02 05:21:26.808 main-SendThread(localhost:2181) o.a.s.s.o.a.z.ClientCnxn [INFO] Opening socket connection to server localhost/127.0.0.1:2181. Will not attempt to authenticate using SASL (unknown error)
2017-04-02 05:21:26.892 main-SendThread(localhost:2181) o.a.s.s.o.a.z.ClientCnxn [WARN] Session 0x0 for server null, unexpected error, closing socket connection and attempting reconnect
java.net.ConnectException: Connection refused
        at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
        at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
        at org.apache.storm.shade.org.apache.zookeeper.ClientCnxnSocketNIO.doTransport(ClientCnxnSocketNIO.java:361)
        at org.apache.storm.shade.org.apache.zookeeper.ClientCnxn$SendThread.run(ClientCnxn.java:1081)
2017-04-02 05:23:03.252 main-SendThread(localhost:2181) o.a.s.s.o.a.z.ClientCnxn [INFO] Opening socket connection to server localhost/0:0:0:0:0:0:0:1:2181. Will not attempt to authenticate using SASL (unknown error)
2017-04-02 05:23:03.353 main o.a.s.s.o.a.z.ZooKeeper [INFO] Session: 0x0 closed
2017-04-02 05:23:03.353 main o.a.s.s.o.a.z.ZooKeeper [INFO] Initiating client connection, connectString=localhost:2181 sessionTimeout=20000 watcher=org.apache.storm.shade.org.apache.curator.ConnectionState@10afe71a
2017-04-02 05:23:03.354 main-EventThread o.a.s.s.o.a.z.ClientCnxn [INFO] EventThread shut down
2017-04-02 05:23:03.356 main-SendThread(localhost:2181) o.a.s.s.o.a.z.ClientCnxn [INFO] Opening socket connection to server localhost/127.0.0.1:2181. Will not attempt to authenticate using SASL (unknown error)
2017-04-02 05:23:03.356 main-SendThread(localhost:2181) o.a.s.s.o.a.z.ClientCnxn [WARN] Session 0x0 for server null, unexpected error, closing socket connection and attempting reconnect
java.net.ConnectException: Connection refused

so it seems it tries to connect to localhost:2181 for Zookeeper, while I have listed 3 IPs I can't find in logs at all.

I don't have local zookeeper up&running, but all 3 Zookeeper IPs are OK:

[root@storm-nimbus-prod]/opt/storm/logs# echo stat | nc 10.138.0.8 2181
Zookeeper version: 3.4.10-39d3a4f269333c922ed3db283be479f9deacaa0f, built on 03/23/2017 10:13 GMT
Clients:
 /10.138.0.10:60690[0](queued=0,recved=1,sent=0)
 /10.138.0.14:44242[1](queued=0,recved=4421,sent=4421)

Latency min/avg/max: 0/0/24
Received: 5268
Sent: 5272
Connections: 2
Outstanding: 0
Zxid: 0xf00000193
Mode: leader
Node count: 54
[root@storm-nimbus-prod]/opt/storm/logs# echo stat | nc 10.138.0.9 2181
Zookeeper version: 3.4.10-39d3a4f269333c922ed3db283be479f9deacaa0f, built on 03/23/2017 10:13 GMT
Clients:
 /10.138.0.13:51812[1](queued=0,recved=4536,sent=4543)
 /10.138.0.10:44096[0](queued=0,recved=1,sent=0)

Latency min/avg/max: 0/0/18
Received: 5310
Sent: 5320
Connections: 2
Outstanding: 0
Zxid: 0xf00000193
Mode: follower
Node count: 54
[root@storm-nimbus-prod]/opt/storm/logs# echo stat | nc 10.138.0.16 2181
Zookeeper version: 3.4.10-39d3a4f269333c922ed3db283be479f9deacaa0f, built on 03/23/2017 10:13 GMT
Clients:
 /10.138.0.10:34488[0](queued=0,recved=1,sent=0)

Latency min/avg/max: 0/0/18
Received: 973
Sent: 984
Connections: 1
Outstanding: 0
Zxid: 0xf00000193
Mode: follower
Node count: 54

Any ideas?


问:
Why do we really need Comparator in Java?
My questions is basically divided into two sub-questions:

Comparable talks about natural ordering. Who is stopping us from implementing a non-natural ordering login in the compareTo method ?

Comparator can do the same stuff as Comparable (ASC or DESC sort). So the only reason it exists is because that if we have a third party class which we cannot change (make it implement Comparable) then we can externalise the sorting logic using Comparator. Is this correct ?

答: A class can only have one compareTo method but you can define as many comparators as you like for it. This is useful to define different orderings which is not such an uncommon requirement.


问:
Determining page numbers and offsets for given addresses
Consider a computer system with a 32-bit logical address and 4KB page size. The system supports up to 512MB of physical memory.

How many entries are there in a conventional single-level page table?

```<code>Conventional single-level page table: 2^32 / 2^12 (4000)  = 2^20 = 1,048,576
</code>```

Why did I have to divide 2^32 / 2^12 to get the answer?

How many entries are there in an inverted page table?

An inverted page table needs as many entries as there are page frames
  in memory.

```<code>Inverted page table: 2^29 (512mb)/ 2^12 (4000) = 2^17 = 131,072
</code>```

Why did I have to divide 512mb / page size to get the inverted page table entries?

What are the page numbers and offsets for the following address
  references: a) 30000, b) 256, c) 0xbcf034

a) 30000 in hex: x7530  Page #: x7 = 7 offset: x530 = 1328

b) 256 in hex x100  Page #: x0 = 0 offset: x100 = 256

c) 0xbcf034 Page #: xbcf = 3023 offset: x034 = 22

How do I figure out these page numbers and offsets based on the hex addresses?

I know the answers and but I want to understand WHY and HOW. Can someone please explain in detail :)

答:
because page size = frame size = 2^12
number of entries in inverted page table  = no of frames
so we are calculating no of frames</p>

Body:
Consider a computer system with a 32-bit logical address and 4KB page size. The system supports up to 512MB of physical memory.

How many entries are there in a conventional single-level page table?

Conventional single-level page table: 2^32 / 2^12 (4000)  = 2^20 = 1,048,576

Why did I have to divide 2^32 / 2^12 to get the answer?

How many entries are there in an inverted page table?

An inverted page table needs as many entries as there are page frames
  in memory.

Inverted page table: 2^29 (512mb)/ 2^12 (4000) = 2^17 = 131,072

Why did I have to divide 512mb / page size to get the inverted page table entries?

What are the page numbers and offsets for the following address
  references: a) 30000, b) 256, c) 0xbcf034

a) 30000 in hex: x7530  Page #: x7 = 7 offset: x530 = 1328

b) 256 in hex x100  Page #: x0 = 0 offset: x100 = 256

c) 0xbcf034 Page #: xbcf = 3023 offset: x034 = 22

How do I figure out these page numbers and offsets based on the hex addresses?

I know the answers and but I want to understand WHY and HOW. Can someone please explain in detail :)


问:
Linear regression with tensorflow
I trying to understand linear regression... here is script that I tried to understand:

```<code>'''
A linear regression learning algorithm example using TensorFlow library.
Author: Aymeric Damien
Project: https://github.com/aymericdamien/TensorFlow-Examples/
'''

from __future__ import print_function

import tensorflow as tf
from numpy import *
import numpy
import matplotlib.pyplot as plt
rng = numpy.random

# Parameters
learning_rate = 0.0001
training_epochs = 1000
display_step = 50

# Training Data
train_X = numpy.asarray([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,
                         7.042,10.791,5.313,7.997,5.654,9.27,3.1])
train_Y = numpy.asarray([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,
                         2.827,3.465,1.65,2.904,2.42,2.94,1.3])

train_X=numpy.asarray(train_X)
train_Y=numpy.asarray(train_Y)
n_samples = train_X.shape[0]

# tf Graph Input
X = tf.placeholder("float")
Y = tf.placeholder("float")

# Set model weights
W = tf.Variable(rng.randn(), name="weight")
b = tf.Variable(rng.randn(), name="bias")

# Construct a linear model
pred = tf.add(tf.multiply(X, W), b)

# Mean squared error
cost = tf.reduce_sum(tf.pow(pred-Y, 2))/(2*n_samples)
# Gradient descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

# Initializing the variables
init = tf.global_variables_initializer()

# Launch the graph
with tf.Session() as sess:
    sess.run(init)

    # Fit all training data
    for epoch in range(training_epochs):
        for (x, y) in zip(train_X, train_Y):
            sess.run(optimizer, feed_dict={X: x, Y: y})

        # Display logs per epoch step
        if (epoch+1) % display_step == 0:
            c = sess.run(cost, feed_dict={X: train_X, Y:train_Y})
            print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c), \
                "W=", sess.run(W), "b=", sess.run(b))

    print("Optimization Finished!")
    training_cost = sess.run(cost, feed_dict={X: train_X, Y: train_Y})
    print("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n')

    # Graphic display
    plt.plot(train_X, train_Y, 'ro', label='Original data')
    plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')
    plt.legend()
    plt.show()
</code>```

Question is what this part represent:

```<code># Set model weights
W = tf.Variable(rng.randn(), name="weight")
b = tf.Variable(rng.randn(), name="bias")
</code>```

And why are there random float numbers?

Also could you show me some math with formals represents cost, pred, optimizer variables?

答:
I'll first define the variables:

```<code>W is a multidimensional line that spans R^d (same dimensionality as X)
b is a scalar value (bias)
Y is also a scalar value i.e. the value at X

pred = W (dot) X + b   # dot here refers to dot product

# cost equals the average squared error
cost = ((pred - Y)^2) / 2*num_samples

#finally optimizer
# optimizer computes the gradient with respect to each variable and the update

W += learning_rate * (pred - Y)/num_samples * X
b += learning_rate * (pred - Y)/num_samples
</code>```

Why are W and b set to random well this updates based on gradients from the error calculated from the cost so W and b could have been initialized to anything.  It isn't performing linear regression via  least squares method although both will converge to the same solution.

Look here for more information: Getting Started

Title: Linear regression with tensorflow

Body:
I trying to understand linear regression... here is script that I tried to understand:

'''
A linear regression learning algorithm example using TensorFlow library.
Author: Aymeric Damien
Project: https://github.com/aymericdamien/TensorFlow-Examples/
'''

from __future__ import print_function

import tensorflow as tf
from numpy import *
import numpy
import matplotlib.pyplot as plt
rng = numpy.random

# Parameters
learning_rate = 0.0001
training_epochs = 1000
display_step = 50

# Training Data
train_X = numpy.asarray([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,
                         7.042,10.791,5.313,7.997,5.654,9.27,3.1])
train_Y = numpy.asarray([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,
                         2.827,3.465,1.65,2.904,2.42,2.94,1.3])

train_X=numpy.asarray(train_X)
train_Y=numpy.asarray(train_Y)
n_samples = train_X.shape[0]

# tf Graph Input
X = tf.placeholder("float")
Y = tf.placeholder("float")

# Set model weights
W = tf.Variable(rng.randn(), name="weight")
b = tf.Variable(rng.randn(), name="bias")

# Construct a linear model
pred = tf.add(tf.multiply(X, W), b)

# Mean squared error
cost = tf.reduce_sum(tf.pow(pred-Y, 2))/(2*n_samples)
# Gradient descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

# Initializing the variables
init = tf.global_variables_initializer()

# Launch the graph
with tf.Session() as sess:
    sess.run(init)

    # Fit all training data
    for epoch in range(training_epochs):
        for (x, y) in zip(train_X, train_Y):
            sess.run(optimizer, feed_dict={X: x, Y: y})

        # Display logs per epoch step
        if (epoch+1) % display_step == 0:
            c = sess.run(cost, feed_dict={X: train_X, Y:train_Y})
            print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c), \
                "W=", sess.run(W), "b=", sess.run(b))

    print("Optimization Finished!")
    training_cost = sess.run(cost, feed_dict={X: train_X, Y: train_Y})
    print("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n')

    # Graphic display
    plt.plot(train_X, train_Y, 'ro', label='Original data')
    plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')
    plt.legend()
    plt.show()

Question is what this part represent:

# Set model weights
W = tf.Variable(rng.randn(), name="weight")
b = tf.Variable(rng.randn(), name="bias")

And why are there random float numbers?

Also could you show me some math with formals represents cost, pred, optimizer variables?

Body:
I'll first define the variables:

W is a multidimensional line that spans R^d (same dimensionality as X)
b is a scalar value (bias)
Y is also a scalar value i.e. the value at X

pred = W (dot) X + b   # dot here refers to dot product

# cost equals the average squared error
cost = ((pred - Y)^2) / 2*num_samples

#finally optimizer
# optimizer computes the gradient with respect to each variable and the update

W += learning_rate * (pred - Y)/num_samples * X
b += learning_rate * (pred - Y)/num_samples

Why are W and b set to random well this updates based on gradients from the error calculated from the cost so W and b could have been initialized to anything.  It isn't performing linear regression via  least squares method although both will converge to the same solution.

Look here for more information: Getting Started


问:
How to unpack a list?
When extracting data from a list this way

```<code>line[0:3], line[3][:2], line[3][2:]
</code>```

I receive an array and two variables after it, as should be expected:

```<code>(['a', 'b', 'c'], 'd', 'e')
</code>```

I need to manipulate the list so the end result is

```<code>('a', 'b', 'c', 'd', 'e')
</code>```

How? Thank you.

P.S. Yes, I know that I can write down the first element as line[0], line[1], line[2], but I think that's a pretty awkward solution.

答:
This function

```<code>def merge(seq):
    merged = []
    for s in seq:
        for x in s:
            merged.append(x)
    return merged
</code>```

source: http://www.testingreflections.com/node/view/4930

Title: How to unpack a list?

Body:
When extracting data from a list this way

line[0:3], line[3][:2], line[3][2:]

I receive an array and two variables after it, as should be expected:

(['a', 'b', 'c'], 'd', 'e')

I need to manipulate the list so the end result is

('a', 'b', 'c', 'd', 'e')

How? Thank you.

P.S. Yes, I know that I can write down the first element as line[0], line[1], line[2], but I think that's a pretty awkward solution.

Body:
This function

def merge(seq):
    merged = []
    for s in seq:
        for x in s:
            merged.append(x)
    return merged

source: http://www.testingreflections.com/node/view/4930


问:
Cannot access Google Cloud SQL database from my App Engine
Last week I tried to setup Google Cloud for a NodeJS API and Cloud SQL database. Overall it works fine, but I can't access my Cloud SQL database. The authorization of the SQL database shows that all apps within the current project are granted to access the database. Unfortunality, this is not true. I need to granted the IP addresses of the instances from the App Engine. The IP adressess of the instances constantly changes after I deploy a newer version of the the API.

Does anybody have a solution to get access from the App Engine to the Cloud SQL database. It's very annoying to add constant the instance ip address to grant the database.

Sample here

Thank you in advance!

Jelle

答:
I was going to suggest to assign a static IP to the app engine, but seems like it's not possible in App engine (it's possible in compute engine though). So lets tackle the root of the problem, you being unable to access cloud sql from App engine, are you sure you followed the instructions of the following link to the letter?

https://cloud.google.com/nodejs/getting-started/using-cloud-sql

This might solve your connection issue if you haven't.


问:
Javascript localstorage get the value into array one by one
Problem:
I would like get the localstorage value "car", i want to get the result like   car = ["red","blue"] in other page, i want to get the result into array one by one. How can i fix it?</p>

```<code>page 1:
car = ["red","blue"];
localStorage.setItem("car", JSON.stringify(car));

 Another Page:
  var car1 = JSON.parse(localStorage.getItem("car"));
  alert(car1[0])
   ****show two record at the same time , i want to put it into array like car1[0] = red; car1[1] = blue;
</code>```

答:
as i know, when you convert it to json it wouldn't parse to you items like array
so car[0] doesn't work as you want,
This is a good resource of using localstorage:
 https://www.smashingmagazine.com/2010/10/local-storage-and-how-to-use-it/

U must enter the items as an object and give them an id
like this:

```<code>{
 name: red,
 id: 1,
}
</code>```

Then retrieve it by car id.

and a better answer: How do I store an array in localStorage?

And know it JSON is not supported in IE7 and earlier.

Body:
Problem:
I would like get the localstorage value "car", i want to get the result like   car = ["red","blue"] in other page, i want to get the result into array one by one. How can i fix it?

page 1:
car = ["red","blue"];
localStorage.setItem("car", JSON.stringify(car));

 Another Page:
  var car1 = JSON.parse(localStorage.getItem("car"));
  alert(car1[0])
   ****show two record at the same time , i want to put it into array like car1[0] = red; car1[1] = blue;

Body:
as i know, when you convert it to json it wouldn't parse to you items like array
so car[0] doesn't work as you want,
This is a good resource of using localstorage:
 https://www.smashingmagazine.com/2010/10/local-storage-and-how-to-use-it/

U must enter the items as an object and give them an id
like this:

{
 name: red,
 id: 1,
}

Then retrieve it by car id.

and a better answer: How do I store an array in localStorage?

And know it JSON is not supported in IE7 and earlier.


问:
Where is link path info generated from?
When I compile my iPhone application I get lots of errors, but the one that looks the most obvious to me is this link error:

```<code>ld: warning: directory '/Users/username/Documents/iPhone/MyAppName/../../core-plot/framework/build/Debug-iphonesimulator' following -L not found
</code>```

I know the above path is wrong.

The correct path is:

```<code>/Users/username/Documents/iPhone/MyAppName/../core-plot/framework/build/Debug-iphonesimulator
</code>```

I'd love to point to the right location, but I have no clue where this wrong path info is coming from.
I have looked at every field in Project Settings and Target Settings but they're correct because they use "../" instead of "../../"
Any suggestions on where I can correct this?
Thanks.

答:
This should take care of itself if you've correctly configured your project. Follow the core-plot project instructions on using CorePlot in an iPhone app, which are illustrated with screenshots here.

In short:

Drag the Core Plot project file into your project's group browser.

Drag the library that will show up as a child of the project file under the "Link Binaries with Libraries" build phase for your application's build target.

Update the Header Search Path in your application's build configuration to include the Core Plot headers.

Add -ObjC to the Other Linker Flags application build configuration setting.

Title: Where is link path info generated from?

Body:
When I compile my iPhone application I get lots of errors, but the one that looks the most obvious to me is this link error:

ld: warning: directory '/Users/username/Documents/iPhone/MyAppName/../../core-plot/framework/build/Debug-iphonesimulator' following -L not found

I know the above path is wrong.

The correct path is:

/Users/username/Documents/iPhone/MyAppName/../core-plot/framework/build/Debug-iphonesimulator

I'd love to point to the right location, but I have no clue where this wrong path info is coming from.
I have looked at every field in Project Settings and Target Settings but they're correct because they use "../" instead of "../../"
Any suggestions on where I can correct this?
Thanks.


问:
javascript create dictionary from array
I have an array like this

```<code>propertiesToCheck: [
    {name: 'name', type: 'type', enabled: true},
    {
        name: 'name2',
        type: 'type2',
        templateUrl: 'something.html',
        preferences: {
            places: [place1, place2,...],
            placesDict: ????
        },
        enabled: true
    }
]
</code>```

In the places array there are objects with id, name, etc. Now I want to create a dictionary placesDict that should look like {place1.id: 0, place2.id: 0, ...}, so all values will be set to 0. How can I do that?

答:
In Ramda for instance:</p>

```<code>var createDict = R.pipe(R.pluck('id'), R.map(R.pair(R.__, 0)), R.fromPairs);

var places = [{ id: 'place1id' }, { id: 'place2id' }];
var placesDict = createDict(places);

// {"place1id": 0, "place2id": 0}
</code>```

Title: javascript create dictionary from array

Body:
I have an array like this

propertiesToCheck: [
    {name: 'name', type: 'type', enabled: true},
    {
        name: 'name2',
        type: 'type2',
        templateUrl: 'something.html',
        preferences: {
            places: [place1, place2,...],
            placesDict: ????
        },
        enabled: true
    }
]

In the places array there are objects with id, name, etc. Now I want to create a dictionary placesDict that should look like {place1.id: 0, place2.id: 0, ...}, so all values will be set to 0. How can I do that?

Body:
In Ramda for instance:

var createDict = R.pipe(R.pluck('id'), R.map(R.pair(R.__, 0)), R.fromPairs);

var places = [{ id: 'place1id' }, { id: 'place2id' }];
var placesDict = createDict(places);

// {"place1id": 0, "place2id": 0}


问:
Breadth first search wrong output
```<code>teren = [
    '########',
    '#s.....#',
    '###..#.#',
    '#...##.#',
    '#.#....#',
    '#.####.#',
    '#......#',
    '###e####'
    ]

def bfs(teren, start, end):
    queue = []
    visited = []
    queue.append([start])

    while queue:
        path = queue.pop()
        node = path[-1]

        x = node[0]
        y = node[1]

        if node == end:
            return path
        if node in visited or teren[x][y] == "#":
            continue

        visited.append(node)

        for adjacent in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
            new_path = list(path)
            new_path.append(adjacent)
            queue.append(new_path)

print(bfs(teren, (1,1), (7, 3)))
</code>```

This is the code i used to try and navigate this maze type thing, this is the output i get [(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 6), (3, 6), (4, 6), (4, 5), (4, 4), (4, 3), (3, 3), (3, 2), (3, 1), (4, 1), (5, 1), (6, 1), (6, 2), (6, 3), (7, 3)] while this is the output i need [(1, 1), (1, 2), (1, 3), (2, 3), (3, 3), (3, 2), (3, 1), (4, 1), (5, 1), (6, 1), (6, 2), (6, 3), (7, 3)]

It seems this is printing out all the walkable coordinates, but I have no idea how to fix that, all the examples online that use grids focus to much on drawing the grid which clutters the actual bfs.

答:
You will get the output you look for if you treat your queue as a queue. This means you don't pop the last element off, but you shift out the first:

replace:

```<code> path = queue.pop()
</code>```

with:

```<code> path, queue = queue[0], queue[1:]
</code>```

or:

```<code> path = queue.pop(0)
</code>```

However deque-objects are better suited for such operations:

```<code>from collections import deque

def bfs(teren, start, end):
    queue = deque([])
    visited = []
    queue.append([start])

    while queue:
        path = queue.popleft()
        # ...etc.
</code>```

Title: Breadth first search wrong output

Body:
teren = [
    '########',
    '#s.....#',
    '###..#.#',
    '#...##.#',
    '#.#....#',
    '#.####.#',
    '#......#',
    '###e####'
    ]

def bfs(teren, start, end):
    queue = []
    visited = []
    queue.append([start])

    while queue:
        path = queue.pop()
        node = path[-1]

        x = node[0]
        y = node[1]

        if node == end:
            return path
        if node in visited or teren[x][y] == "#":
            continue

        visited.append(node)

        for adjacent in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
            new_path = list(path)
            new_path.append(adjacent)
            queue.append(new_path)

print(bfs(teren, (1,1), (7, 3)))

This is the code i used to try and navigate this maze type thing, this is the output i get [(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 6), (3, 6), (4, 6), (4, 5), (4, 4), (4, 3), (3, 3), (3, 2), (3, 1), (4, 1), (5, 1), (6, 1), (6, 2), (6, 3), (7, 3)] while this is the output i need [(1, 1), (1, 2), (1, 3), (2, 3), (3, 3), (3, 2), (3, 1), (4, 1), (5, 1), (6, 1), (6, 2), (6, 3), (7, 3)]

It seems this is printing out all the walkable coordinates, but I have no idea how to fix that, all the examples online that use grids focus to much on drawing the grid which clutters the actual bfs.

Body:
You will get the output you look for if you treat your queue as a queue. This means you don't pop the last element off, but you shift out the first:

replace:

 path = queue.pop()

with:

 path, queue = queue[0], queue[1:]

or:

 path = queue.pop(0)

However deque-objects are better suited for such operations:

from collections import deque

def bfs(teren, start, end):
    queue = deque([])
    visited = []
    queue.append([start])

    while queue:
        path = queue.popleft()
        # ...etc.