问:
Implementing LSTM regression model with tensor flow
I am trying to implement a tensor flow LSTM regression model for a list  of inputs number.
 example:

```<code> input_data = [1, 2, 3, 4, 5]
 time_steps = 2
    -> X == [[1, 2], [2, 3], [3, 4]]
    -> y == [3, 4, 5]
</code>```

The code is below:

```<code>TIMESTEPS = 20
num_hidden=20

Xd, yd = load_data()

train_input = Xd['train']
train_input = train_input.reshape(-1,20,1)
train_output = yd['train']

# train_input = [[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],..
# train_output  = [[21],[22],[23]....

test_input = Xd['test']
test_output = yd['test']

X = tf.placeholder(tf.float32, [None, 20, 1])
y = tf.placeholder(tf.float32, [None, 1])

cell = tf.nn.rnn_cell.LSTMCell(num_hidden, state_is_tuple=True)

val, state = tf.nn.dynamic_rnn(cell, X, dtype=tf.float32)
val = tf.Print(val, [tf.argmax(val,1)], 'argmax(val)=' , summarize=20, first_n=7)

val = tf.transpose(val, [1, 0, 2])
val = tf.Print(val, [tf.argmax(val,1)], 'argmax(val2)=' , summarize=20, first_n=7)

# Take only the last output after 20 time steps
last = tf.gather(val, int(val.get_shape()[0]) - 1)
last = tf.Print(last, [tf.argmax(last,1)], 'argmax(val3)=' , summarize=20, first_n=7)

# define variables for weights and bias
weight = tf.Variable(tf.truncated_normal([num_hidden, int(y.get_shape()[1])]))
bias = tf.Variable(tf.constant(0.1, shape=[y.get_shape()[1]]))

# Prediction is matmul of last value + wieght + bias
prediction = tf.matmul(last, weight) + bias

# Cost function using softmax
# y is the true distrubution and prediction is the predicted
cost = tf.reduce_mean(-tf.reduce_sum(y * tf.log(prediction), reduction_indices=[1]))
#cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y))

optimizer = tf.train.AdamOptimizer()
minimize = optimizer.minimize(cost)

from tensorflow.python import debug as tf_debug
inita = tf.initialize_all_variables()
sess = tf.Session()
sess.run(inita)

batch_size = 100
no_of_batches = int(len(train_input)/batch_size)
epoch = 10
test_size = 100
for i in range(epoch):
    for start, end in zip(range(0, len(train_input), batch_size), range(batch_size, len(train_input)+1, batch_size)):
        sess.run(minimize, feed_dict={X: train_input[start:end], y: train_output[start:end]})

    test_indices = np.arange(len(test_input))  # Get A Test Batch
    np.random.shuffle(test_indices)
    test_indices = test_indices[0:test_size]
    print (i, mean_squared_error(np.argmax(test_output[test_indices], axis=1), sess.run(prediction, feed_dict={X: test_input[test_indices]})))

print ("predictions", prediction.eval(feed_dict={X: train_input}, session=sess))
y_pred = prediction.eval(feed_dict={X: test_input}, session=sess)
sess.close()
test_size = test_output.shape[0]
ax = np.arange(0, test_size, 1)
plt.plot(ax, test_output, 'r', ax, y_pred, 'b')
plt.show()
</code>```

But i am not able to minimize the cost, the calculated MSE increases at each step instead of decreasing.
I suspect there is a problem with the cost problem that i am using.

any thoughts or suggestions as to what i am doing wrong ?

Thanks

答: As mentioned in the comment, you had to change your loss function to the MSE function and reduce your learning rate. Is your error converging to zero ?</p>

Body:
I am trying to implement a tensor flow LSTM regression model for a list  of inputs number.
 example:

 input_data = [1, 2, 3, 4, 5]
 time_steps = 2
    -> X == [[1, 2], [2, 3], [3, 4]]
    -> y == [3, 4, 5]

The code is below:

TIMESTEPS = 20
num_hidden=20

Xd, yd = load_data()

train_input = Xd['train']
train_input = train_input.reshape(-1,20,1)
train_output = yd['train']

# train_input = [[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],..
# train_output  = [[21],[22],[23]....

test_input = Xd['test']
test_output = yd['test']

X = tf.placeholder(tf.float32, [None, 20, 1])
y = tf.placeholder(tf.float32, [None, 1])

cell = tf.nn.rnn_cell.LSTMCell(num_hidden, state_is_tuple=True)

val, state = tf.nn.dynamic_rnn(cell, X, dtype=tf.float32)
val = tf.Print(val, [tf.argmax(val,1)], 'argmax(val)=' , summarize=20, first_n=7)

val = tf.transpose(val, [1, 0, 2])
val = tf.Print(val, [tf.argmax(val,1)], 'argmax(val2)=' , summarize=20, first_n=7)

# Take only the last output after 20 time steps
last = tf.gather(val, int(val.get_shape()[0]) - 1)
last = tf.Print(last, [tf.argmax(last,1)], 'argmax(val3)=' , summarize=20, first_n=7)

# define variables for weights and bias
weight = tf.Variable(tf.truncated_normal([num_hidden, int(y.get_shape()[1])]))
bias = tf.Variable(tf.constant(0.1, shape=[y.get_shape()[1]]))

# Prediction is matmul of last value + wieght + bias
prediction = tf.matmul(last, weight) + bias

# Cost function using softmax
# y is the true distrubution and prediction is the predicted
cost = tf.reduce_mean(-tf.reduce_sum(y * tf.log(prediction), reduction_indices=[1]))
#cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y))

optimizer = tf.train.AdamOptimizer()
minimize = optimizer.minimize(cost)

from tensorflow.python import debug as tf_debug
inita = tf.initialize_all_variables()
sess = tf.Session()
sess.run(inita)

batch_size = 100
no_of_batches = int(len(train_input)/batch_size)
epoch = 10
test_size = 100
for i in range(epoch):
    for start, end in zip(range(0, len(train_input), batch_size), range(batch_size, len(train_input)+1, batch_size)):
        sess.run(minimize, feed_dict={X: train_input[start:end], y: train_output[start:end]})

    test_indices = np.arange(len(test_input))  # Get A Test Batch
    np.random.shuffle(test_indices)
    test_indices = test_indices[0:test_size]
    print (i, mean_squared_error(np.argmax(test_output[test_indices], axis=1), sess.run(prediction, feed_dict={X: test_input[test_indices]})))

print ("predictions", prediction.eval(feed_dict={X: train_input}, session=sess))
y_pred = prediction.eval(feed_dict={X: test_input}, session=sess)
sess.close()
test_size = test_output.shape[0]
ax = np.arange(0, test_size, 1)
plt.plot(ax, test_output, 'r', ax, y_pred, 'b')
plt.show()

But i am not able to minimize the cost, the calculated MSE increases at each step instead of decreasing.
I suspect there is a problem with the cost problem that i am using.

any thoughts or suggestions as to what i am doing wrong ?

Thanks


来源: stackexchange

问:
Magento 2 : How to generate Add to Cart URL
I am looping some specific products on the home page but unable to generate the ADD TO CART URL in magento 2

How to generate ADD TO CART URL when displaying products in loop.

答:
I know it's been a year since this has been touched on, but as I've just done what has been requested, I thought that I may post my solution to help others.

The other answers will work, but only for simple products, where no further input is required (e.g. selecting options). When using getAddToCartUrl(), Magento first checks if the products requires any options to be selected; if it does, then it will simply supply the URL to the product page instead.

To skip all of these checks and directly obtain the add to cart URL, then make use of the Magento\Checkout\Helper\Cart helper instead. If you are within a .phtml file, then this can be utilised simply by calling $this->helper:

```<code>$cartHelper = $this->helper('Magento\Checkout\Helper\Cart');
</code>```

From there, you can generate the add to cart URL via getAddUrl(), ensuring you pass the product object as the parameter:

```<code>echo $cartHelper->getAddUrl($product)
</code>```

For it to fully work, you must have a hidden field for the form key as described in the other answers, and if the product in question has compulsory options to choose from (e.g. a configurable product), then make sure you include those fields as well, otherwise you will get redirected to the product page itself, with a message informing the user that options are required.

ContentLicense: CC BY-SA 3.0

Body:
I know it's been a year since this has been touched on, but as I've just done what has been requested, I thought that I may post my solution to help others.

The other answers will work, but only for simple products, where no further input is required (e.g. selecting options). When using getAddToCartUrl(), Magento first checks if the products requires any options to be selected; if it does, then it will simply supply the URL to the product page instead.

To skip all of these checks and directly obtain the add to cart URL, then make use of the Magento\Checkout\Helper\Cart helper instead. If you are within a .phtml file, then this can be utilised simply by calling $this->helper:

$cartHelper = $this->helper('Magento\Checkout\Helper\Cart');

From there, you can generate the add to cart URL via getAddUrl(), ensuring you pass the product object as the parameter:

echo $cartHelper->getAddUrl($product)

For it to fully work, you must have a hidden field for the form key as described in the other answers, and if the product in question has compulsory options to choose from (e.g. a configurable product), then make sure you include those fields as well, otherwise you will get redirected to the product page itself, with a message informing the user that options are required.


问:
Putting of common method of derived classes in base, where the base doesn't use it
Is it correct from terms of OOP to put common method of derived classes in base class, where base doesn't (!) use it. As in the example:</p>

```<code>class Base {
    virtual void CalculateTotal()
    {
        //calculate without taxes (no need in base)
    }

    void CalculateTaxes()
    {
        //do something
    }
}

class A : Base {
   override void CalculateTotal() {
       //...
       CalculateTaxes();
       //...
   }
}

class B : Base {
   override void CalculateTotal() {
       //...
       CalculateTaxes();
       //...
   }
}
</code>```

答: If there is no default functionality for calculating total value and each class, derived from the Base should provide it, better to make the Base class and the CalculateTotal method abstract.

Body:
Is it correct from terms of OOP to put common method of derived classes in base class, where base doesn't (!) use it. As in the example:

class Base {
    virtual void CalculateTotal()
    {
        //calculate without taxes (no need in base)
    }

    void CalculateTaxes()
    {
        //do something
    }
}

class A : Base {
   override void CalculateTotal() {
       //...
       CalculateTaxes();
       //...
   }
}

class B : Base {
   override void CalculateTotal() {
       //...
       CalculateTaxes();
       //...
   }
}


问:
Groovy Script to add new phase job to multi-job in Jenkins
For the already available multi-job in jenkins, need to add new phase jobs using Groovy Scripting. I have written the following groovy code which adds up an already existing job p25_deploy-1.

This code is working to create the multi-job but the phase job is not showing as mapped in the Jenkins UI. Where as if I see it config.xml, its created properly as expected except a tag <killPhaseOnJobResultCondition>. Not sure why the phase job is not mapped properly?

```<code>import jenkins.model.*
import hudson.model.*
import com.tikal.jenkins.plugins.multijob.*
import com.tikal.jenkins.plugins.multijob.PhaseJobsConfig.*
import com.tikal.jenkins.plugins.multijob.PhaseJobsConfig.KillPhaseOnJobResultCondition.*
import java.lang.String.*
import hudson.model.Descriptor;
import hudson.tasks.Builder;

def jenkinsInstance = jenkins.model.Jenkins.instance

def templateJobName = 'profile_p25'

def templateJob = jenkinsInstance.getJob(templateJobName)

 // get MultiJob BuildPhases and clone each PhaseJob
 builders = templateJob.getBuilders();

builders.each { b ->
if (b instanceof MultiJobBuilder){
def pj = b.getPhaseJobs()

   hudson.model.Describable p1 = new PhaseJobsConfig("p25_deploy-1",null,
        true,PhaseJobsConfig.KillPhaseOnJobResultCondition NEVER,null,false,false,null,0,false,true,null,false,false)
   pj.add(p1)
   }
 }

    templateJob.save()
   // update dependencies
    jenkinsInstance.rebuildDependencyGraph()
</code>```

Any help will be really appreciated. Have tried many ways but was not able to figure out the problem with the script.

We can use DSL to create but I wanted it to be done in Groovy Scripting and moreover modify the existing job.

Blockquote

答:
Yay! I am back with the answer for my question. Have tried this since very long time. Finally am able to make it though. I was aware that solution would be really simple but not able to figure out the hack of it.</p>
```<code>import jenkins.model.*
import hudson.model.*
import com.tikal.jenkins.plugins.multijob.*
import com.tikal.jenkins.plugins.multijob.PhaseJobsConfig.*
import com.tikal.jenkins.plugins.multijob.PhaseJobsConfig.KillPhaseOnJobResultCondition.*
import java.lang.String.*
import hudson.model.Descriptor
import hudson.tasks.Builder

def jenkinsInstance = jenkins.model.Jenkins.instance

def templateJobName = 'profile_p25'

def templateJob = jenkinsInstance.getJob(templateJobName)

// get MultiJob BuildPhases and clone each PhaseJob
builders = templateJob.getBuilders();

builders.each { b -> if (b instanceof MultiJobBuilder)
    { def pj =
        b.getPhaseJobs()

        hudson.model.Describable newphase = new
        PhaseJobsConfig(deploys[i],null,
            true,null,null,false,false,null,0,false,false,"",false,false)
            newphase.killPhaseOnJobResultCondition = 'NEVER'
            pj.add(newphase)
    }
}
templateJob.save()
</code>```

Body:
For the already available multi-job in jenkins, need to add new phase jobs using Groovy Scripting. I have written the following groovy code which adds up an already existing job p25_deploy-1.

This code is working to create the multi-job but the phase job is not showing as mapped in the Jenkins UI. Where as if I see it config.xml, its created properly as expected except a tag <killPhaseOnJobResultCondition>. Not sure why the phase job is not mapped properly?

import jenkins.model.*
import hudson.model.*
import com.tikal.jenkins.plugins.multijob.*
import com.tikal.jenkins.plugins.multijob.PhaseJobsConfig.*
import com.tikal.jenkins.plugins.multijob.PhaseJobsConfig.KillPhaseOnJobResultCondition.*
import java.lang.String.*
import hudson.model.Descriptor;
import hudson.tasks.Builder;

def jenkinsInstance = jenkins.model.Jenkins.instance

def templateJobName = 'profile_p25'

def templateJob = jenkinsInstance.getJob(templateJobName)

 // get MultiJob BuildPhases and clone each PhaseJob
 builders = templateJob.getBuilders();

builders.each { b ->
if (b instanceof MultiJobBuilder){
def pj = b.getPhaseJobs()

   hudson.model.Describable p1 = new PhaseJobsConfig("p25_deploy-1",null,
        true,PhaseJobsConfig.KillPhaseOnJobResultCondition NEVER,null,false,false,null,0,false,true,null,false,false)
   pj.add(p1)
   }
 }

    templateJob.save()
   // update dependencies
    jenkinsInstance.rebuildDependencyGraph()

Any help will be really appreciated. Have tried many ways but was not able to figure out the problem with the script.

We can use DSL to create but I wanted it to be done in Groovy Scripting and moreover modify the existing job.

Blockquote

Body:
Yay! I am back with the answer for my question. Have tried this since very long time. Finally am able to make it though. I was aware that solution would be really simple but not able to figure out the hack of it.

import jenkins.model.*
import hudson.model.*
import com.tikal.jenkins.plugins.multijob.*
import com.tikal.jenkins.plugins.multijob.PhaseJobsConfig.*
import com.tikal.jenkins.plugins.multijob.PhaseJobsConfig.KillPhaseOnJobResultCondition.*
import java.lang.String.*
import hudson.model.Descriptor
import hudson.tasks.Builder

def jenkinsInstance = jenkins.model.Jenkins.instance

def templateJobName = 'profile_p25'

def templateJob = jenkinsInstance.getJob(templateJobName)

// get MultiJob BuildPhases and clone each PhaseJob
builders = templateJob.getBuilders();

builders.each { b -> if (b instanceof MultiJobBuilder)
    { def pj =
        b.getPhaseJobs()

        hudson.model.Describable newphase = new
        PhaseJobsConfig(deploys[i],null,
            true,null,null,false,false,null,0,false,false,"",false,false)
            newphase.killPhaseOnJobResultCondition = 'NEVER'
            pj.add(newphase)
    }
}
templateJob.save()

ContentLicense: CC BY-SA 4.0


问:
React Navigation: 'navigation.state.params' is always undefined in 'static navigationOptions'
The heart of my problem is that when I have this in my navigationOptions:

```<code>static navigationOptions = ({ navigation }) => {
    console.log(navigation)
    console.log(navigation.state)
}
</code>```

The first 'console.log' statement returns the navigation object complete with "navigation.state.params" containing the params that I have passed into it.

However, the second 'console.log' returns the 'navigation.state' object but for some reason the 'params' are undefined.

Here is how I am setting the navigation params (from redux):

```<code>function mapStateToProps(state, props) {
    let sum = 0
    for (let product in state.cart) {
        sum += state.cart[product]
    }
    return props.navigation.state = {params: {cartSum: sum}}
}
</code>```

And my developer environment:

node         6.10.1

react-native 0.46.4

redux        3.7.1

react-redux  5.0.5

react-navigation 1.0.0-beta.11

答:
It is possible to go around this issue by implementing a method in the component class.

```<code>getNavigationParams() {
        return this.props.navigation.state.params || {};
    }
</code>```

This will give you access to the parameters. But it does not work for nested objects.

Body:
The heart of my problem is that when I have this in my navigationOptions:

static navigationOptions = ({ navigation }) => {
    console.log(navigation)
    console.log(navigation.state)
}

The first 'console.log' statement returns the navigation object complete with "navigation.state.params" containing the params that I have passed into it.

However, the second 'console.log' returns the 'navigation.state' object but for some reason the 'params' are undefined.

Here is how I am setting the navigation params (from redux):

function mapStateToProps(state, props) {
    let sum = 0
    for (let product in state.cart) {
        sum += state.cart[product]
    }
    return props.navigation.state = {params: {cartSum: sum}}
}

And my developer environment:

node         6.10.1

react-native 0.46.4

redux        3.7.1

react-redux  5.0.5

react-navigation 1.0.0-beta.11

Body:
It is possible to go around this issue by implementing a method in the component class.

getNavigationParams() {
        return this.props.navigation.state.params || {};
    }

This will give you access to the parameters. But it does not work for nested objects.


问:
Creating SKScene, init(fileNamed:) vs init(size:)
If you make a new game template project in Xcode, the default GameViewController will use the following initializer to instantiate the game scene:

```<code>let scene = SKScene(fileNamed: "GameScene")
</code>```

The initializer's use in the template file suggests that this is Apple's recommended way for creating an SKScene. However, I have seen many examples on Stack Overflow that use the init(size:) initializer or simply SKScene().

I am wondering which is the best way to create an instance of SKScene and what are the advantages/disadvantages of each way, as well as various pitfalls to look out for when using one approach versus another.

My reason for asking is that I used init(fileNamed:) to create my game's scene and build level 1. When I later tried to create another instance of the scene for level 2 using init(size:), I ran into problems. Namely, some positional calculations using UIScreen and the scene's frame seem to produce different results if I create the scene using init(size:) instead of init(fileNamed:).

In a more general sense, I would like to hear the opinion of someone who is very familiar with using iOS and SpriteKit about their preferred way of initializing a new SKScene and the pros & cons of using different approaches.

答:
I very strongly recommend not using init(size:) when it comes to creating your scenes that you use as a part of your game.  You really should try to keep design separate from structure.  This allows for you to change how the layout of your game is, without changing any code, thus reducing the potential for bugs.

With that being said, there is a very common practice tutorials use that looks like this init(size:view.size).  This one causes all kinds of trouble with game designers, and destroys the simple handling of multiple devices that SpriteKit offers.  People tend to end up in a 0..1 coordinate system, placing divides everywhere when positioning their nodes, and this too leads to bugs because people may end up forgetting a divide somewhere, or using width when they meant height.

SKScenes have 4 scale modes that handle how a scene should look on every device, and it should always be taken into consideration when developing a game with this tool.  It really should be the first thing that gets discussed so that people can understand the power behind it.

The only time I would recommend using init(size:) is when you need to create a dynamic scene that cannot be achieved via the sprite kit builder, and when you already have a static size of the window established.

Body:
If you make a new game template project in Xcode, the default GameViewController will use the following initializer to instantiate the game scene:

let scene = SKScene(fileNamed: "GameScene")

The initializer's use in the template file suggests that this is Apple's recommended way for creating an SKScene. However, I have seen many examples on Stack Overflow that use the init(size:) initializer or simply SKScene().

I am wondering which is the best way to create an instance of SKScene and what are the advantages/disadvantages of each way, as well as various pitfalls to look out for when using one approach versus another.

My reason for asking is that I used init(fileNamed:) to create my game's scene and build level 1. When I later tried to create another instance of the scene for level 2 using init(size:), I ran into problems. Namely, some positional calculations using UIScreen and the scene's frame seem to produce different results if I create the scene using init(size:) instead of init(fileNamed:).

In a more general sense, I would like to hear the opinion of someone who is very familiar with using iOS and SpriteKit about their preferred way of initializing a new SKScene and the pros & cons of using different approaches.


问:
How can I populate the following objects in multiple input fields?
Please forgive me if the title is not very descriptive,
I'm using vibrant.js to get a picture's color HEX, everything is working as expected and i'm quite happy with everything so far,please help me / guide me on how to get the values in the input text fields, MUCH APPRECIATED!

<!DOCTYPE html>

    <meta charset="UTF-8">

How to get the console result in the input fields below?

1st
<input value="" id="1">

2nd
<input value="" id="2">

3rd
<input value="" id="3">

4th
<input value="" id="4">

5th
<input value="" id="5">

```
</div>
</div>
</p>

<p>My console perfectly returns </p>

``` * Vibrant #7a4426
 * Muted #7b9eae
 * DarkVibrant #348945
 * DarkMuted #141414
 * LightVibrant #f3ccb4
```

The main goal is to get the Color HEX into the input text field ( you can remove the color name bu removing (swatch,) in the console.log.

答:
You can try something like following</p>

```<code>for (var i=0; i< swatches.length; i++)
     if (swatches.hasOwnProperty(swatches[i]) && swatches[i]){
          document.getElementById(""+(i+1)).value = swatches[i].getHex();
          console.log(swatches[i], swatches[i].getHex())
        }
</code>```

Body:
Please forgive me if the title is not very descriptive,
I'm using vibrant.js to get a picture's color HEX, everything is working as expected and i'm quite happy with everything so far,please help me / guide me on how to get the values in the input text fields, MUCH APPRECIATED!

<!DOCTYPE html>

    <meta charset="UTF-8">

How to get the console result in the input fields below?

1st
<input value="" id="1">

2nd
<input value="" id="2">

3rd
<input value="" id="3">

4th
<input value="" id="4">

5th
<input value="" id="5">

My console perfectly returns

 * Vibrant #7a4426
 * Muted #7b9eae
 * DarkVibrant #348945
 * DarkMuted #141414
 * LightVibrant #f3ccb4

The main goal is to get the Color HEX into the input text field ( you can remove the color name bu removing (swatch,) in the console.log.

Body:
You can try something like following

for (var i=0; i< swatches.length; i++)
     if (swatches.hasOwnProperty(swatches[i]) && swatches[i]){
          document.getElementById(""+(i+1)).value = swatches[i].getHex();
          console.log(swatches[i], swatches[i].getHex())
        }


问:
Output multiple commands into columns
I'm trying to write a script which runs various commands and outputs the result of each command into one column but I'm not able to get the output ot be displayed in colums.

```<code>#!/bin/bash

# Get GBP Neighbour NAMES
NEIGHBOR=$(vtysh -c 'show ip bgp neighbors' | grep Incoming | awk '{print $7}')

# Get IPs of BGP neighbours
IP=$(vtysh -c 'show ip bgp summary' | awk '{print $1}' | head -n -2 | tail -n +6)

# Get Up/Down time
TIME=$(vtysh -c 'show ip bgp summary' | awk '{print $9}' | head -n -2 | tail -n +6)

# Get State/PfxRcd
STATE=$(vtysh -c 'show ip bgp summary' | awk '{print $10}' | head -n -2 | tail -n +6)
</code>```

How can I get the output to be separated in columns such as:

```<code>NEIGHBOR | IP | TIME | STATE
</code>```

答:
With paste command:

```<code>paste -d'|' <(echo "$NEIGHBOR ") <(echo "$IP") <(echo "$TIME") <(echo "$STATE")
</code>```

Title: Output multiple commands into columns

Body:
I'm trying to write a script which runs various commands and outputs the result of each command into one column but I'm not able to get the output ot be displayed in colums.

#!/bin/bash

# Get GBP Neighbour NAMES
NEIGHBOR=$(vtysh -c 'show ip bgp neighbors' | grep Incoming | awk '{print $7}')

# Get IPs of BGP neighbours
IP=$(vtysh -c 'show ip bgp summary' | awk '{print $1}' | head -n -2 | tail -n +6)

# Get Up/Down time
TIME=$(vtysh -c 'show ip bgp summary' | awk '{print $9}' | head -n -2 | tail -n +6)

# Get State/PfxRcd
STATE=$(vtysh -c 'show ip bgp summary' | awk '{print $10}' | head -n -2 | tail -n +6)

How can I get the output to be separated in columns such as:

NEIGHBOR | IP | TIME | STATE

Body:
With paste command:

paste -d'|' <(echo "$NEIGHBOR ") <(echo "$IP") <(echo "$TIME") <(echo "$STATE")


问:
Derby jpa select MAX()
I have a little problem with my query.
Here my table
And I want this rows

But I only get one row

Here my query :

```<code>        Query q = em.createQuery("SELECT OBJECT(historic) FROM Historic historic WHERE historic.user.id = :user_id AND historic.enchere.id = historic.enchere.id AND historic.limcoins = (SELECT MAX(historic.limcoins) FROM Historic historic WHERE historic.enchere.id = historic.enchere.id AND historic.state LIKE :state)");
        q.setParameter("user_id", user_id);
        q.setParameter("state", "none");
        List<Historic> list = q.getResultList();
</code>```

答:
Okay I found.

Replace the = oprator by IN

```<code>historic.limcoins IN (SELECT MAX(historic.limcoins) FROM Historic historic WHERE historic.enchere.id = historic.enchere.id AND historic.state LIKE :state)
</code>```

Title: Derby jpa select MAX()

Body:
I have a little problem with my query.
Here my table
And I want this rows

But I only get one row

Here my query :

        Query q = em.createQuery("SELECT OBJECT(historic) FROM Historic historic WHERE historic.user.id = :user_id AND historic.enchere.id = historic.enchere.id AND historic.limcoins = (SELECT MAX(historic.limcoins) FROM Historic historic WHERE historic.enchere.id = historic.enchere.id AND historic.state LIKE :state)");
        q.setParameter("user_id", user_id);
        q.setParameter("state", "none");
        List<Historic> list = q.getResultList();

Body:
Okay I found.

Replace the = oprator by IN

historic.limcoins IN (SELECT MAX(historic.limcoins) FROM Historic historic WHERE historic.enchere.id = historic.enchere.id AND historic.state LIKE :state)


问:
Has anyone been successful in using 64-bit Eclipse for Android 2.3 dev on 64-bit Windows 7?
Has anyone been successful in using 64-bit Eclipse for Android 2.3 dev on 64-bit Windows 7?

Please answer positively only if, when you invoke the emulator via Eclipse's Run (Ctrl+F11), your app-to-be-debugged's APK is installed automatically onto the Android emulator and you are running this same exact configuration:

Windows 7 Ultimate 64-bit.

JDK 64-bit (jdk-6u23-windows-x64.exe installed.)

JDK 32-bit (jdk-6u23-windows-i586.exe installed.)

Eclipse Classic 3.6 64-bit (eclipse-SDK-3.6.1-win32-x86_64.zip)

Android 2.3 SDK Starter Package

If you are able to fully use 64-bit Eclipse for Android 2.3 dev on 64-bit Windows 7, please describe the steps you performed to make this happen.

As of now, the following steps did NOT work for me:

install the 64-bit JDK

install the 32-bit JDK

unzip android-sdk_r08-windows.zip to
C:\android-sdk-windows

append C:\android-sdk-windows\tools
to %PATH% in System env vars.

Run C:\android-sdk-windows\tools>android.bat

Install ADT Plugin via Eclipse

Create "Android 2.3 - API Level 9" virtual device via Eclipse

Window > Preferences > Java > Installed JREs: [Search...]

答:
I myself have never used the Eclipse "classic" version, I always get the Java version as another poster mentioned (the 64bit version). Personally no idea what the difference is. I am guessing this is where your problem may stem from?

It works perfectly on Windows 7 x64 (Home Premium here), 64-bit and 32-bit JDKs installed, latest Android SDK and ADT plugin. I'm not sure which JRE is actually used, never bothered to find out (wouldn't be surprised if its 32bit). Also the JDK versions I used (quite awhile back) were 6u21, since then my 32bit version has updated to 6u23 but 64bit has not. Couldn't tell you the exact order as I don't recall (it was quite awhile back). Likely I installed the JDKs first, then extracted Eclipse, install/downloaded Android SDK, then installed ADT plugin.

Has always started up emulator fine, installs APKs, and debugs as expected. I also do alot of dev'ing on my Nexus One.

One recommendation I have seen alot is NEVER install any of the tools to the typical "C:\Program Files" because of spaces in filepaths. Why this is still a problem in 2011 I will not know, but putting Eclipse, JDK, and the Android SDK all straight off the root of some drive is likely to lead to significantly less issues apparently.

Edit: I uninstalled my current versions of Java, and removed eclipse/android sdk to startover

Installed jdk-6u23-windows-x64.exe to C:\Java

Added JAVA_HOME env variable pointing to C:\Java\jdk1.6.0_23

Added Java bin dir to PATH env var ;C:\Java\jdk1.6.0_23\bin

Extracted eclipse-java-helios-SR1-win32-x86_64.zip to C:\eclipse

Installed installer_r09-windows.exe to C:\android-sdk-windows

Downloaded necessary SDK versions

Installed ADT plugin through Eclipse interface, point to android SDK dir

Added ANDROID_HOME env variable pointing to C:\android-sdk-windows

Added Android platform-tools dir to PATH env var ;C:\android-sdk-windows\platform-tools

After this everything seems to work fine (except for DDMS in Eclipse, still fidgeting with that). And that is without the 32bit version of Java installed (neither JRE or JDK). Only 64bit is installed.

ContentLicense: CC BY-SA 2.5


问:
How Do I collapse rows on null values in t-sql?
I'm in a weird situation with my query. My objective is to display the total deposits and withdrawals from multiple transactions for each person and display them. I am getting multiple rows that I need to collapse into one. This all needs to happen in one query

```<code>SELECT
       lastname,
       firsname,
       case when upper(category) = 'W' then sum(abs(principal)) end as Withdrawal,
       case when upper(category) = 'D' then sum(abs(principal)) end as Deposit,
       description
FROM
       table1
       JOIN table2 ON table1.id = table2.id
       JOIN table3 ON table2.c = table3.c
WHERE
       description = 'string'
GROUP BY
       lastname,
       firstname,
       description,
       category
</code>```

my result is

```<code> lastname    firstname    Withdrawal    Deposit    description
 john         smith       null           140.34    string
 john         smith       346.00          null     string
 jane         doe         null           68.03     string
 jane         doe         504.00          null     string
</code>```

and I am looking for

```<code> lastname    firstname    Withdrawal    Deposit    description
 john         smith       346.00        140.34     string
 jane         doe         504.00        68.03      string
</code>```

adding principal into the group does not work. any help on solving this will be greatly appreciated!

答:
Try this: </p>

```<code>SELECT lastname,firsname,
       SUM(case when upper(category) = 'W' then abs(principal) end) as Withdrawal,
       SUM(case when upper(category) = 'D' then abs(principal) end) as Deposit,
       description
FROM
       table1
       JOIN table2 ON table1.id = table2.id
       JOIN table3 ON table2.c = table3.c
WHERE
       description = 'string'
GROUP BY
lastname,firstname,description
</code>```

Body:
I'm in a weird situation with my query. My objective is to display the total deposits and withdrawals from multiple transactions for each person and display them. I am getting multiple rows that I need to collapse into one. This all needs to happen in one query

SELECT
       lastname,
       firsname,
       case when upper(category) = 'W' then sum(abs(principal)) end as Withdrawal,
       case when upper(category) = 'D' then sum(abs(principal)) end as Deposit,
       description
FROM
       table1
       JOIN table2 ON table1.id = table2.id
       JOIN table3 ON table2.c = table3.c
WHERE
       description = 'string'
GROUP BY
       lastname,
       firstname,
       description,
       category

my result is

 lastname    firstname    Withdrawal    Deposit    description
 john         smith       null           140.34    string
 john         smith       346.00          null     string
 jane         doe         null           68.03     string
 jane         doe         504.00          null     string

and I am looking for

 lastname    firstname    Withdrawal    Deposit    description
 john         smith       346.00        140.34     string
 jane         doe         504.00        68.03      string

adding principal into the group does not work. any help on solving this will be greatly appreciated!

Body:
Try this:

SELECT lastname,firsname,
       SUM(case when upper(category) = 'W' then abs(principal) end) as Withdrawal,
       SUM(case when upper(category) = 'D' then abs(principal) end) as Deposit,
       description
FROM
       table1
       JOIN table2 ON table1.id = table2.id
       JOIN table3 ON table2.c = table3.c
WHERE
       description = 'string'
GROUP BY
lastname,firstname,description


问:
ArrayIndexOutOfBoundsException when populating RecyclerView
I am getting an error every so often when I try to populate my RecyclerView but the error seems to happening internally in the StaggeredGridLayoutManager.

I populate the RecyclerView from my database then add the images to my adapter using this

```<code>List<WImage> images;

public void addImages(LinkedHashMap<Integer,WImage> newImages){
    for(Map.Entry<Integer,WImage> entry : newImages.entrySet()){
        addImage(entry.getValue(),entry.getKey());
    }
}

public void addImage(WImage image, int position){
    images.add(position,image);
    notifyItemRangeInserted(position, 1);

}
</code>```

What is weird is when the app first loads it is fine and displays everything correctly but if I replace what was currently in the RecyclerView with a different set of images based on a database query then come back with the initial images again I get this error.

```<code>java.lang.ArrayIndexOutOfBoundsException: src.length=16 srcPos=0 dst.length=0 dstPos=0 length=16
            at java.lang.System.arraycopy(Native Method)
            at android.support.v7.widget.StaggeredGridLayoutManager$LazySpanLookup.ensureSize(StaggeredGridLayoutManager.java:2277)
            at android.support.v7.widget.StaggeredGridLayoutManager$LazySpanLookup.offsetForAddition(StaggeredGridLayoutManager.java:2323)
            at android.support.v7.widget.StaggeredGridLayoutManager.handleUpdate(StaggeredGridLayoutManager.java:1280)
            at android.support.v7.widget.StaggeredGridLayoutManager.onItemsAdded(StaggeredGridLayoutManager.java:1253)
            at android.support.v7.widget.RecyclerView$5.dispatchUpdate(RecyclerView.java:406)
            at android.support.v7.widget.RecyclerView$5.onDispatchSecondPass(RecyclerView.java:422)
            at android.support.v7.widget.AdapterHelper.consumePostponedUpdates(AdapterHelper.java:119)
            at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:1896)
            at android.support.v7.widget.RecyclerView.resumeRequestLayout(RecyclerView.java:1101)
            at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:155)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
            at android.view.Choreographer.doCallbacks(Choreographer.java:574)
            at android.view.Choreographer.doFrame(Choreographer.java:543)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5086)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)
</code>```

it goes through all the images just fine but when its ready to call onBindViewHolder again it crashes.

When I change the data in the RecyclerView I remove everything first with this before populating with the new data from the query

```<code>public void removeAll(){
    images.clear();
    notifyDataSetChanged();
}
</code>```

I also tried inserting them all at once and then calling notifyItemRangeInserted with the start position and the total number of images but it still crashsed with the same error.

EDIT

it seems to happen when I hit about 20 or so items that I need to put into the Grid. If I just use notifyDatasetChanged it seems to work fine but I want to use notifyItemRangeInserted so I get the nice insert animation

Has anyone else seen this problem?

EDIT2

here is my onCreateViewHolder

```<code>@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, final int i) {

    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.image_normal_grid_cell, viewGroup, false);
    return new ViewHolder(v);
}
</code>```

and my onBindViewHolder

```<code>@Override
public void onBindViewHolder(final ViewHolder holder, final int i) {
    final WImage image = images.get(i);
    holder.v.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            listener.onItemClick(v,i,image);
        }
    });

    holder.heart.setActivated(image.getLikeDislike());

    holder.heart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Uri.Builder ub = SyncProvider.CONTENT_ID_URI_BASE.buildUpon();
            ub.appendPath(String.valueOf(image.getId()));
            ContentValues values = new ContentValues();

            if(image.getLikeDislike()){
                values.put(SyncProvider.LIKE,0);
                holder.heart.setActivated(false);
                image.setLikeDislike(false);
            }else{
                values.put(SyncProvider.LIKE,1);
                holder.heart.setActivated(true);
                image.setLikeDislike(true);
            }
            values.put(SyncProvider.IMAGE_CHANGED,1);
            context.getContentResolver().update(ub.build(),values,null,null);
        }
    });
    if(cancelPotentialDownload(image.getUri(),holder.imageview)){
        LoadImageTask task = new LoadImageTask(holder.imageview,image.getThumbUri());
        holder.imageview.setImageDrawable(new AsyncBitmap(task));
        task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }
}
</code>```

EDIT 3

here is what I do when I replace the adapter

on selected index change of my nav drawer I init my loader to make a query

```<code>public void initLoader(int page){
    if(currentPage != page && mAdapter != null){
        mAdapter.removeAll();
        hashImages.clear();
        getLoaderManager().destroyLoader(currentPage);
    }
    currentPage = page;
    getLoaderManager().initLoader(page,null,this);
}
</code>```

then in my onLoadFinished of my loader I add the objects to the adapter

```<code>@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
    if(cursor != null && cursor.moveToFirst()){
            do{
                WImage image = new WImage(cursor);
                if(!hashImages.containsKey(image.getId())){
                    newImages.put(tempHash.size(),image);
                }else if(image.getImageChanged()){
                    update = true;
                }
                int pos = tempHash.size();
                tempHash.put(image.getId(),pos);
            }while(cursor.moveToNext());
        }

    if(newImages.size() > 0){
            mAdapter.addImages(newImages);
        }
</code>```

答:
This crash happen when you try to notifyDataSetChanged/notifyItemRemoved/Added/change while RecyclerView  isComputingLayout

This case may happen if you have some custom logic to change adapter
  contents in response to a View callback

In these cases, you should just postpone the change using a Handler

DON'T notify change until RecyclerView.isComputingLayout() return false.

```<code> /**
     * Returns whether RecyclerView is currently computing a layout.
     * <p>
     * If this method returns true, it means that RecyclerView is in a lockdown state and any
     * attempt to update adapter contents will result in an exception because adapter contents
     * cannot be changed while RecyclerView is trying to compute the layout.
     * <p>
     * It is very unlikely that your code will be running during this state as it is
     * called by the framework when a layout traversal happens or RecyclerView starts to scroll
     * in response to system events (touch, accessibility etc).
     * <p>
     * This case may happen if you have some custom logic to change adapter contents in
     * response to a View callback (e.g. focus change callback) which might be triggered during a
     * layout calculation. In these cases, you should just postpone the change using a Handler or a
     * similar mechanism.
     *
     * @return <code>true</code> if RecyclerView is currently computing a layout, <code>false</code>
     *         otherwise
     */
    public boolean isComputingLayout() {
        return mLayoutOrScrollCounter > 0;
    }
</code>```

Body:
I am getting an error every so often when I try to populate my RecyclerView but the error seems to happening internally in the StaggeredGridLayoutManager.

I populate the RecyclerView from my database then add the images to my adapter using this

List<WImage> images;

public void addImages(LinkedHashMap<Integer,WImage> newImages){
    for(Map.Entry<Integer,WImage> entry : newImages.entrySet()){
        addImage(entry.getValue(),entry.getKey());
    }
}

public void addImage(WImage image, int position){
    images.add(position,image);
    notifyItemRangeInserted(position, 1);

}

What is weird is when the app first loads it is fine and displays everything correctly but if I replace what was currently in the RecyclerView with a different set of images based on a database query then come back with the initial images again I get this error.

java.lang.ArrayIndexOutOfBoundsException: src.length=16 srcPos=0 dst.length=0 dstPos=0 length=16
            at java.lang.System.arraycopy(Native Method)
            at android.support.v7.widget.StaggeredGridLayoutManager$LazySpanLookup.ensureSize(StaggeredGridLayoutManager.java:2277)
            at android.support.v7.widget.StaggeredGridLayoutManager$LazySpanLookup.offsetForAddition(StaggeredGridLayoutManager.java:2323)
            at android.support.v7.widget.StaggeredGridLayoutManager.handleUpdate(StaggeredGridLayoutManager.java:1280)
            at android.support.v7.widget.StaggeredGridLayoutManager.onItemsAdded(StaggeredGridLayoutManager.java:1253)
            at android.support.v7.widget.RecyclerView$5.dispatchUpdate(RecyclerView.java:406)
            at android.support.v7.widget.RecyclerView$5.onDispatchSecondPass(RecyclerView.java:422)
            at android.support.v7.widget.AdapterHelper.consumePostponedUpdates(AdapterHelper.java:119)
            at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:1896)
            at android.support.v7.widget.RecyclerView.resumeRequestLayout(RecyclerView.java:1101)
            at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:155)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
            at android.view.Choreographer.doCallbacks(Choreographer.java:574)
            at android.view.Choreographer.doFrame(Choreographer.java:543)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5086)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)

it goes through all the images just fine but when its ready to call onBindViewHolder again it crashes.

When I change the data in the RecyclerView I remove everything first with this before populating with the new data from the query

public void removeAll(){
    images.clear();
    notifyDataSetChanged();
}

I also tried inserting them all at once and then calling notifyItemRangeInserted with the start position and the total number of images but it still crashsed with the same error.

EDIT

it seems to happen when I hit about 20 or so items that I need to put into the Grid. If I just use notifyDatasetChanged it seems to work fine but I want to use notifyItemRangeInserted so I get the nice insert animation

Has anyone else seen this problem?

EDIT2

here is my onCreateViewHolder

@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, final int i) {

    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.image_normal_grid_cell, viewGroup, false);
    return new ViewHolder(v);
}

and my onBindViewHolder

@Override
public void onBindViewHolder(final ViewHolder holder, final int i) {
    final WImage image = images.get(i);
    holder.v.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            listener.onItemClick(v,i,image);
        }
    });

    holder.heart.setActivated(image.getLikeDislike());

    holder.heart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Uri.Builder ub = SyncProvider.CONTENT_ID_URI_BASE.buildUpon();
            ub.appendPath(String.valueOf(image.getId()));
            ContentValues values = new ContentValues();

            if(image.getLikeDislike()){
                values.put(SyncProvider.LIKE,0);
                holder.heart.setActivated(false);
                image.setLikeDislike(false);
            }else{
                values.put(SyncProvider.LIKE,1);
                holder.heart.setActivated(true);
                image.setLikeDislike(true);
            }
            values.put(SyncProvider.IMAGE_CHANGED,1);
            context.getContentResolver().update(ub.build(),values,null,null);
        }
    });
    if(cancelPotentialDownload(image.getUri(),holder.imageview)){
        LoadImageTask task = new LoadImageTask(holder.imageview,image.getThumbUri());
        holder.imageview.setImageDrawable(new AsyncBitmap(task));
        task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }
}

EDIT 3

here is what I do when I replace the adapter

on selected index change of my nav drawer I init my loader to make a query

public void initLoader(int page){
    if(currentPage != page && mAdapter != null){
        mAdapter.removeAll();
        hashImages.clear();
        getLoaderManager().destroyLoader(currentPage);
    }
    currentPage = page;
    getLoaderManager().initLoader(page,null,this);
}

then in my onLoadFinished of my loader I add the objects to the adapter

@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
    if(cursor != null && cursor.moveToFirst()){
            do{
                WImage image = new WImage(cursor);
                if(!hashImages.containsKey(image.getId())){
                    newImages.put(tempHash.size(),image);
                }else if(image.getImageChanged()){
                    update = true;
                }
                int pos = tempHash.size();
                tempHash.put(image.getId(),pos);
            }while(cursor.moveToNext());
        }

    if(newImages.size() > 0){
            mAdapter.addImages(newImages);
        }

Body:
This crash happen when you try to notifyDataSetChanged/notifyItemRemoved/Added/change while RecyclerView  isComputingLayout

This case may happen if you have some custom logic to change adapter
  contents in response to a View callback

In these cases, you should just postpone the change using a Handler

DON'T notify change until RecyclerView.isComputingLayout() return false.

 /**
     * Returns whether RecyclerView is currently computing a layout.
     * <p>
     * If this method returns true, it means that RecyclerView is in a lockdown state and any
     * attempt to update adapter contents will result in an exception because adapter contents
     * cannot be changed while RecyclerView is trying to compute the layout.
     * <p>
     * It is very unlikely that your code will be running during this state as it is
     * called by the framework when a layout traversal happens or RecyclerView starts to scroll
     * in response to system events (touch, accessibility etc).
     * <p>
     * This case may happen if you have some custom logic to change adapter contents in
     * response to a View callback (e.g. focus change callback) which might be triggered during a
     * layout calculation. In these cases, you should just postpone the change using a Handler or a
     * similar mechanism.
     *
     * @return <code>true</code> if RecyclerView is currently computing a layout, <code>false</code>
     *         otherwise
     */
    public boolean isComputingLayout() {
        return mLayoutOrScrollCounter > 0;
    }


问:
Button in tableViewheader doesn't recognize header no. 0
I have this problem, hope you can help me out.

This is the code I have in viewForHeaderInSection :

```<code>let button = UIButton(frame: CGRect(x: view.frame.width - (cancel.frame.width + xImage.frame.width + 100), y: view.frame.origin.y, width: cancel.frame.width + xImage.frame.width + 120, height: view.frame.height))
button.backgroundColor = UIColor.blue.withAlphaComponent(0.5)
button.addTarget(self, action: #selector(action), for: .touchUpInside)
view.addSubview(button)
</code>```

and this is  action func:

```<code>@objc func action(sender: UIButton) {
    let position: CGPoint = sender.convert(CGPoint.zero, to: self.tableView)
    if let indexPath = self.tableView.indexPathForRow(at: position) {
        let section = indexPath.section
        print(section)
    }
}
</code>```

Now if I tap on every header except the first one (header 0) it prints the correct section.
How to make it to detect the header 0 too?

答:
If you want to know which is the button's section, you might assign the section to the button's tag, eg:

in your viewForHeaderInSection

```<code>func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
   let button = UIButton(frame: CGRect(x: view.frame.width - (cancel.frame.width + xImage.frame.width + 100), y: view.frame.origin.y, width: cancel.frame.width + xImage.frame.width + 120, height: view.frame.height))
   button.backgroundColor = UIColor.blue.withAlphaComponent(0.5)
   button.addTarget(self, action: #selector(action), for: .touchUpInside)
   view.addSubview(button)
   button.tag = section // this is the trick
}
</code>```

and then inside the action:

```<code>@objc func action(sender: UIButton) {
    let section = sender.tag
    print(section)
}
</code>```

Body:
I have this problem, hope you can help me out.

This is the code I have in viewForHeaderInSection :

let button = UIButton(frame: CGRect(x: view.frame.width - (cancel.frame.width + xImage.frame.width + 100), y: view.frame.origin.y, width: cancel.frame.width + xImage.frame.width + 120, height: view.frame.height))
button.backgroundColor = UIColor.blue.withAlphaComponent(0.5)
button.addTarget(self, action: #selector(action), for: .touchUpInside)
view.addSubview(button)

and this is  action func:

@objc func action(sender: UIButton) {
    let position: CGPoint = sender.convert(CGPoint.zero, to: self.tableView)
    if let indexPath = self.tableView.indexPathForRow(at: position) {
        let section = indexPath.section
        print(section)
    }
}

Now if I tap on every header except the first one (header 0) it prints the correct section.
How to make it to detect the header 0 too?

Body:
If you want to know which is the button's section, you might assign the section to the button's tag, eg:

in your viewForHeaderInSection

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
   let button = UIButton(frame: CGRect(x: view.frame.width - (cancel.frame.width + xImage.frame.width + 100), y: view.frame.origin.y, width: cancel.frame.width + xImage.frame.width + 120, height: view.frame.height))
   button.backgroundColor = UIColor.blue.withAlphaComponent(0.5)
   button.addTarget(self, action: #selector(action), for: .touchUpInside)
   view.addSubview(button)
   button.tag = section // this is the trick
}

and then inside the action:

@objc func action(sender: UIButton) {
    let section = sender.tag
    print(section)
}


问:
delete duplicate records without using common table expression (CTE)
I know how to delete duplicate records using CTE.

How can we achieve this without using CTE [Interview Question]

Is it possible?

Example: Table with the following data:

```<code>name     salary
-----------------
Husain   20000.00
Husain   20000.00
Husain   20000.00
Munavvar 50000.00
Munavvar 50000.00
</code>```

After deleting the duplicate records
table should contains data like this :

```<code>name     salary
-----------------
Husain   20000.00
Munavvar 50000.00
</code>```

答:
We can also Delete Duplicate Record from Table by Using Cursor or by using another lopping statements. following code spinets deletes Duplicates Record by using Cursor

```<code>  DECLARE @A nvarchar(50), @B nvarchar(50) , @C nvarchar(50), @TotalDuplicate INT ;

DECLARE a_cursor CURSOR FOR
SELECT A, B  ,C ,COUNT(1)-1 AS TotalDuplicate
FROM A
GROUP BY  A, B  ,C
HAVING COUNT(1)>1

OPEN a_cursor

FETCH NEXT FROM a_cursor INTO @A, @B,@C,@TotalDuplicate

WHILE @@FETCH_STATUS = 0
BEGIN

    DELETE TOP (@TotalDuplicate) FROM A WHERE A=@A AND B=@B AND C=@C

    FETCH NEXT FROM a_cursor INTO @A, @B,@C,@TotalDuplicate

END

CLOSE a_cursor;
DEALLOCATE a_cursor;
</code>```

Body:
I know how to delete duplicate records using CTE.

How can we achieve this without using CTE [Interview Question]

Is it possible?

Example: Table with the following data:

name     salary
-----------------
Husain   20000.00
Husain   20000.00
Husain   20000.00
Munavvar 50000.00
Munavvar 50000.00

After deleting the duplicate records
table should contains data like this :

name     salary
-----------------
Husain   20000.00
Munavvar 50000.00

Body:
We can also Delete Duplicate Record from Table by Using Cursor or by using another lopping statements. following code spinets deletes Duplicates Record by using Cursor

  DECLARE @A nvarchar(50), @B nvarchar(50) , @C nvarchar(50), @TotalDuplicate INT ;

DECLARE a_cursor CURSOR FOR
SELECT A, B  ,C ,COUNT(1)-1 AS TotalDuplicate
FROM A
GROUP BY  A, B  ,C
HAVING COUNT(1)>1

OPEN a_cursor

FETCH NEXT FROM a_cursor INTO @A, @B,@C,@TotalDuplicate

WHILE @@FETCH_STATUS = 0
BEGIN

    DELETE TOP (@TotalDuplicate) FROM A WHERE A=@A AND B=@B AND C=@C

    FETCH NEXT FROM a_cursor INTO @A, @B,@C,@TotalDuplicate

END

CLOSE a_cursor;
DEALLOCATE a_cursor;


问:
Mongo db $push operator not working
I am trying to push data in array in object in mongo model
 by using  req.params method
 but it is giving me
ERROR:

MongoError: cannot use the part (friends of friends.username) to traverse the element ( { friends:[ ] } )

Here's my Code:

BackEnd

```<code>  router.post('/accept/:id/:username',isLoggedIn,function(req,res){
              User.findOneAndUpdate({username:req.user.username,'friendRequest._id':req.params.id},
              {$set:{'friendRequest.$.Status':'Friend','friendRequest.$.Color':'green'}},function(err,founduser){

                if (err) {
                  throw err;
                } else {

               User.findOneAndUpdate({username:req.user.username},
               {$push:{'friends.username':req.params.username}}
               ,function(err,founduser){

                 if (err) {
                  throw err;
                } else {

//Error is coming from this line
                User.findOneAndUpdate({username:req.params.username},
                {$push:{'friends.username':req.user.username}}
                ,function(err,founduser){

                     if (err) {
                      throw err;
                    } else {
                        res.render("back");
                    }
                   })
                }
                   })
                }
              })
            })

**My Model**

            var  mongoose = require('mongoose');
            var passportLocalMongoose = require('passport-local-mongoose');

            var UserSchema = new mongoose.Schema({

            username:String,
            password :String,

              friends:[{
            username: String  //Here I wanna insert a data
            }],
</code>```

Front End

```<code><form  action = "/accept/<%=request._id%>/<%=request.username%>" method = "post">
         <button id="add" class="ui  medium  <%=request.Color%> button"><%=request.Status%></button>
         </form>
</code>```

答:
There a small change need to be made:</p>

```<code>       User.findOneAndUpdate({
                username: req.params.username
            }, {
                $push: {
                    "friends":{
                           username:req.params.username
                     }
                }
            },function(err,founduser){
                 if (err) {
                  throw err;
                } else {
                    res.render("back");
                }})
</code>```

Title: Mongo db $push operator not working

Body:
I am trying to push data in array in object in mongo model
 by using  req.params method
 but it is giving me
ERROR:

MongoError: cannot use the part (friends of friends.username) to traverse the element ( { friends:[ ] } )

Here's my Code:

BackEnd

  router.post('/accept/:id/:username',isLoggedIn,function(req,res){
              User.findOneAndUpdate({username:req.user.username,'friendRequest._id':req.params.id},
              {$set:{'friendRequest.$.Status':'Friend','friendRequest.$.Color':'green'}},function(err,founduser){

                if (err) {
                  throw err;
                } else {

               User.findOneAndUpdate({username:req.user.username},
               {$push:{'friends.username':req.params.username}}
               ,function(err,founduser){

                 if (err) {
                  throw err;
                } else {

//Error is coming from this line
                User.findOneAndUpdate({username:req.params.username},
                {$push:{'friends.username':req.user.username}}
                ,function(err,founduser){

                     if (err) {
                      throw err;
                    } else {
                        res.render("back");
                    }
                   })
                }
                   })
                }
              })
            })

**My Model**

            var  mongoose = require('mongoose');
            var passportLocalMongoose = require('passport-local-mongoose');

            var UserSchema = new mongoose.Schema({

            username:String,
            password :String,

              friends:[{
            username: String  //Here I wanna insert a data
            }],

Front End

<form  action = "/accept/<%=request._id%>/<%=request.username%>" method = "post">
         <button id="add" class="ui  medium  <%=request.Color%> button"><%=request.Status%></button>
         </form>

Body:
There a small change need to be made:

       User.findOneAndUpdate({
                username: req.params.username
            }, {
                $push: {
                    "friends":{
                           username:req.params.username
                     }
                }
            },function(err,founduser){
                 if (err) {
                  throw err;
                } else {
                    res.render("back");
                }})


问:
Java Spring Hibernate Saving Duplicate Values to MySQL table is throwing error
I am trying to save some values to a MYSQL database using CrudRepository but doesnt seem to work. I have tried the following guide https://spring.io/guides/gs/accessing-data-mysql/ and it works fine but when iam trying to follow the same principle for my program it doesnt seem to work for some reason.

Here is the class iam creating a database for, The table gets created properly:

```<code> @Entity
 public class MeasurementPoint {

 @Id

 @JsonProperty("f1")
 private double f1;

 @JsonProperty("precison")
 private double precison;

 @JsonProperty("recall")
 private double recall;

 private String date;

 public MeasurementPoint(double f1, double precison, double recall, String
 date)  {
     this.f1 = f1;
     this.precison = precison;
     this.recall = recall;
     this.date=date;
 }

 public double getF1() {
     return f1;
 }

 public double getPrecison() {
     return precison;
 }

 public String getDate() {
     return date;
 }
 public double getRecall() {
     return recall;
 }
}
</code>```

Here is the MSQL terminal outputting the columns for the entity created:

```<code>+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| f1       | double       | NO   | PRI | NULL    | auto_increment |
| date     | varchar(255) | YES  |     | NULL    |                |
| precison | double       | NO   |     | NULL    |                |
| recall   | double       | NO   |     | NULL    |                |
+----------+--------------+------+-----+---------+----------------+
</code>```

Here is the class iam trying to add values to the database from:

```<code>@Controller
public class DataChart {

private static final Logger logger= LoggerFactory.getLogger(DataChart.class);

@Autowired
private static MeasurementRepository measurementRepository;

@GetMapping(value = "/statementchart")
@ResponseBody
public List<Measurement> scoreChartData() {

    List<MeasurementPoint> needDataPoints = new ArrayList<>();
    List<MeasurementPoint> backgroundDataPoints = new ArrayList<>();
    List<MeasurementPoint> goalDataPoints=new ArrayList<>();
    needDataPoints.add(new MeasurementPoint(0.3, 0.5, 0.2,  "2017-11-19"));
    needDataPoints.add(new MeasurementPoint(0.7, 0.4, 0.15, "2017-11-12"));
    needDataPoints.add(new MeasurementPoint(0.5, 0.3, 0.10, "2017-11-15"));
    needDataPoints.add(new MeasurementPoint(0.6, 0.2, 0.05, "2017-11-18"));
    measurementRepository.save(needDataPoints);

    backgroundDataPoints.add(new MeasurementPoint(0.2, 0.4, 0.2, "2017-11-19"));
    backgroundDataPoints.add(new MeasurementPoint(0.4, 0.3, 0.15, "2017-11-12"));
    measurementRepository.save(backgroundDataPoints);
   //backgroundDataPoints.add(new MeasurementPoint(0.5, 0.2, 0.10, "2017-11-15"));
   //measurementRepository.save(backgroundDataPoints);
</code>```

Here is the output from saving these points:

```<code>+-----+------------+----------+--------+
| f1  | date       | precison | recall |
+-----+------------+----------+--------+
| 0.2 | 2017-11-19 |      0.4 |    0.2 |
| 0.3 | 2017-11-19 |      0.5 |    0.2 |
| 0.4 | 2017-11-12 |      0.3 |   0.15 |
| 0.5 | 2017-11-15 |      0.3 |    0.1 |
| 0.6 | 2017-11-18 |      0.2 |   0.05 |
| 0.7 | 2017-11-12 |      0.4 |   0.15 |
+-----+------------+----------+--------+
6 rows in set (0.00 sec)
</code>```

Here is my CrudRepository class:

```<code>public interface MeasurementRepository extends CrudRepository<MeasurementPoint,Long> {
}
</code>```

SOLVED

saving these points works fine but as soon i save that out-commented new MeasurementPoint

```<code>//backgroundDataPoints.add(new MeasurementPoint(0.5, 0.2, 0.10, "2017-11-15"));
//measurementRepository.save(backgroundDataPoints);
</code>```

i get a error saying: I guess it has to do with duplicate values but how do i fix this?

```<code>javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session :
</code>```

I solved it by creating a field of type long called id with annotation @Id because apparently every object created should get a unique id, the error thrown is because objects had some id. @GeneratedValue makes sure that everytime a new object is created a unqiue Id is given to that object.

```<code>    @Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;
</code>```

答:
I managed to solve it by removing @GeneratedValue(strategy=GenerationType.AUTO)
apparently and at the same time I was inserting id (any primary key value) by code too.
so the fix is: Do not insert id by code if using @GeneratedValue</p>

Body:
I am trying to save some values to a MYSQL database using CrudRepository but doesnt seem to work. I have tried the following guide https://spring.io/guides/gs/accessing-data-mysql/ and it works fine but when iam trying to follow the same principle for my program it doesnt seem to work for some reason.

Here is the class iam creating a database for, The table gets created properly:

 @Entity
 public class MeasurementPoint {

 @Id

 @JsonProperty("f1")
 private double f1;

 @JsonProperty("precison")
 private double precison;

 @JsonProperty("recall")
 private double recall;

 private String date;

 public MeasurementPoint(double f1, double precison, double recall, String
 date)  {
     this.f1 = f1;
     this.precison = precison;
     this.recall = recall;
     this.date=date;
 }

 public double getF1() {
     return f1;
 }

 public double getPrecison() {
     return precison;
 }

 public String getDate() {
     return date;
 }
 public double getRecall() {
     return recall;
 }
}

Here is the MSQL terminal outputting the columns for the entity created:

+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| f1       | double       | NO   | PRI | NULL    | auto_increment |
| date     | varchar(255) | YES  |     | NULL    |                |
| precison | double       | NO   |     | NULL    |                |
| recall   | double       | NO   |     | NULL    |                |
+----------+--------------+------+-----+---------+----------------+

Here is the class iam trying to add values to the database from:

@Controller
public class DataChart {

private static final Logger logger= LoggerFactory.getLogger(DataChart.class);

@Autowired
private static MeasurementRepository measurementRepository;

@GetMapping(value = "/statementchart")
@ResponseBody
public List<Measurement> scoreChartData() {

    List<MeasurementPoint> needDataPoints = new ArrayList<>();
    List<MeasurementPoint> backgroundDataPoints = new ArrayList<>();
    List<MeasurementPoint> goalDataPoints=new ArrayList<>();
    needDataPoints.add(new MeasurementPoint(0.3, 0.5, 0.2,  "2017-11-19"));
    needDataPoints.add(new MeasurementPoint(0.7, 0.4, 0.15, "2017-11-12"));
    needDataPoints.add(new MeasurementPoint(0.5, 0.3, 0.10, "2017-11-15"));
    needDataPoints.add(new MeasurementPoint(0.6, 0.2, 0.05, "2017-11-18"));
    measurementRepository.save(needDataPoints);

    backgroundDataPoints.add(new MeasurementPoint(0.2, 0.4, 0.2, "2017-11-19"));
    backgroundDataPoints.add(new MeasurementPoint(0.4, 0.3, 0.15, "2017-11-12"));
    measurementRepository.save(backgroundDataPoints);
   //backgroundDataPoints.add(new MeasurementPoint(0.5, 0.2, 0.10, "2017-11-15"));
   //measurementRepository.save(backgroundDataPoints);

Here is the output from saving these points:

+-----+------------+----------+--------+
| f1  | date       | precison | recall |
+-----+------------+----------+--------+
| 0.2 | 2017-11-19 |      0.4 |    0.2 |
| 0.3 | 2017-11-19 |      0.5 |    0.2 |
| 0.4 | 2017-11-12 |      0.3 |   0.15 |
| 0.5 | 2017-11-15 |      0.3 |    0.1 |
| 0.6 | 2017-11-18 |      0.2 |   0.05 |
| 0.7 | 2017-11-12 |      0.4 |   0.15 |
+-----+------------+----------+--------+
6 rows in set (0.00 sec)

Here is my CrudRepository class:

public interface MeasurementRepository extends CrudRepository<MeasurementPoint,Long> {
}

SOLVED

saving these points works fine but as soon i save that out-commented new MeasurementPoint

//backgroundDataPoints.add(new MeasurementPoint(0.5, 0.2, 0.10, "2017-11-15"));
//measurementRepository.save(backgroundDataPoints);

i get a error saying: I guess it has to do with duplicate values but how do i fix this?

javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session :

I solved it by creating a field of type long called id with annotation @Id because apparently every object created should get a unique id, the error thrown is because objects had some id. @GeneratedValue makes sure that everytime a new object is created a unqiue Id is given to that object.

    @Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;


问:
Yajra Relationship Call to undefined relationship [XXX_id] on model [App\XXX]
I get an error like below
Call to undefined relationship [hotel_id] on model [App\Room]

Model file Hotel.php

```<code>class Hotel extends Model {
    protected $primaryKey = 'id';
    protected $fillable   = ['hotel_name', 'hotel_area'];
    public function room() {
        return $this->hasMany('App\Room', 'hotel_id');
    }
}
</code>```

Model File Room.php

```<code>class Room extends Model {
    protected $primaryKey = 'id';
    protected $fillable   = ['hotel_id', 'room_name', 'bonus_sum'];
    public function hotel() {
        return $this->belongsTo('App\Hotel', 'hotel_id');
    }
}
</code>```

Controller File RoomController.php

```<code>public function apiRoom() {
        $rooms = Room::with('hotel');
        return Datatables::eloquent($rooms)
            ->addColumn('action', function ($rooms) {
                return '<a onclick="editForm('.$rooms->id.')" data-toggle="tooltip" data-original-title="Edit"> <i class="fa fa-pencil text-inverse m-r-10"></i> </a>'.
                '<a onclick="deleteData('.$rooms->id.')" data-toggle="tooltip" data-original-title="Close"> <i class="fa fa-close text-danger"></i> </a>';
            })
            ->escapeColumns()
            ->toJson();
</code>```

Route file web.php

```<code>Route::get('rooms-list', 'RoomController@list');
Route::resource('room', 'RoomController', [
        'except' => ['create']
    ]);
Route::get('api/room', 'RoomController@apiRoom')->name('api.room');
</code>```

Migrate create_new_room

```<code>$table->increments('id');
$table->integer('hotel_id')->unsigned();
        $table->foreign('hotel_id')->references('id')->on('hotels')->onDelete('cascade');
$table->string('room_name');
$table->string('bonus_sum');
$table->timestamps();
</code>```

View File

```<code>$('#room-table').DataTable({
  processing: true,
  serverSide: true,
  ajax: "{{ route('api.room') }}",
  columns: [
    {data: 'id', name: 'id'},
    {data: 'hotel.hotel_name', name: 'hotel.hotel_name'},
    {data: 'room_name', name: 'room_name'},
    {data: 'bonus_sum', name: 'bonus_sum'},
    {data: 'action', name: 'action', orderable: false, searchable: false}
  ]
});
</code>```

It's not related to the database. There is probably an error in the ajax file.

答:
Your hasMany has been defined incorrectly in your Hotel class.

Per the API documentation here, you need to pass an instance of the Room class through.

```<code>public function room() {
    return $this->hasMany(App\Room::class, 'hotel_id');
    // OR
    return $this->hasMany('App\Room', 'hotel_id');
}
</code>```

Same applies your Room class.

```<code>public function hotel() {
    return $this->belongsTo(App\Hotel::class, 'hotel_id');
    // OR
    return $this->belongsTo('App\Hotel', 'hotel_id');
}
</code>```

-- EDIT --

On the comment, the belongsTo function has the definition:

belongsTo($related, $foreignKey = null, $ownerKey = null, $relation = null)

For your hotel() relationship on the Room class to work, you need to pass the related models key as the second parameter. You should write it like this:

```<code>public function hotel() {
    return $this->belongsTo('App\Hotel', 'id', 'hotel_id');
}
</code>```

Body:
I get an error like below
Call to undefined relationship [hotel_id] on model [App\Room]

Model file Hotel.php

class Hotel extends Model {
    protected $primaryKey = 'id';
    protected $fillable   = ['hotel_name', 'hotel_area'];
    public function room() {
        return $this->hasMany('App\Room', 'hotel_id');
    }
}

Model File Room.php

class Room extends Model {
    protected $primaryKey = 'id';
    protected $fillable   = ['hotel_id', 'room_name', 'bonus_sum'];
    public function hotel() {
        return $this->belongsTo('App\Hotel', 'hotel_id');
    }
}

Controller File RoomController.php

public function apiRoom() {
        $rooms = Room::with('hotel');
        return Datatables::eloquent($rooms)
            ->addColumn('action', function ($rooms) {
                return 'id.')" data-toggle="tooltip" data-original-title="Edit">  '.
                'id.')" data-toggle="tooltip" data-original-title="Close">  ';
            })
            ->escapeColumns()
            ->toJson();

Route file web.php

Route::get('rooms-list', 'RoomController@list');
Route::resource('room', 'RoomController', [
        'except' => ['create']
    ]);
Route::get('api/room', 'RoomController@apiRoom')->name('api.room');

Migrate create_new_room

$table->increments('id');
$table->integer('hotel_id')->unsigned();
        $table->foreign('hotel_id')->references('id')->on('hotels')->onDelete('cascade');
$table->string('room_name');
$table->string('bonus_sum');
$table->timestamps();

View File

$('#room-table').DataTable({
  processing: true,
  serverSide: true,
  ajax: "{{ route('api.room') }}",
  columns: [
    {data: 'id', name: 'id'},
    {data: 'hotel.hotel_name', name: 'hotel.hotel_name'},
    {data: 'room_name', name: 'room_name'},
    {data: 'bonus_sum', name: 'bonus_sum'},
    {data: 'action', name: 'action', orderable: false, searchable: false}
  ]
});

It's not related to the database. There is probably an error in the ajax file.

Body:
Your hasMany has been defined incorrectly in your Hotel class.

Per the API documentation here, you need to pass an instance of the Room class through.

public function room() {
    return $this->hasMany(App\Room::class, 'hotel_id');
    // OR
    return $this->hasMany('App\Room', 'hotel_id');
}

Same applies your Room class.

public function hotel() {
    return $this->belongsTo(App\Hotel::class, 'hotel_id');
    // OR
    return $this->belongsTo('App\Hotel', 'hotel_id');
}

-- EDIT --

On the comment, the belongsTo function has the definition:

belongsTo($related, $foreignKey = null, $ownerKey = null, $relation = null)

For your hotel() relationship on the Room class to work, you need to pass the related models key as the second parameter. You should write it like this:

public function hotel() {
    return $this->belongsTo('App\Hotel', 'id', 'hotel_id');
}


问:
Does interface has to be explicitly defined?
I am new to C# and I am looking at dependency injection

```<code> private IDataContextFactory DataContextFactory { get; set; }
</code>```

How does the compiler know that this property is interface?

答:
The compiler knows that property DataContextFactory is IDataContextFactory because that is what you typed in your class.

It then knows that IDataContextFactory is an interface IF (that is not in your listing) it is declared as

```<code>public interface IDataContextFactory{
// something here
}
</code>```

Body:
I am new to C# and I am looking at dependency injection

 private IDataContextFactory DataContextFactory { get; set; }

How does the compiler know that this property is interface?

Body:
The compiler knows that property DataContextFactory is IDataContextFactory because that is what you typed in your class.

It then knows that IDataContextFactory is an interface IF (that is not in your listing) it is declared as

public interface IDataContextFactory{
// something here
}


问:
Java: Adding/Subtracting Math.ulp() vs. Math.nextAfter()
I'm trying to understand floating point operations in Java in more detail. If I read the documentation correctly, the following holds for any given double x:

```<code>x - Math.ulp(x) == Math.nextAfter(x, Double.NEGATIVE_INFINITY);
x + Math.ulp(x) == Math.nextAfter(x, Double.POSITIVE_INFINITY);
</code>```

Question: Is this always the case or are there some exceptional cases in which results will differ?

答:
The immediate cases I'd think to check are 0, +infinity and -infinity and NaN:

```<code>static void check(double x) {
  double a, b;
  System.out.printf(
      "%9s %9s %23s %5s%n",
      x, a = x - Math.ulp(x), b = Math.nextAfter(x, Double.NEGATIVE_INFINITY), a == b);
  System.out.printf(
      "%9s %9s %23s %5s%n",
      x, a = x + Math.ulp(x), b = Math.nextAfter(x, Double.POSITIVE_INFINITY), a == b);
  System.out.println();
}

public static void main(String[] args) throws java.lang.Exception {
  check(0);
  check(Double.POSITIVE_INFINITY);
  check(Double.NEGATIVE_INFINITY);
  check(Double.NaN);
}
</code>```

Ideone demo

Output:

```<code>      0.0 -4.9E-324               -4.9E-324  true
      0.0  4.9E-324                4.9E-324  true

 Infinity       NaN  1.7976931348623157E308 false
 Infinity  Infinity                Infinity  true

-Infinity -Infinity               -Infinity  true
-Infinity       NaN -1.7976931348623157E308 false

      NaN       NaN                     NaN false
      NaN       NaN                     NaN false
</code>```

That the expressions aren't equal in the NaN case isn't surprising (by the definition of NaN); but these expressions also aren't true for +infinity and -infinity (see the last column).

This answer is not intended to provide an exhaustive list of problematic values, but rather to show that some problematic values do exist.

Body:
I'm trying to understand floating point operations in Java in more detail. If I read the documentation correctly, the following holds for any given double x:

x - Math.ulp(x) == Math.nextAfter(x, Double.NEGATIVE_INFINITY);
x + Math.ulp(x) == Math.nextAfter(x, Double.POSITIVE_INFINITY);

Question: Is this always the case or are there some exceptional cases in which results will differ?

Body:
The immediate cases I'd think to check are 0, +infinity and -infinity and NaN:

static void check(double x) {
  double a, b;
  System.out.printf(
      "%9s %9s %23s %5s%n",
      x, a = x - Math.ulp(x), b = Math.nextAfter(x, Double.NEGATIVE_INFINITY), a == b);
  System.out.printf(
      "%9s %9s %23s %5s%n",
      x, a = x + Math.ulp(x), b = Math.nextAfter(x, Double.POSITIVE_INFINITY), a == b);
  System.out.println();
}

public static void main(String[] args) throws java.lang.Exception {
  check(0);
  check(Double.POSITIVE_INFINITY);
  check(Double.NEGATIVE_INFINITY);
  check(Double.NaN);
}

Ideone demo

Output:

      0.0 -4.9E-324               -4.9E-324  true
      0.0  4.9E-324                4.9E-324  true

 Infinity       NaN  1.7976931348623157E308 false
 Infinity  Infinity                Infinity  true

-Infinity -Infinity               -Infinity  true
-Infinity       NaN -1.7976931348623157E308 false

      NaN       NaN                     NaN false
      NaN       NaN                     NaN false

That the expressions aren't equal in the NaN case isn't surprising (by the definition of NaN); but these expressions also aren't true for +infinity and -infinity (see the last column).

This answer is not intended to provide an exhaustive list of problematic values, but rather to show that some problematic values do exist.


问:
App_offline.htm, CSS, images, and aspnet_isapi.dll
So, the site I'm working on is using urlrewriting in coordination with aspnet_isapi.dll (everything is mapped to it). I put up my app_offline.htm file, and all the text shows, however, the CSS or images aren't being served. I'm guessing they're being processed by ASP.NET due to the wildcard mapping instead of IIS. Is this correct? If so, how can I allow IIS to serve these files? Furthermore, an issue I can see arising..in the web.config for the rewriter settings:

```<code><rewrite url="^~/images/network/(.*)/(.*).jpg$" to="~/services/ImageHandler.ashx?type=$1&id=$2"/>
    <rewrite url="^~/image/view/(.*).jpg$" to="~/ServePRView.aspx?id=$1"/>
    <rewrite url="^~/asset/view/(.*).jpg$" to="~/services/ImageHandler.ashx?id=$1&type=asset"/>
</code>```

Thanks for the help all,
-Steve

答:
@JeremyWeir is correct. IIS stops serving sub resources in the prescense of app_offline.htm A way around this is to embed the content in the page directly by using:

1) Encode Images inside Html
2) Internal Style Sheets
3) the same for your javascript

This isn't the easiest to maintain but it does give you control over the appearance of the content displayed on the page.

Body:
So, the site I'm working on is using urlrewriting in coordination with aspnet_isapi.dll (everything is mapped to it). I put up my app_offline.htm file, and all the text shows, however, the CSS or images aren't being served. I'm guessing they're being processed by ASP.NET due to the wildcard mapping instead of IIS. Is this correct? If so, how can I allow IIS to serve these files? Furthermore, an issue I can see arising..in the web.config for the rewriter settings:

<rewrite url="^~/images/network/(.*)/(.*).jpg$" to="~/services/ImageHandler.ashx?type=$1&id=$2"/>
    <rewrite url="^~/image/view/(.*).jpg$" to="~/ServePRView.aspx?id=$1"/>
    <rewrite url="^~/asset/view/(.*).jpg$" to="~/services/ImageHandler.ashx?id=$1&type=asset"/>

Thanks for the help all,
-Steve


问:
WPF Storyboard.Completed event is not immediate
In WPF, a Storyboard can be stopped by Storyboard.SkipToFill(), but the Completed event will not be fired immediately. Just as the following demo code showing:

```<code>public partial class MainWindow : Window
{
    private Storyboard _storyboard = new Storyboard();

    public MainWindow()
    {
        InitializeComponent();
        InitializeStoryboard();
    }

    private void InitializeStoryboard()
    {
        var animation = new DoubleAnimation
        {
            Duration = TimeSpan.FromSeconds(3),
            From = 0,
            To = 300
        };

        Storyboard.SetTarget(animation, MyRectangle);
        Storyboard.SetTargetProperty(animation, new PropertyPath(WidthProperty));

        _storyboard = new Storyboard();
        _storyboard.Children.Add(animation);

        _storyboard.Completed += StoryboardOnCompleted;
    }

    private void StartButton_OnClick(object sender, RoutedEventArgs e)
    {
        _storyboard.Begin(this, true);
    }

    private void StopButton_OnClick(object sender, RoutedEventArgs e)
    {
        _storyboard.SkipToFill(this);
        Debug.WriteLine(@"SkipToFill");
    }

    private void StoryboardOnCompleted(object sender, EventArgs eventArgs)
    {
        Debug.WriteLine(@"Completed");
    }
}
</code>```

Click the StartButton to begin the Storyboard, and then click the StopButton to stop it. The output will be:

SkipToFill

Completed

So, my question: How to make the Completed event fired immediately? i.e. to make the output be:

Completed

SkipToFill

答:
The SkipToFill method schedules an end of the animation. I suppose you could try to wait for the renderer to run (sort of). I doubt that it will work, but anyway:

```<code>_storyboard.SkipToFill(this);

Dispatcher.CurrentDispatcher.Invoke(
    new Action(delegate { }), DispatcherPriority.Background);

Debug.WriteLine(@"SkipToFill");
</code>```

Body:
In WPF, a Storyboard can be stopped by Storyboard.SkipToFill(), but the Completed event will not be fired immediately. Just as the following demo code showing:

public partial class MainWindow : Window
{
    private Storyboard _storyboard = new Storyboard();

    public MainWindow()
    {
        InitializeComponent();
        InitializeStoryboard();
    }

    private void InitializeStoryboard()
    {
        var animation = new DoubleAnimation
        {
            Duration = TimeSpan.FromSeconds(3),
            From = 0,
            To = 300
        };

        Storyboard.SetTarget(animation, MyRectangle);
        Storyboard.SetTargetProperty(animation, new PropertyPath(WidthProperty));

        _storyboard = new Storyboard();
        _storyboard.Children.Add(animation);

        _storyboard.Completed += StoryboardOnCompleted;
    }

    private void StartButton_OnClick(object sender, RoutedEventArgs e)
    {
        _storyboard.Begin(this, true);
    }

    private void StopButton_OnClick(object sender, RoutedEventArgs e)
    {
        _storyboard.SkipToFill(this);
        Debug.WriteLine(@"SkipToFill");
    }

    private void StoryboardOnCompleted(object sender, EventArgs eventArgs)
    {
        Debug.WriteLine(@"Completed");
    }
}

Click the StartButton to begin the Storyboard, and then click the StopButton to stop it. The output will be:

SkipToFill

Completed

So, my question: How to make the Completed event fired immediately? i.e. to make the output be:

Completed

SkipToFill

Body:
The SkipToFill method schedules an end of the animation. I suppose you could try to wait for the renderer to run (sort of). I doubt that it will work, but anyway:

_storyboard.SkipToFill(this);

Dispatcher.CurrentDispatcher.Invoke(
    new Action(delegate { }), DispatcherPriority.Background);

Debug.WriteLine(@"SkipToFill");


问:
Kotlin DialogFragment editText editable always null
So, I'm using Kotlin extensions which is straightforward, but I can't get string from edittext

here is my code:

```<code>override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {

    val v = activity.layoutInflater
            .inflate(R.layout.dialog_group, null)

    v.add_group_button.setOnClickListener(addListener)

    return AlertDialog.Builder(activity)
            .setView(v)
            .create()
}

private var addListener: View.OnClickListener = View.OnClickListener {

        val groupNameInput: String = view?.group_edit_text?.text.toString()

    }
</code>```

when I'm pressing add button groupNameInput always returns null why?

答:
So finally I figure it out — on Dialog Fragment view will always be null, because its never created, but it's created and added to dialog view which means I need to call:

```<code>dialog.group_edit_text.text.toString()
</code>```

Instead of:

```<code>view.group_edit_text.text.toString()
</code>```

Body:
So, I'm using Kotlin extensions which is straightforward, but I can't get string from edittext

here is my code:

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {

    val v = activity.layoutInflater
            .inflate(R.layout.dialog_group, null)

    v.add_group_button.setOnClickListener(addListener)

    return AlertDialog.Builder(activity)
            .setView(v)
            .create()
}

private var addListener: View.OnClickListener = View.OnClickListener {

        val groupNameInput: String = view?.group_edit_text?.text.toString()

    }

when I'm pressing add button groupNameInput always returns null why?

Body:
So finally I figure it out — on Dialog Fragment view will always be null, because its never created, but it's created and added to dialog view which means I need to call:

dialog.group_edit_text.text.toString()

Instead of:

view.group_edit_text.text.toString()


问:
Could not find com.github.scottyab:showhidepasswordedittext:0.6
I am trying to add this dependency
 com.github.scottyab:showhidepasswordedittext:0.6. in an android app. On building the project I am having this error critically

```<code>Error:A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugApkCopy'.
   > Could not find com.github.scottyab:showhidepasswordedittext:0.6.
     Required by:
         push:app:unspecified
</code>```

Please what am I doing wrong. Kindly assist

答:
latest version of dependency is :

```<code>dependencies {
    compile 'com.github.scottyab:showhidepasswordedittext:0.8'
}
</code>```

and don't forgot to add maven repo in the project-level build.gradle file

```<code>allprojects {
    repositories {
        maven {
            url "https://jitpack.io"
        }
    }
}
</code>```

for more information check here

Body:
I am trying to add this dependency
 com.github.scottyab:showhidepasswordedittext:0.6. in an android app. On building the project I am having this error critically

Error:A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugApkCopy'.
   > Could not find com.github.scottyab:showhidepasswordedittext:0.6.
     Required by:
         push:app:unspecified

Please what am I doing wrong. Kindly assist

Body:
latest version of dependency is :

dependencies {
    compile 'com.github.scottyab:showhidepasswordedittext:0.8'
}

and don't forgot to add maven repo in the project-level build.gradle file

allprojects {
    repositories {
        maven {
            url "https://jitpack.io"
        }
    }
}

for more information check here


问:
How to specify port of MySQL in Drupal?
I need to change the default port of MySQL from 3306 to something else (let us say 3300)

I have edited setting.php in sites/default.settings.php and changed

$db_url['default'] = 'mysqli://root:password@localhost/dbname'; TO

$db_url['default'] = 'mysqli://root:password@localhost:3300/dbname';

but this didn't work!
How can I change the default port?

答:
Have you tried clearing the cache? Drupal won't recognize the change if its pulling the data from elsewhere.

I think you can do it at yoursite.com/admin/settings/performance

Title: How to specify port of MySQL in Drupal?


问:
Select item by a maximum value and duplicates of this value present in List<Tuple>
Print top value and its  duplicate values present in List
Suppose List is ordered list.

```<code>List<Tuple<int, string, string>> result = new List<Tuple<int, string, string>> {
    {4, "am", "I am the One"}
    {4, "am" , "I am human"}
    {2, "one", "zero plus one is one"}
    {1, "is", "this is list"}
};
</code>```

Selected output should Top int value and its duplicate if present.

Top according to int values is : 4. Duplicates are 1st and 2nd entries of list.

Output:

```<code>4, am, I am the One
4, am , I am human
</code>```

Can anyone code to get max value and its duplicate?

答:
I think this will do it:

```<code>List<Tuple<int, string, string>> maxTuples =
    result.Where(r => r.Item1 == (result.Max(m => m.Item1))).ToList();
</code>```

You are getting the maximum value of Item1 (the int) and then finding all records that have the same value.

HTH, like mentioned in the comments previously good to post what you have tried in future.

Body:
Print top value and its  duplicate values present in List
Suppose List is ordered list.

List<Tuple<int, string, string>> result = new List<Tuple<int, string, string>> {
    {4, "am", "I am the One"}
    {4, "am" , "I am human"}
    {2, "one", "zero plus one is one"}
    {1, "is", "this is list"}
};

Selected output should Top int value and its duplicate if present.

Top according to int values is : 4. Duplicates are 1st and 2nd entries of list.

Output:

4, am, I am the One
4, am , I am human

Can anyone code to get max value and its duplicate?

Body:
I think this will do it:

List<Tuple<int, string, string>> maxTuples =
    result.Where(r => r.Item1 == (result.Max(m => m.Item1))).ToList();

You are getting the maximum value of Item1 (the int) and then finding all records that have the same value.

HTH, like mentioned in the comments previously good to post what you have tried in future.


问:
Php search in database to show data, not working
i'm trying to display some data from my database, and i dosen't work when i try to display some of the data, specified by a search bar. Here is the code. I hope someone can fix my problem.

Ive tried for a few hours, but nothing seems to work.

I removed most of the html code, to even be able to post.

<?php
 include_once 'includes/dbh.inc.php';
?>
<!DOCTYPE html>

    <form>
    <input type="text" name="search" placeholder="Search for graphicscard"/>
    <input type="submit" value="Search" />

<?php

?>

    </form>

Graphicscard
Coin
Hashrate
Bios-modded
Core-clock
Memory-clock
Power draw
Additional info

      <?
  if(isset($_POST['search'])) {
        $searchq = $_POST['search'];
        $searchq = preg_replace("#[^`0-9a-z]#i","", $searchq);

        $query = mysqli_query("SELECT * FROM 'cards' WHERE 'name' LIKE '$search%' OR coin LIKE '$search%'") or die ("No results");
        $count = mysqli_num_rows($queryQ);

            while ($row = mysqli_fetch_array($query)) {
                echo "
";
                echo "".$row['name']."	";
                echo "".$row['coin'] . "	";
                echo "".$row['hashrate'] . "	";
                echo "".$row['bios_mod'] . "	";
                echo "".$row['core_clock'] . "	";
                echo "".$row['memory_clock'] . "	";
                echo "".$row['power_draw'] . "	";
                echo "".$row['additional_info'] . "	";
                echo "
";
            }
        }

        ?>```

答:
Do you get correct query result and how many rows in it? As I can see were is a mistake in your query:

SELECT * FROM 'cards' WHERE 'name' LIKE...

Name of table and fields should be in another quoats - `

SELECT * FROM cards WHERE name LIKE...

Or this is typing issue on posted message?

On this row: $count = mysqli_num_rows($queryQ); - you variable of query result is - $query not $queryQ