答:
Assuming you know the maximim column number, you can deal with it in the RowDataBound event of the GridView:

Declare an array of totals at the page class level:

```<code>int maxTotals = 10;
Decimal[] Totals = new Decimal[10];
</code>```

Process data in RowDatBound event

```<code>protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{

  if (e.Row.RowType == DataControlRowType.HeaderRow)
  {
   //Initialize totals array
   for (int k=0; k<=maxTotals; k++)
     totals[k]=0;
  }
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
   //Collect totals from relevant cells
   DataRowView rowView = (DataRowView)e.Row.DataItem;
   for (int k=0; k<=maxTotals; k++)
      totals[k] += (Decimal)rowView[k];
  }
  if (e.Row.RowType == DataControlRowType.FooterRow)
  {
   //Show totals
   for (int k=0; k<=maxTotals; k++)
     e.Row.Cells[k].Text = String.Format("{0:c}",totals[k]);
  }
}
</code>```

In case you don't know the column maximum number, you can always put a try/catch in the for loop and exit the loop in case of an ArrayOutOfBoundException

Title: calculating the sum total of the columns and display in footer when colum names are dynamic

Body:
I have a DataTable whose data are retrieved from the database. I am trying to get sum of the values of each cells every column wise and display in the footer of the DataTable .

But the problem is, my retrieved column names are dynamic, they vary every time user gives different input. How can I get the sum of the each column when my column names are dynamic.

protected void search_Click(object sender, EventArgs e)
{
    try
    {
        DataTable dt = new DataTable();
        string from_date = srch_date.Text.ToString();
        string to_date = srch_to_date.Text.ToString();

        dt = new DAL_Reports().Rpt_Count_Transpose(from_date, to_date);
        if (dt != null && dt.Rows.Count > 0)
        {
            GridView1.DataSource = dt_;
            GridView1.DataBind();
        }
    }
    catch (Exception ex) { }
}

Body:
Assuming you know the maximim column number, you can deal with it in the RowDataBound event of the GridView:

Declare an array of totals at the page class level:

int maxTotals = 10;
Decimal[] Totals = new Decimal[10];

Process data in RowDatBound event

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{

  if (e.Row.RowType == DataControlRowType.HeaderRow)
  {
   //Initialize totals array
   for (int k=0; k<=maxTotals; k++)
     totals[k]=0;
  }
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
   //Collect totals from relevant cells
   DataRowView rowView = (DataRowView)e.Row.DataItem;
   for (int k=0; k<=maxTotals; k++)
      totals[k] += (Decimal)rowView[k];
  }
  if (e.Row.RowType == DataControlRowType.FooterRow)
  {
   //Show totals
   for (int k=0; k<=maxTotals; k++)
     e.Row.Cells[k].Text = String.Format("{0:c}",totals[k]);
  }
}

In case you don't know the column maximum number, you can always put a try/catch in the for loop and exit the loop in case of an ArrayOutOfBoundException


来源: stackexchange

问:
Why is my LSTM in tensorflow learning so slowly and badly?
This program reads a text file RNNtext.txt, creates one-hot vector representation for all the data, trains the LSTM with the data and displays a bunch of sampled characters every now and then. However, even looking at the cost vs iterations graph shows that it's learning very very inefficiently. Honestly, the raw code (numpy) for the LSTM I have does a MUCH better job. It's not only faster but it produces mostly meaningful words. This produces gibberish only. Where is my mistake? I really am out of ideas and I can't seem to find where it is logically wrong.

```<code>import numpy as np
import random
import tensorflow as tf
import os
import matplotlib.pyplot as plt

plt.style.use('fivethirtyeight')

# Reading RNNtext.txt file
direc = os.path.dirname(os.path.realpath(__file__))
data = open(direc + "/RNNtext.txt", "r").read()

# Array of unique characters
chars = list(set(data))

num_hidden = 80
iterations = 1000
display_iteration = 100 # Sample when iteration % display_iteration == 0
sample_size = 250
batch_size = 120 # batch size or the number of time steps to unroll RNN
alpha = 0.01 # Learning rate

#Vocabulary and text file sizes
vocab_size = len(chars)
data_size = len(data)

# Bijection from a unique character to an index
char_to_ix = {}
# Bijection from an index to a unique character
ix_to_char = {}

for j in range(vocab_size):
    char_to_ix[chars[j]] = j
    ix_to_char[j] = chars[j]

# Transforming all characters to indices
data_ix = [char_to_ix[ch] for ch in data]

train_data = [] # This will contain one-hot vectors
for k in range(data_size):
    # Representing each index/character by a one-hot vector
    hot1 = np.zeros((vocab_size, 1))
    hot1[data_ix[k]] = 1
    train_data.append(hot1)

X = tf.placeholder(tf.float32, [None, vocab_size, 1]) #Number of examples, number of input, dimension of each input
target = tf.placeholder(tf.float32, [None, vocab_size])

cell = tf.contrib.rnn.LSTMCell(num_hidden,state_is_tuple=True)
output, _ = tf.nn.dynamic_rnn(cell, X, dtype = tf.float32)
output = tf.transpose(output, [1, 0, 2])

weight = tf.Variable(tf.random_normal([num_hidden, vocab_size]))
bias = tf.Variable(tf.constant(0.0, shape=[vocab_size]))

prediction = tf.matmul(output[-1], weight) + bias
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=target))

optimizer = tf.train.ProximalGradientDescentOptimizer(alpha)
minimize = optimizer.minimize(cost)

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

ARR = [i for i in range(vocab_size)] # for extracting index by probabilities in np.random.choice()

ITER = []
COST = []

p = 0 # p will be iterated by batch_size steps
for i in range(iterations):
    if p + batch_size >= data_size:
        p = 0

    # sweeping through data one-hot vectors
    inp, out = train_data[p:p+batch_size], train_data[p+1:p+batch_size+1]
    out = np.reshape(out, [-1, vocab_size])

    c = sess.run(cost, {X: inp, target: out}) # calculating cost for plotting later
    COST.append(c)
    ITER.append(i)

    sess.run(minimize, {X: inp, target: out})

    # displaying sample_size number of characters with random seed
    # doesn't affect training
    if i % display_iteration == 0:
        seed = np.random.randint(0, vocab_size)
        CHARS = []
        for j in range(sample_size):
            x = np.zeros((vocab_size, 1))
            x[seed] = 1
            x = [x]
            pred = sess.run(prediction, {X: x})[0]
            pred = np.exp(pred) / np.sum(np.exp(pred))
            pred = pred.ravel()

            seed = np.random.choice(ARR, 1, p = pred)[0]
            ch = ix_to_char[seed]
            CHARS.append(ch)
        TXT = ''.join(CHARS)

        print("-------------------------------------------------")
        print(TXT)
        print("Iteration: ", str(i))

    p += batch_size
sess.close()
plt.plot(ITER, COST)
plt.show()
</code>```

EDIT: Added numpy code for comparison

```<code>import numpy as np
import matplotlib.pyplot as plt
import os
plt.style.use('fivethirtyeight')
direc = os.path.dirname(os.path.realpath(__file__))

readFile = open(direc + "\RNNtext.txt", 'r')

data = readFile.read()
readFile.close()

chars = list(set(data))
data_size, vocab_size = len(data), len(chars)
print(chars)
print("Vocabulary size: " + str(vocab_size))
char_to_ix = {}
ix_to_char = {}

for j in range(len(chars)):
    char_to_ix[chars[j]] = j
    ix_to_char[j] = chars[j]

hidden_size = 80
batch_size = 120
alpha = 0.1
sample_size = 250
iterations = 1000
display_iteration = 100

Wxh = np.random.randn(hidden_size, vocab_size)*0.01 # input to hidden
Whh = np.random.randn(hidden_size, hidden_size)*0.01 # hidden to hidden
Why = np.random.randn(vocab_size, hidden_size)*0.01 # hidden to output
bh = np.zeros((hidden_size, 1)) # hidden bias
by = np.zeros((vocab_size, 1)) # output bias

def sample(hid, seed, weights, sample_size):
    X = np.zeros((vocab_size, 1))
    X[seed] = 1
    CHARS = []
    ARR = [i for i in range(vocab_size)]

    for t in range(sample_size):
        hid = np.tanh(np.dot(Wxh, X)  + np.dot(Whh, hid) + bh)
        y = np.dot(Why, hid) + by
        prob = np.exp(y) / np.sum(np.exp(y))
        prob = prob.ravel()
        ix = np.random.choice(ARR, 1, p=prob)[0]
        CHARS.append(ix_to_char[ix])
        X = np.zeros((vocab_size, 1))
        X[ix] = 1
        TXT = ''.join(CHARS)
    return TXT

LOSS = []
ITER = []
p = 0

mWxh, mWhh, mWhy = np.zeros_like(Wxh), np.zeros_like(Whh), np.zeros_like(Why)
mbh, mby = np.zeros_like(bh), np.zeros_like(by) # memory variables for Adagrad

smooth_loss = -np.log(1.0/vocab_size)*batch_size # loss at iteration 0
hprev = np.zeros((hidden_size,1))

for i in range(iterations): ## just time passing by

    dWxh = np.zeros_like(Wxh)
    dWhh = np.zeros_like(Whh)
    dWhy = np.zeros_like(Why)
    dbh = np.zeros_like(bh)
    dby = np.zeros_like(by)

    if p+batch_size >= len(data) or i == 0:
        hprev = np.zeros((hidden_size,1))
        p = 0

    inputs = [char_to_ix[ch] for ch in data[p:p+batch_size]]
    targets = [char_to_ix[ch] for ch in data[p+1:p+batch_size+1]]

    HID = {}
    X = {}
    Y = {}
    P = {}
    HID[-1] = np.copy(hprev)

    loss = 0

    ##======FORWARD======##
    for t in range(len(inputs)):
        X[t] = np.zeros((vocab_size,1))
        X[t][inputs[t]] = 1

        HID[t] = np.tanh(np.dot(Wxh, X[t])  + np.dot(Whh, HID[t-1]) + bh) # inp -> X
        Y[t] = np.dot(Why, HID[t]) + by # tanh
        P[t] = np.exp(Y[t]) / np.sum(np.exp(Y[t]))
        loss += -np.log(P[t][targets[t]][0])
    dhnext = np.zeros_like(HID[0])
    ##======BACKPROP======##
    for t in reversed(range(len(inputs))):

        dy = np.copy(P[t])
        dy[targets[t]] -= 1
        dh = (np.dot(Why.T, dy) + dhnext)*(1-HID[t]*HID[t])
        dx = np.dot(Why.T, dy)*(1 - HID[t]**2)

        dWhy += np.dot(dy, HID[t].T)
        dWhh += np.dot(dh, HID[t-1].T)
        dWxh += np.dot(dh, X[t].T)
        dby += dy
        dbh += dh

        dhnext = np.dot(Whh.T, dh)

    ##=====================##
    hprev = HID[-1]
    smooth_loss = smooth_loss * 0.999 + loss * 0.001
    for dparam in [dWxh, dWhh, dWhy, dbh, dby]:
        np.clip(dparam, -1, 1, out=dparam) # clip to mitigate exploding gradients

    for param, dparam, mem in zip([Wxh, Whh, Why, bh, by],
                                [dWxh, dWhh, dWhy, dbh, dby],
                                [mWxh, mWhh, mWhy, mbh, mby]):

        mem += dparam * dparam

        param += -alpha * dparam / np.sqrt(mem + 1e-8) # Adagrad
    if i % display_iteration == 0:
        print(str(i))
        weights = [Wxh,Whh,Why,bh,by]
        seed = inputs[np.random.randint(0,len(inputs))]
        TXT = sample(HID[-1], seed, weights, sample_size)
        print("-----------------------------------------------")
        print(TXT)
        print("-----------------------------------------------")
        with open(direc + "\RNNout.txt", 'w') as writeFile:
            writeFile.write(TXT)
    ITER.append(i)
    LOSS.append(loss)

    p += batch_size
best_text = sample(HID[-1], inputs[0], weights, sample_size)

plt.plot(ITER, LOSS, linewidth = 1)
plt.show()

writeFile.close()
</code>```

答:
Well, doh... looks like you are not re-using the state! How is LSTM (state machine) supposed to work properly if you are not maintaining the state?

To me this looks like a red flag:

```<code>output, _ = tf.nn.dynamic_rnn(cell, X, dtype = tf.float32)
</code>```

the second output from tf.nn.dynamic_rnn is the latest state after the given sequence has been processed. Looks like you are explicitly ignoring it and not re-feeding it into each following iteration of training in sess.run(...) (and hence your dynamic_rnn doesn't have the initial_state parameter).

I would highly recommend changing that part of your code before looking any further.

Also, I don't know what your data looks like, but your feeding and batching strategy needs to be such as to make sense out of this whole state-passing exercise. Otherwise, once again, it will just produce gibberish.

ContentLicense: CC BY-SA 3.0

Body:
This program reads a text file RNNtext.txt, creates one-hot vector representation for all the data, trains the LSTM with the data and displays a bunch of sampled characters every now and then. However, even looking at the cost vs iterations graph shows that it's learning very very inefficiently. Honestly, the raw code (numpy) for the LSTM I have does a MUCH better job. It's not only faster but it produces mostly meaningful words. This produces gibberish only. Where is my mistake? I really am out of ideas and I can't seem to find where it is logically wrong.

import numpy as np
import random
import tensorflow as tf
import os
import matplotlib.pyplot as plt

plt.style.use('fivethirtyeight')

# Reading RNNtext.txt file
direc = os.path.dirname(os.path.realpath(__file__))
data = open(direc + "/RNNtext.txt", "r").read()

# Array of unique characters
chars = list(set(data))

num_hidden = 80
iterations = 1000
display_iteration = 100 # Sample when iteration % display_iteration == 0
sample_size = 250
batch_size = 120 # batch size or the number of time steps to unroll RNN
alpha = 0.01 # Learning rate

#Vocabulary and text file sizes
vocab_size = len(chars)
data_size = len(data)

# Bijection from a unique character to an index
char_to_ix = {}
# Bijection from an index to a unique character
ix_to_char = {}

for j in range(vocab_size):
    char_to_ix[chars[j]] = j
    ix_to_char[j] = chars[j]

# Transforming all characters to indices
data_ix = [char_to_ix[ch] for ch in data]

train_data = [] # This will contain one-hot vectors
for k in range(data_size):
    # Representing each index/character by a one-hot vector
    hot1 = np.zeros((vocab_size, 1))
    hot1[data_ix[k]] = 1
    train_data.append(hot1)

X = tf.placeholder(tf.float32, [None, vocab_size, 1]) #Number of examples, number of input, dimension of each input
target = tf.placeholder(tf.float32, [None, vocab_size])

cell = tf.contrib.rnn.LSTMCell(num_hidden,state_is_tuple=True)
output, _ = tf.nn.dynamic_rnn(cell, X, dtype = tf.float32)
output = tf.transpose(output, [1, 0, 2])

weight = tf.Variable(tf.random_normal([num_hidden, vocab_size]))
bias = tf.Variable(tf.constant(0.0, shape=[vocab_size]))

prediction = tf.matmul(output[-1], weight) + bias
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=target))

optimizer = tf.train.ProximalGradientDescentOptimizer(alpha)
minimize = optimizer.minimize(cost)

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

ARR = [i for i in range(vocab_size)] # for extracting index by probabilities in np.random.choice()

ITER = []
COST = []

p = 0 # p will be iterated by batch_size steps
for i in range(iterations):
    if p + batch_size >= data_size:
        p = 0

    # sweeping through data one-hot vectors
    inp, out = train_data[p:p+batch_size], train_data[p+1:p+batch_size+1]
    out = np.reshape(out, [-1, vocab_size])

    c = sess.run(cost, {X: inp, target: out}) # calculating cost for plotting later
    COST.append(c)
    ITER.append(i)

    sess.run(minimize, {X: inp, target: out})

    # displaying sample_size number of characters with random seed
    # doesn't affect training
    if i % display_iteration == 0:
        seed = np.random.randint(0, vocab_size)
        CHARS = []
        for j in range(sample_size):
            x = np.zeros((vocab_size, 1))
            x[seed] = 1
            x = [x]
            pred = sess.run(prediction, {X: x})[0]
            pred = np.exp(pred) / np.sum(np.exp(pred))
            pred = pred.ravel()

            seed = np.random.choice(ARR, 1, p = pred)[0]
            ch = ix_to_char[seed]
            CHARS.append(ch)
        TXT = ''.join(CHARS)

        print("-------------------------------------------------")
        print(TXT)
        print("Iteration: ", str(i))

    p += batch_size
sess.close()
plt.plot(ITER, COST)
plt.show()

EDIT: Added numpy code for comparison

import numpy as np
import matplotlib.pyplot as plt
import os
plt.style.use('fivethirtyeight')
direc = os.path.dirname(os.path.realpath(__file__))

readFile = open(direc + "\RNNtext.txt", 'r')

data = readFile.read()
readFile.close()

chars = list(set(data))
data_size, vocab_size = len(data), len(chars)
print(chars)
print("Vocabulary size: " + str(vocab_size))
char_to_ix = {}
ix_to_char = {}

for j in range(len(chars)):
    char_to_ix[chars[j]] = j
    ix_to_char[j] = chars[j]

hidden_size = 80
batch_size = 120
alpha = 0.1
sample_size = 250
iterations = 1000
display_iteration = 100

Wxh = np.random.randn(hidden_size, vocab_size)*0.01 # input to hidden
Whh = np.random.randn(hidden_size, hidden_size)*0.01 # hidden to hidden
Why = np.random.randn(vocab_size, hidden_size)*0.01 # hidden to output
bh = np.zeros((hidden_size, 1)) # hidden bias
by = np.zeros((vocab_size, 1)) # output bias

def sample(hid, seed, weights, sample_size):
    X = np.zeros((vocab_size, 1))
    X[seed] = 1
    CHARS = []
    ARR = [i for i in range(vocab_size)]

    for t in range(sample_size):
        hid = np.tanh(np.dot(Wxh, X)  + np.dot(Whh, hid) + bh)
        y = np.dot(Why, hid) + by
        prob = np.exp(y) / np.sum(np.exp(y))
        prob = prob.ravel()
        ix = np.random.choice(ARR, 1, p=prob)[0]
        CHARS.append(ix_to_char[ix])
        X = np.zeros((vocab_size, 1))
        X[ix] = 1
        TXT = ''.join(CHARS)
    return TXT

LOSS = []
ITER = []
p = 0

mWxh, mWhh, mWhy = np.zeros_like(Wxh), np.zeros_like(Whh), np.zeros_like(Why)
mbh, mby = np.zeros_like(bh), np.zeros_like(by) # memory variables for Adagrad

smooth_loss = -np.log(1.0/vocab_size)*batch_size # loss at iteration 0
hprev = np.zeros((hidden_size,1))

for i in range(iterations): ## just time passing by

    dWxh = np.zeros_like(Wxh)
    dWhh = np.zeros_like(Whh)
    dWhy = np.zeros_like(Why)
    dbh = np.zeros_like(bh)
    dby = np.zeros_like(by)

    if p+batch_size >= len(data) or i == 0:
        hprev = np.zeros((hidden_size,1))
        p = 0

    inputs = [char_to_ix[ch] for ch in data[p:p+batch_size]]
    targets = [char_to_ix[ch] for ch in data[p+1:p+batch_size+1]]

    HID = {}
    X = {}
    Y = {}
    P = {}
    HID[-1] = np.copy(hprev)

    loss = 0

    ##======FORWARD======##
    for t in range(len(inputs)):
        X[t] = np.zeros((vocab_size,1))
        X[t][inputs[t]] = 1

        HID[t] = np.tanh(np.dot(Wxh, X[t])  + np.dot(Whh, HID[t-1]) + bh) # inp -> X
        Y[t] = np.dot(Why, HID[t]) + by # tanh
        P[t] = np.exp(Y[t]) / np.sum(np.exp(Y[t]))
        loss += -np.log(P[t][targets[t]][0])
    dhnext = np.zeros_like(HID[0])
    ##======BACKPROP======##
    for t in reversed(range(len(inputs))):

        dy = np.copy(P[t])
        dy[targets[t]] -= 1
        dh = (np.dot(Why.T, dy) + dhnext)*(1-HID[t]*HID[t])
        dx = np.dot(Why.T, dy)*(1 - HID[t]**2)

        dWhy += np.dot(dy, HID[t].T)
        dWhh += np.dot(dh, HID[t-1].T)
        dWxh += np.dot(dh, X[t].T)
        dby += dy
        dbh += dh

        dhnext = np.dot(Whh.T, dh)

    ##=====================##
    hprev = HID[-1]
    smooth_loss = smooth_loss * 0.999 + loss * 0.001
    for dparam in [dWxh, dWhh, dWhy, dbh, dby]:
        np.clip(dparam, -1, 1, out=dparam) # clip to mitigate exploding gradients

    for param, dparam, mem in zip([Wxh, Whh, Why, bh, by],
                                [dWxh, dWhh, dWhy, dbh, dby],
                                [mWxh, mWhh, mWhy, mbh, mby]):

        mem += dparam * dparam

        param += -alpha * dparam / np.sqrt(mem + 1e-8) # Adagrad
    if i % display_iteration == 0:
        print(str(i))
        weights = [Wxh,Whh,Why,bh,by]
        seed = inputs[np.random.randint(0,len(inputs))]
        TXT = sample(HID[-1], seed, weights, sample_size)
        print("-----------------------------------------------")
        print(TXT)
        print("-----------------------------------------------")
        with open(direc + "\RNNout.txt", 'w') as writeFile:
            writeFile.write(TXT)
    ITER.append(i)
    LOSS.append(loss)

    p += batch_size
best_text = sample(HID[-1], inputs[0], weights, sample_size)

plt.plot(ITER, LOSS, linewidth = 1)
plt.show()

writeFile.close()

Body:
Well, doh... looks like you are not re-using the state! How is LSTM (state machine) supposed to work properly if you are not maintaining the state?

To me this looks like a red flag:

output, _ = tf.nn.dynamic_rnn(cell, X, dtype = tf.float32)

the second output from tf.nn.dynamic_rnn is the latest state after the given sequence has been processed. Looks like you are explicitly ignoring it and not re-feeding it into each following iteration of training in sess.run(...) (and hence your dynamic_rnn doesn't have the initial_state parameter).

I would highly recommend changing that part of your code before looking any further.

Also, I don't know what your data looks like, but your feeding and batching strategy needs to be such as to make sense out of this whole state-passing exercise. Otherwise, once again, it will just produce gibberish.


问:
Why don't the values for a single studentid add up while i execute this SQL statement even though i used Distinct?

I have to write a query to display the studentid and the total fees paid by each student and then sort the result based on studentid in ascending order.

I have used Distinct so that studid is displayed only once but still I don't get the expected output.

My code:

```<code>select distinct s.studid,c.fees as total_fees from Student s join
Registration r on s.studid=r.studid join Course c on r.courseid=c.courseid
group by s.studid,c.fees order by s.studid;
</code>```

My Output:

Expected Output:

答:
You join registration.
That would give you one record per student and registration,
which is what you want.
Calling distinct on it then, though, means you only get one of those records.

What you want to do is sum up those fees, group the results per student, and order by studid.

```<code>SELECT s.studid, SUM(c.fees) as total_fees FROM student s
JOIN registration r ON s.studid = r.studid
JOIN course c ON r.courseid=c.courseid
GROUP BY s.studid
ORDER BY s.studid;
</code>```

Body:
I have to write a query to display the studentid and the total fees paid by each student and then sort the result based on studentid in ascending order.

I have used Distinct so that studid is displayed only once but still I don't get the expected output.

My code:

select distinct s.studid,c.fees as total_fees from Student s join
Registration r on s.studid=r.studid join Course c on r.courseid=c.courseid
group by s.studid,c.fees order by s.studid;

My Output:

Expected Output:

Body:
You join registration.
That would give you one record per student and registration,
which is what you want.
Calling distinct on it then, though, means you only get one of those records.

What you want to do is sum up those fees, group the results per student, and order by studid.

SELECT s.studid, SUM(c.fees) as total_fees FROM student s
JOIN registration r ON s.studid = r.studid
JOIN course c ON r.courseid=c.courseid
GROUP BY s.studid
ORDER BY s.studid;


问:
I am trying to fetch all links from a website and clicking one by one on all links
I am trying to fetch all links from a website and clicking one by one on all links. While running below code- I am getting total links count correctly but I am not able to navigate on the links. It throws null pointer exception.

Refer the code

```<code>public class Fetch_all_links {

static int count =0;
public static String[] links = null;

public static void main (String args[]) throws InterruptedException{

    System.setProperty("webdriver.chrome.driver", "D:\\New folder\\exe\\chromedriver_win32\\chromedriver.exe");

    WebDriver driver = new ChromeDriver();
    driver.get("http://www.msn.com");
    driver.manage().window().maximize();

    List<WebElement>all_links = driver.findElements(By.tagName("a"));

    System.out.println(all_links.size());
    for(int i=0;i<all_links.size();i++){

        links[i] = all_links.get(i).getAttribute("href");
        driver.navigate().to(links[i]);
        System.out.println(count + driver.getTitle());
        count++;
        Thread.sleep(1000);

    }

}
</code>```

答:
Here is the Answer to your Question:

You are getting a Null Pointer Exception because you are parsing the attribute href through all_links.get(i).getAttribute("href"); and assigning it to links which is of String[] type. Instead to avoid Null Pointer Exception you can store all the hrefs in a List<String>. Next you can traverse the list and open the individual links as follows:

```<code>    import java.util.ArrayList;
    import java.util.List;

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;

    public class Q44985587_links {

        static int count =0;
        public static void main (String args[]) throws InterruptedException
        {
            System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
            WebDriver driver = new ChromeDriver();
            driver.get("http://www.msn.com");
            driver.manage().window().maximize();
            List<WebElement> all_links = driver.findElements(By.tagName("a"));
            System.out.println(all_links.size());
            List<String> links = new ArrayList<String>();
            for(WebElement link:all_links)
            {
            String link_href = link.getAttribute("href");
            links.add(link_href);
            }
            System.out.println(links);

        }
    }
</code>```

Let me know if this Answers your Question.

Body:
I am trying to fetch all links from a website and clicking one by one on all links. While running below code- I am getting total links count correctly but I am not able to navigate on the links. It throws null pointer exception.

Refer the code

public class Fetch_all_links {

static int count =0;
public static String[] links = null;

public static void main (String args[]) throws InterruptedException{

    System.setProperty("webdriver.chrome.driver", "D:\\New folder\\exe\\chromedriver_win32\\chromedriver.exe");

    WebDriver driver = new ChromeDriver();
    driver.get("http://www.msn.com");
    driver.manage().window().maximize();

    List<WebElement>all_links = driver.findElements(By.tagName("a"));

    System.out.println(all_links.size());
    for(int i=0;i<all_links.size();i++){

        links[i] = all_links.get(i).getAttribute("href");
        driver.navigate().to(links[i]);
        System.out.println(count + driver.getTitle());
        count++;
        Thread.sleep(1000);

    }

}

Body:
Here is the Answer to your Question:

You are getting a Null Pointer Exception because you are parsing the attribute href through all_links.get(i).getAttribute("href"); and assigning it to links which is of String[] type. Instead to avoid Null Pointer Exception you can store all the hrefs in a List<String>. Next you can traverse the list and open the individual links as follows:

    import java.util.ArrayList;
    import java.util.List;

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;

    public class Q44985587_links {

        static int count =0;
        public static void main (String args[]) throws InterruptedException
        {
            System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
            WebDriver driver = new ChromeDriver();
            driver.get("http://www.msn.com");
            driver.manage().window().maximize();
            List<WebElement> all_links = driver.findElements(By.tagName("a"));
            System.out.println(all_links.size());
            List<String> links = new ArrayList<String>();
            for(WebElement link:all_links)
            {
            String link_href = link.getAttribute("href");
            links.add(link_href);
            }
            System.out.println(links);

        }
    }

Let me know if this Answers your Question.


问:
How to add an image as html and load it to webview in iPhone sdk?
I am implementing a webview based application, in that I tried to load an image but it is not coming as expected. I don't know what is the problem. The following is my code that I tried. Please suggest me if I did any thing wrong.</p>

```<code>  NSString *returnString = @"";

returnString = [returnString stringByReplacingOccurrencesOfString:@"<html><body>" withString:@"<body> <p>Hello Sekhar"];
returnString = [returnString stringByAppendingString:@"<img src='tutorial/images/bg1.png'"];
returnString = [returnString stringByAppendingString:@"alt='footer'"];
returnString = [returnString stringByAppendingString:@"align='middle' width='140' height='32' />"];
returnString = [returnString stringByAppendingString:@"</p></body></html>"];
[myWebView loadHTMLString:returnString baseURL:[NSURL URLWithString:@"http:www.google.com"]];
</code>```

答:
```<code>    NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
    NSURL *bundleBaseURL = [NSURL fileURLWithPath: bundlePath];

    NSLog(@"webview %@", bundlePath);

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
    NSData *htmlData = [NSData dataWithContentsOfFile:filePath];
    NSString * html =  [NSString stringWithContentsOfFile:filePath encoding:NSStringEncodingConversionAllowLossy error:nil];
    if (htmlData) {
       [webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:bundleBaseURL];
    }
</code>```

used the search function once: load-image-in-web-view-from-a-html-file

ContentLicense: CC BY-SA 2.5

Body:
I am implementing a webview based application, in that I tried to load an image but it is not coming as expected. I don't know what is the problem. The following is my code that I tried. Please suggest me if I did any thing wrong.

  NSString *returnString = @"";

returnString = [returnString stringByReplacingOccurrencesOfString:@"" withString:@"
Hello Sekhar"];
returnString = [returnString stringByAppendingString:@""];
returnString = [returnString stringByAppendingString:@"
"];
[myWebView loadHTMLString:returnString baseURL:[NSURL URLWithString:@"http:www.google.com"]];

Body:
    NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
    NSURL *bundleBaseURL = [NSURL fileURLWithPath: bundlePath];

    NSLog(@"webview %@", bundlePath);

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
    NSData *htmlData = [NSData dataWithContentsOfFile:filePath];
    NSString * html =  [NSString stringWithContentsOfFile:filePath encoding:NSStringEncodingConversionAllowLossy error:nil];
    if (htmlData) {
       [webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:bundleBaseURL];
    }

used the search function once: load-image-in-web-view-from-a-html-file


问:
Building an executable file for python code using py2exe. ImportError: No module named cell
I installed "py2exe" for "Python2.7" , made a "Hello World" program, used py2exe to build its exe and it worked perfectly.

Now when I tried building the exe of my actual code, the folders get created and exe is also created without any problem but when I launch the exe the console appears for less than a second and closes.

Following are import commands which I am using:

```<code>import tweepy
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import json
__version__='2.4.8'
from openpyxl import __version__
from openpyxl import Workbook
from Tkinter import *
import tkFileDialog
</code>```

My setup file is like this:

```<code>from distutils.core import setup
import py2exe
__version__='2.3.5'
from openpyxl import __version__
from openpyxl.cell import Cell

setup(
    windows=[{"script":'try.py'}],
    options = {"py2exe":{"includes":["tweepy","openpyxl.reader.excel","openpyxl.cell","openpyxl.workbook","openpyxl.worksheet","jdcal","xlutils","json","xlrd","Tkconstants","Tkinter","tkFileDialog","xml.etree.ElementPath", "xml.etree.ElementTree","xml.etree.cElementTree"],
 "packages": ["xml.etree", "xml"]}}
    )
</code>```

The error which I am getting is :

```<code>Traceback (most recent call last):
  File "try.py", line 7, in <module>
  File "openpyxl\__init__.pyc", line 29, in <module>
  File "openpyxl\workbook\__init__.pyc", line 5, in <module>
  File "openpyxl\workbook\workbook.pyc", line 8, in <module>
  File "openpyxl\worksheet\__init__.pyc", line 4, in <module>
  File "openpyxl\worksheet\worksheet.pyc", line 23, in <module>
  File "openpyxl\utils\__init__.pyc", line 5, in <module>
ImportError: No module named cell
</code>```

My file name is try.py

答:
the solution is too use pip, just write in your terminal:

```<code>pip install openpyxl
</code>```

If you are using windows, press:

Win + R

Type CMD in the run window which has opened

and then:

```<code>pip install openpyxl
</code>```

for the future, sometimes (very often) you need to install python packages, for that reason pip is your best friend.

Body:
I installed "py2exe" for "Python2.7" , made a "Hello World" program, used py2exe to build its exe and it worked perfectly.

Now when I tried building the exe of my actual code, the folders get created and exe is also created without any problem but when I launch the exe the console appears for less than a second and closes.

Following are import commands which I am using:

import tweepy
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import json
__version__='2.4.8'
from openpyxl import __version__
from openpyxl import Workbook
from Tkinter import *
import tkFileDialog

My setup file is like this:

from distutils.core import setup
import py2exe
__version__='2.3.5'
from openpyxl import __version__
from openpyxl.cell import Cell

setup(
    windows=[{"script":'try.py'}],
    options = {"py2exe":{"includes":["tweepy","openpyxl.reader.excel","openpyxl.cell","openpyxl.workbook","openpyxl.worksheet","jdcal","xlutils","json","xlrd","Tkconstants","Tkinter","tkFileDialog","xml.etree.ElementPath", "xml.etree.ElementTree","xml.etree.cElementTree"],
 "packages": ["xml.etree", "xml"]}}
    )

The error which I am getting is :

Traceback (most recent call last):
  File "try.py", line 7, in <module>
  File "openpyxl\__init__.pyc", line 29, in <module>
  File "openpyxl\workbook\__init__.pyc", line 5, in <module>
  File "openpyxl\workbook\workbook.pyc", line 8, in <module>
  File "openpyxl\worksheet\__init__.pyc", line 4, in <module>
  File "openpyxl\worksheet\worksheet.pyc", line 23, in <module>
  File "openpyxl\utils\__init__.pyc", line 5, in <module>
ImportError: No module named cell

My file name is try.py

Body:
the solution is too use pip, just write in your terminal:

pip install openpyxl

If you are using windows, press:

Win + R

Type CMD in the run window which has opened

and then:

pip install openpyxl

for the future, sometimes (very often) you need to install python packages, for that reason pip is your best friend.


问:
Nginx + php-fpm gives file not found
I am getting File not found error with nginx and i have been trying to fix this for hours.The config look similar to what i use on other sites but i don't know why it doesn't work.html files works fine thought.

btw i looked at this post but still couldn't find what is wrong with mine.

```<code>server {
    listen 80;
    server_name servergreek.com   167.88.125.157;
    return 301 http://www.servergreek.com$request_uri;
}
server {
    listen      80 default_server;
    server_name  www.servergreek.com;
    access_log   /home/servergreek.com/public_html/logs/access_log main;
    error_log     /home/servergreek.com/public_html/logs/error_log crit;
    root /home/servergreek.com/public_html/www;
    index index.php index.html index.htm;

    #Serve static content directly
    location ~* \.(jpg|jpeg|gif|css|png|js|ico|html|woff)$ {
    access_log off;
    expires max;
    }

    location ~ ^/tmp/(.*)$ {
    deny all;
    }

    # Zend Opcache rules
        #location  /opcache/ {
            # root /home/servergreek.com/public_html/www;
            # index index.php index.html index.htm;
            # auth_basic            "Restricted Area (Secured by Khavish)";
            # auth_basic_user_file  /var/www/servergreek.com/private/htpasswd;
        #}

    # Only requests to our Host are allowed
    if ($host  !~ ^(servergreek.com|www.servergreek.com)$ ) {
         return 444;
      }

     location ~* \.php$ {
        root /home/servergreek.com/public_html/www;
        fastcgi_pass   unix:/tmp/php5-fpm.sock;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include        fastcgi_params;
        fastcgi_connect_timeout 60;
        fastcgi_send_timeout 300;
        fastcgi_read_timeout 300;
        fastcgi_buffer_size 128k;
        fastcgi_buffers 256 16k;
        fastcgi_busy_buffers_size 256k;

    }

    #location ~ /\.ht {
     #  deny  all;
    #}

      }
</code>```

index.php location is /home/servergreek.com/public_html/www/index.php.Thanks for helping me out

答:
first </p>

```<code>chmod 0755  /home/servergreek.com/
chmod 0755  /home/servergreek.com/public_html/
chmod 0755  /home/servergreek.com/public_html/www
</code>```

<p>secand  add </p>

```<code>location / {
            root   /home/servergreek.com/public_html/www/;
            index  index.html index.htm index.php ;
    }
</code>```

Title: Nginx + php-fpm gives file not found

Body:
I am getting File not found error with nginx and i have been trying to fix this for hours.The config look similar to what i use on other sites but i don't know why it doesn't work.html files works fine thought.

btw i looked at this post but still couldn't find what is wrong with mine.

server {
    listen 80;
    server_name servergreek.com   167.88.125.157;
    return 301 http://www.servergreek.com$request_uri;
}
server {
    listen      80 default_server;
    server_name  www.servergreek.com;
    access_log   /home/servergreek.com/public_html/logs/access_log main;
    error_log     /home/servergreek.com/public_html/logs/error_log crit;
    root /home/servergreek.com/public_html/www;
    index index.php index.html index.htm;

    #Serve static content directly
    location ~* \.(jpg|jpeg|gif|css|png|js|ico|html|woff)$ {
    access_log off;
    expires max;
    }

    location ~ ^/tmp/(.*)$ {
    deny all;
    }

    # Zend Opcache rules
        #location  /opcache/ {
            # root /home/servergreek.com/public_html/www;
            # index index.php index.html index.htm;
            # auth_basic            "Restricted Area (Secured by Khavish)";
            # auth_basic_user_file  /var/www/servergreek.com/private/htpasswd;
        #}

    # Only requests to our Host are allowed
    if ($host  !~ ^(servergreek.com|www.servergreek.com)$ ) {
         return 444;
      }

     location ~* \.php$ {
        root /home/servergreek.com/public_html/www;
        fastcgi_pass   unix:/tmp/php5-fpm.sock;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include        fastcgi_params;
        fastcgi_connect_timeout 60;
        fastcgi_send_timeout 300;
        fastcgi_read_timeout 300;
        fastcgi_buffer_size 128k;
        fastcgi_buffers 256 16k;
        fastcgi_busy_buffers_size 256k;

    }

    #location ~ /\.ht {
     #  deny  all;
    #}

      }

index.php location is /home/servergreek.com/public_html/www/index.php.Thanks for helping me out

Body:
first

chmod 0755  /home/servergreek.com/
chmod 0755  /home/servergreek.com/public_html/
chmod 0755  /home/servergreek.com/public_html/www

secand  add

location / {
            root   /home/servergreek.com/public_html/www/;
            index  index.html index.htm index.php ;
    }


问:
Jquery and dynamic content
I have the following HTML code:

```<code><div id="summary_form">
    <textarea class="summary">Please fill in</textarea><br/>
    <textarea class="summary">Please fill in</textarea><br/>
   <div>
</code>```

And I have the following JS code that is called on document.ready:

```<code>var summaries = $('textArea.summary');
</code>```

This JS grabs all textareas with the class name 'summary' and stores it in the summaries variable.

I also have a link that when users click on it, will dynamically add another textarea with the 'summary' class name using Ajax, as follows:

```<code>$("#add_summary").click(function(){
  $('#temp').load("/addSummary.html", function() {
  $("#summary_form").append($('#temp').html());
  summaries = $('textArea.summary');
});
</code>```

The addSummary.html simply contains the following HTML:

```<code><textarea class="summary">Please fill in</textarea><br/>
</code>```

When the form is submitted, I am running the following code to clear the textareas of the "Please fill in" helper text as follows:

```<code>$("#user-form").submit(function () {
 //First reload all old and new textareas into summary variable - THIS PART IS NOT WORKING!
 summaries = $('textArea.work_history_summary');

 for (var i=0; i<summaries.length; i++)
    {
      if (summaries[i].value == 'Please fill in')
      {
        summaries[i].value = '';
      }
    }
 });
</code>```

But when the form submits, all the original textareas are cleared, but the newly added textareas are not.  For some reason, JQuery is not able to see the new textareas and store them in the summary variable.

Any idea what I may be doing wrong?

Thanks!

答:
Is it possible that what you load is a bit different - not textArea, or not summary? Just by mistake?

Additionally, consider using $.ajax() method:

```<code>$.ajax({
    url: '/addSummary',
    success: function(response) {
        $('#summary_form').append(response);
        summaries = $('textArea.summary');
    }
});
</code>```

This way you will not need any temporary storage, but will be able to append obtained html directly to you form. Maybe this will also fix your issue. (I could be a bit wrong with the parameter names or function arguments order, but you have got the main idea, have not you?)

Title: Jquery and dynamic content

Body:
I have the following HTML code:

    <textarea class="summary">Please fill in</textarea>

    <textarea class="summary">Please fill in</textarea>

And I have the following JS code that is called on document.ready:

var summaries = $('textArea.summary');

This JS grabs all textareas with the class name 'summary' and stores it in the summaries variable.

I also have a link that when users click on it, will dynamically add another textarea with the 'summary' class name using Ajax, as follows:

$("#add_summary").click(function(){
  $('#temp').load("/addSummary.html", function() {
  $("#summary_form").append($('#temp').html());
  summaries = $('textArea.summary');
});

The addSummary.html simply contains the following HTML:

<textarea class="summary">Please fill in</textarea>

When the form is submitted, I am running the following code to clear the textareas of the "Please fill in" helper text as follows:

$("#user-form").submit(function () {
 //First reload all old and new textareas into summary variable - THIS PART IS NOT WORKING!
 summaries = $('textArea.work_history_summary');

 for (var i=0; i<summaries.length; i++)
    {
      if (summaries[i].value == 'Please fill in')
      {
        summaries[i].value = '';
      }
    }
 });

But when the form submits, all the original textareas are cleared, but the newly added textareas are not.  For some reason, JQuery is not able to see the new textareas and store them in the summary variable.

Any idea what I may be doing wrong?

Thanks!

Body:
Is it possible that what you load is a bit different - not textArea, or not summary? Just by mistake?

Additionally, consider using $.ajax() method:

$.ajax({
    url: '/addSummary',
    success: function(response) {
        $('#summary_form').append(response);
        summaries = $('textArea.summary');
    }
});

This way you will not need any temporary storage, but will be able to append obtained html directly to you form. Maybe this will also fix your issue. (I could be a bit wrong with the parameter names or function arguments order, but you have got the main idea, have not you?)


问:
Can't upload images to WordPress
I am trying to upload images via the dashboard but it gives me the following error,

```<code>Unable to create directory uploads/2015/03. Is its parent directory writable by the server?
</code>```

I read forum posts online which guided to change the folder permissions to 777. I did so but the error is still there. Please guide me. Thanks.

Note: I have also updated to the latest version of WordPress but that does not solve the problem.

答: Some time when you upload image so this issue arise just try to change  permission level to 744 but select only for directories and  try to change the permission level to 644 this time for files hope this will works for you .</p>

Title: Can't upload images to WordPress

Body:
I am trying to upload images via the dashboard but it gives me the following error,

Unable to create directory uploads/2015/03. Is its parent directory writable by the server?

I read forum posts online which guided to change the folder permissions to 777. I did so but the error is still there. Please guide me. Thanks.

Note: I have also updated to the latest version of WordPress but that does not solve the problem.


问:
How to read from socket without blocking
I ran into a problem when dealing with the server, sending me initial "greetings header" (smtp server):

I need to read this header before send any commands and receive any answers from the server, but i dont know, how to do this, because Julia seems to lack any possibility to readi from IO stream without blocking: "read" command and its analogues does not have any NB-options, nb_available always is 0 though i know exactly that server send me header and my read buffer cant be empty (and "read" command issued right after "nb_available" give me data immediately, without blocking).

```<code>julia> s=connect("smtp.mail.ru",25)
TCPSocket(RawFD(18) open, 0 bytes waiting)

julia> nb_available(s)
0

julia> nb_available(s)
0
(after 5 seconds or so...)
julia> nb_available(s)
0

julia> t=read(s,10)
10-element Array{UInt8,1}:
 0x32
 0x32
 0x30
 0x20
 0x73
 0x6d
 0x74
 0x70
 0x31
 0x34
(HOW, WHY???? nb_available==0, but read returns me 10 bytes?!)

... (read was repeated many times...)
julia> t=read(s,10)
^CERROR: InterruptException:
Stacktrace:
 [1] process_events at ./libuv.jl:82 [inlined]
 [2] wait() at ./event.jl:216
 [3] wait(::Condition) at ./event.jl:27
 [4] wait_readnb(::TCPSocket, ::Int64) at ./stream.jl:296
 [5] readbytes!(::TCPSocket, ::Array{UInt8,1}, ::Int64) at ./stream.jl:714
 [6] read(::TCPSocket, ::Int64) at ./io.jl:529
</code>```

I dont want to use @async for the simplest case described above.

Who knows, how to read from TCP socket in non-blocking mode, when i can determine some way, whether read buffer contain any data or no and/or whether next read issued by tcp client will block overall client process or no.

Is it possible in Julia without "green threads" usage?

答:
Since no-one's provided an "official" solution yet, here's the workaround I mentioned above.

Functions:

# Causes stagnant 'nb' count to be updated.
# Note asynchronous nature; this means refresh may not yet have occurred
# when function has exited.
function refreshBufsize(s)
  @async eof(s);
  return nothing;
end;
```

<p>

<pre class="lang-julia prettyprint-override"><code># Check if socket is blocked (refresh bytecount first)
# Note, since refresh is asynchronous, may misreport 'blockage' until
# 'refresh' operation is actually finished; however, if socket is actually
# unblocked, subsequent calls of this function will eventually properly
# report socket is not blocked, and in general, misreporting blockage once
# or twice when socket is actually free is probably acceptable (rather
# than other way round).
function isblocked(s)
  refreshBufsize(s)
  return nb_available(s) == 0;
end;
</code>```

# Peek contents of socket without consuming stream
function peek(s, nb)
  refreshBufsize(s)
  s.buffer.seekable = true;
  Out = read(s.buffer, nb);
  seekstart(s.buffer);
  s.buffer.seekable = false
  return Out
end;
```

<p>

<p><strong>Example:</strong> (console outputs denoted as "#>" comments, for copy-pastable code)</p>

<pre class="lang-julia prettyprint-override"><code>server = listen(9001);
sOut   = connect(9001);
sIn    = accept(server);

nb_available(sIn)
#> 0
isblocked(sIn)
#> true
refreshBufsize(sIn); # we expect no change, as we haven't written anything yet
isblocked(sIn)
#> true
write(sOut, "Greetinks and salutations!\n")
#> 27
write(sOut, "We would be honoured if you would join us.\n")
#> 43
refreshBufsize(sIn);
isblocked(sIn) # note: may say true at first (until refresh properly finished)
#> false
nb_available(sIn)
#> 27
String( peek( sIn, 10)) # peek socket contents without consuming
#> "Greetinks "
String( read( sIn, nb_available( sIn))) # read (consume) as normal
#> "Greetinks and salutations!\n"
nb_available(sIn) # note 0 even though second buffer awaiting. needs refresh!
#> 0
isblocked(sIn) # note: called "refresh" under the hood
               # (but keep async in mind, i.e. might say 'true' at first!)
#> false
nb_available(sIn)
#> 43
String( read( sIn, nb_available( sIn)))
#> "We would be honoured if you would join us.\n"
isblocked(sIn)
#> true
</code>```

EDIT: for comparison, a more typical "asynchronous" socket session (which typically relies on such "blocking" behaviour) would probably look something like this:

server = listen(9002);
sOut   = connect(9002);
sIn    = accept(server);

TaskRef = @async try
  while true
    In = String(readavailable(sIn));
    if !isempty(In); println("Received from server: $In"); else; break; end
  end
  println("Connection closed normally");
catch E
  println("Connection closed (with status $E)");
end;

write(sOut, "Stop repeating everything I say!\n");
#> Received from server: Stop repeating everything I say!

close(sIn)
#> Connection closed normally
```

Body:
I ran into a problem when dealing with the server, sending me initial "greetings header" (smtp server):

I need to read this header before send any commands and receive any answers from the server, but i dont know, how to do this, because Julia seems to lack any possibility to readi from IO stream without blocking: "read" command and its analogues does not have any NB-options, nb_available always is 0 though i know exactly that server send me header and my read buffer cant be empty (and "read" command issued right after "nb_available" give me data immediately, without blocking).

julia> s=connect("smtp.mail.ru",25)
TCPSocket(RawFD(18) open, 0 bytes waiting)

julia> nb_available(s)
0

julia> nb_available(s)
0
(after 5 seconds or so...)
julia> nb_available(s)
0

julia> t=read(s,10)
10-element Array{UInt8,1}:
 0x32
 0x32
 0x30
 0x20
 0x73
 0x6d
 0x74
 0x70
 0x31
 0x34
(HOW, WHY???? nb_available==0, but read returns me 10 bytes?!)

... (read was repeated many times...)
julia> t=read(s,10)
^CERROR: InterruptException:
Stacktrace:
 [1] process_events at ./libuv.jl:82 [inlined]
 [2] wait() at ./event.jl:216
 [3] wait(::Condition) at ./event.jl:27
 [4] wait_readnb(::TCPSocket, ::Int64) at ./stream.jl:296
 [5] readbytes!(::TCPSocket, ::Array{UInt8,1}, ::Int64) at ./stream.jl:714
 [6] read(::TCPSocket, ::Int64) at ./io.jl:529

I dont want to use @async for the simplest case described above.

Who knows, how to read from TCP socket in non-blocking mode, when i can determine some way, whether read buffer contain any data or no and/or whether next read issued by tcp client will block overall client process or no.

Is it possible in Julia without "green threads" usage?

Body:
Since no-one's provided an "official" solution yet, here's the workaround I mentioned above.

Functions:

# Causes stagnant 'nb' count to be updated.
# Note asynchronous nature; this means refresh may not yet have occurred
# when function has exited.
function refreshBufsize(s)
  @async eof(s);
  return nothing;
end;

# Check if socket is blocked (refresh bytecount first)
# Note, since refresh is asynchronous, may misreport 'blockage' until
# 'refresh' operation is actually finished; however, if socket is actually
# unblocked, subsequent calls of this function will eventually properly
# report socket is not blocked, and in general, misreporting blockage once
# or twice when socket is actually free is probably acceptable (rather
# than other way round).
function isblocked(s)
  refreshBufsize(s)
  return nb_available(s) == 0;
end;

# Peek contents of socket without consuming stream
function peek(s, nb)
  refreshBufsize(s)
  s.buffer.seekable = true;
  Out = read(s.buffer, nb);
  seekstart(s.buffer);
  s.buffer.seekable = false
  return Out
end;

Example: (console outputs denoted as "#>" comments, for copy-pastable code)

server = listen(9001);
sOut   = connect(9001);
sIn    = accept(server);

nb_available(sIn)
#> 0
isblocked(sIn)
#> true
refreshBufsize(sIn); # we expect no change, as we haven't written anything yet
isblocked(sIn)
#> true
write(sOut, "Greetinks and salutations!\n")
#> 27
write(sOut, "We would be honoured if you would join us.\n")
#> 43
refreshBufsize(sIn);
isblocked(sIn) # note: may say true at first (until refresh properly finished)
#> false
nb_available(sIn)
#> 27
String( peek( sIn, 10)) # peek socket contents without consuming
#> "Greetinks "
String( read( sIn, nb_available( sIn))) # read (consume) as normal
#> "Greetinks and salutations!\n"
nb_available(sIn) # note 0 even though second buffer awaiting. needs refresh!
#> 0
isblocked(sIn) # note: called "refresh" under the hood
               # (but keep async in mind, i.e. might say 'true' at first!)
#> false
nb_available(sIn)
#> 43
String( read( sIn, nb_available( sIn)))
#> "We would be honoured if you would join us.\n"
isblocked(sIn)
#> true

EDIT: for comparison, a more typical "asynchronous" socket session (which typically relies on such "blocking" behaviour) would probably look something like this:

server = listen(9002);
sOut   = connect(9002);
sIn    = accept(server);

TaskRef = @async try
  while true
    In = String(readavailable(sIn));
    if !isempty(In); println("Received from server: $In"); else; break; end
  end
  println("Connection closed normally");
catch E
  println("Connection closed (with status $E)");
end;

write(sOut, "Stop repeating everything I say!\n");
#> Received from server: Stop repeating everything I say!

close(sIn)
#> Connection closed normally


问:
How to select first and last  only?
My table has id="mytable". I'm trying to apply some CSS on the first and last  only. I tried this but it doesn't work.

```<code>#mytable th:first,
#mytable th:last{
 //css goes here
}
</code>```

答:
```<code>#mytable th:last-child, #mytable th:first-child {
 //css goes here
}
</code>```

Title: How to select first and last <th> only?

Body:
My table has id="mytable". I'm trying to apply some CSS on the first and last  only. I tried this but it doesn't work.

#mytable th:first,
#mytable th:last{
 //css goes here
}


问:
Making a module dependent python code run on machine without the module
I am just done with the pretty piece of code. It uses some of the modules which doesn't come preinstalled in the python. Now the issue is that to make it run a user would have to install all the modules required on the system.

How can I save user from this pain?

Is there any way to factor out only those functions in the modules which are being used and somehow package them with the code I wrote over it?

One thing that I have in my ming right now is to write a assistvie shell script to ease out users effort. But again installing modules might give pain and through errors on various system. I can't handle that.
Please suggest me something.

Thank you

Edit1:  I was little worried about the complexity to install whole of the library. I am working on the cv2 module for python (which in the background is implemented in C/C++) I can't afford to ask user install whole of the library when at the end of the day I am just using a bunch of functions from it.

PS: It took me couple of hours to install opencv

答:
Say you have the module xyz

Normally you would install that using pip

```<code>pip install xyz
</code>```

For some reason you don't have access to doing that in the environment where it's suppose to run, so instead go and clone/download the xyz repository from github into your application (preferably as a git submodule)

The xyz repo will probably look some thing like this.

```<code>XYZ repo (dir)
- xyz (dir) <-- this is where the actual module is
- readme.md
- setup.py
</code>```

Now you applications directory looks like this:

```<code>My app (dir)
- XYZ repo (dir)
- __init__.py
- myapp.py
</code>```

To be able to import xyz in myapp.py you need to add a symlink to the module directory of the XYZ Repo

```<code>ln -s XYZ\ Repo/xyz xyz
</code>```

You application now looks like this:

```<code>My app (dir)
- XYZ repo (dir)
- xyz
- __init__.py
- myapp.py
</code>```

And you can now import xyz in your code.

DISCLAIMER: This will only work for pure python libraries, if it has c dependencies they will need to be built during install time, and you need to have access to pip or at least to run the build script yourself.
Also any dependencies of the xyz package must be installed in the same way

Body:
Say you have the module xyz

Normally you would install that using pip

pip install xyz

For some reason you don't have access to doing that in the environment where it's suppose to run, so instead go and clone/download the xyz repository from github into your application (preferably as a git submodule)

The xyz repo will probably look some thing like this.

XYZ repo (dir)
- xyz (dir) <-- this is where the actual module is
- readme.md
- setup.py

Now you applications directory looks like this:

My app (dir)
- XYZ repo (dir)
- __init__.py
- myapp.py

To be able to import xyz in myapp.py you need to add a symlink to the module directory of the XYZ Repo

ln -s XYZ\ Repo/xyz xyz

You application now looks like this:

My app (dir)
- XYZ repo (dir)
- xyz
- __init__.py
- myapp.py

And you can now import xyz in your code.

DISCLAIMER: This will only work for pure python libraries, if it has c dependencies they will need to be built during install time, and you need to have access to pip or at least to run the build script yourself.
Also any dependencies of the xyz package must be installed in the same way


问:
Extract pattern and subsequent n elements from array and count number of occurences
I have an array of doubles like this:

```<code>C = [1 2 3 4 0 3 2 5 6 7 1 2 3 4 150 30]
</code>```

i want to find the pattern [1 2 3 4] within the array and then store the 2 values after that pattern with it like:

```<code>A = [1 2 3 4 0 3]
B = [1 2 3 4 150 30]
</code>```

i can find the pattern like this but i don't know how to get and store 2 values after that with the previous one.

And after finding A, B if i want to find the number of occurrences of each arrays within array C how can i do that?

```<code>indices = cellfun(@(c) strfind(c,pattern), C, 'UniformOutput', false);
</code>```

Thanks!

答:
Assuming you're fine with a cell array output, this works fine:

```<code>C = [1 2 3 4 0 3 2 5 6 7 1 2 3 4 150 30 42 1 2 3 4 0 3]
p = [1 2 3 4]
n = 2

% full patttern length - 1
dn = numel(p) + n - 1

%// find indices
ind = strfind(C,p)

%// pre check if pattern at end of array
if ind(end)+ dn  > numel(C), k = -1; else k = 0; end

%// extracting
temp = arrayfun(@(x) C(x:x+dn), ind(1:end+k) , 'uni', 0)

%// post processing
[out, ~, idx] = unique(vertcat(temp{:}),'rows','stable')
occ = histcounts(idx).'
</code>```

If the array C ends with at least n elements after the last occurrence of the pattern p, you can use the short form:

```<code>out = arrayfun(@(x) C(x:x+n+numel(p)-1), strfind(C,p) , 'uni', 0)
</code>```

```<code>out =

     1     2     3     4     0     3
     1     2     3     4   150    30

occ =

     2
     1
</code>```

Body:
I have an array of doubles like this:

C = [1 2 3 4 0 3 2 5 6 7 1 2 3 4 150 30]

i want to find the pattern [1 2 3 4] within the array and then store the 2 values after that pattern with it like:

A = [1 2 3 4 0 3]
B = [1 2 3 4 150 30]

i can find the pattern like this but i don't know how to get and store 2 values after that with the previous one.

And after finding A, B if i want to find the number of occurrences of each arrays within array C how can i do that?

indices = cellfun(@(c) strfind(c,pattern), C, 'UniformOutput', false);

Thanks!

Body:
Assuming you're fine with a cell array output, this works fine:

C = [1 2 3 4 0 3 2 5 6 7 1 2 3 4 150 30 42 1 2 3 4 0 3]
p = [1 2 3 4]
n = 2

% full patttern length - 1
dn = numel(p) + n - 1

%// find indices
ind = strfind(C,p)

%// pre check if pattern at end of array
if ind(end)+ dn  > numel(C), k = -1; else k = 0; end

%// extracting
temp = arrayfun(@(x) C(x:x+dn), ind(1:end+k) , 'uni', 0)

%// post processing
[out, ~, idx] = unique(vertcat(temp{:}),'rows','stable')
occ = histcounts(idx).'

If the array C ends with at least n elements after the last occurrence of the pattern p, you can use the short form:

out = arrayfun(@(x) C(x:x+n+numel(p)-1), strfind(C,p) , 'uni', 0)

out =

     1     2     3     4     0     3
     1     2     3     4   150    30

occ =

     2
     1


问:
How can I plot a histogram next to an image?
I would like to evaluate an idea for finding the "right" rotation of documents. The idea is to apply an edge detector and to count the white values per row and per column. In order to evaluate it, I want to plot this count (or a histogram with a small bin size) next to the image. How can I do that?

What I did

```<code>#!/usr/bin/env python

import scipy.misc
import numpy as np
import scipy.ndimage
import seaborn as sns

im = scipy.misc.imread("morc-0102.jpg", mode="L")
height, width = im.shape
k = np.array([[1, -1],
              [1, -1]])
im = scipy.ndimage.convolve(im, k, mode='constant', cval=0.0)

# Calculate histogram
hist_height = np.zeros(height)
hist_width = np.zeros(width)
for y in range(height):
    for x in range(width):
        hist_height[y] += im[y][x]
        hist_width[x] += im[y][x]
sns.distplot(hist_height, kde=False, rug=False)
sns.distplot(hist_width, kde=False, rug=False)
sns.plt.show()
scipy.misc.imshow(im)
</code>```

What I want

A visualization similar to this: At the right of the image the (normalized) counts hist_height are plotted, at the bottom the (normalized) counts hist_width are plotted.

I think I have seen something very similar before. I know how to do this manually by resizing the canvas and plotting each line "by hand", but I guess libaries like matplotlib / seaborn support this directly?

答:
How about adding two bar diagrams as subplots? Like this e.g.

```<code>import matplotlib.pyplot as plt
import numpy as np

# remove upper corner plot
ax1 = plt.subplot2grid((3, 3), (0, 2))
ax1.axis('off')

# plot some example image
imageExample = np.random.uniform(0,1,(5,5))
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2)
ax2.imshow(imageExample)
ax2.axis('off')

# use 'barh' for horizontal bar plot
horzSum = np.sum(imageExample,1)
ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2, sharey=ax2)
ax3.barh(range(len(horzSum)), horzSum)
ax3.axis('off')

vertSum = np.sum(imageExample, 0)
ax4 = plt.subplot2grid((3, 3), (0, 0), colspan=2, sharex=ax2)
ax4.bar(range(len(vertSum)), vertSum)
ax4.axis('off')

plt.subplots_adjust(wspace=0, hspace=0)
plt.show()
</code>```

Setting width of barand barhto 1 and color='r'you get something very similar to what you aim for except for the blank spaces that you can probably get rid of somehow.

Body:
I would like to evaluate an idea for finding the "right" rotation of documents. The idea is to apply an edge detector and to count the white values per row and per column. In order to evaluate it, I want to plot this count (or a histogram with a small bin size) next to the image. How can I do that?

What I did

#!/usr/bin/env python

import scipy.misc
import numpy as np
import scipy.ndimage
import seaborn as sns

im = scipy.misc.imread("morc-0102.jpg", mode="L")
height, width = im.shape
k = np.array([[1, -1],
              [1, -1]])
im = scipy.ndimage.convolve(im, k, mode='constant', cval=0.0)

# Calculate histogram
hist_height = np.zeros(height)
hist_width = np.zeros(width)
for y in range(height):
    for x in range(width):
        hist_height[y] += im[y][x]
        hist_width[x] += im[y][x]
sns.distplot(hist_height, kde=False, rug=False)
sns.distplot(hist_width, kde=False, rug=False)
sns.plt.show()
scipy.misc.imshow(im)

What I want

A visualization similar to this: At the right of the image the (normalized) counts hist_height are plotted, at the bottom the (normalized) counts hist_width are plotted.

I think I have seen something very similar before. I know how to do this manually by resizing the canvas and plotting each line "by hand", but I guess libaries like matplotlib / seaborn support this directly?

Body:
How about adding two bar diagrams as subplots? Like this e.g.

import matplotlib.pyplot as plt
import numpy as np

# remove upper corner plot
ax1 = plt.subplot2grid((3, 3), (0, 2))
ax1.axis('off')

# plot some example image
imageExample = np.random.uniform(0,1,(5,5))
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2)
ax2.imshow(imageExample)
ax2.axis('off')

# use 'barh' for horizontal bar plot
horzSum = np.sum(imageExample,1)
ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2, sharey=ax2)
ax3.barh(range(len(horzSum)), horzSum)
ax3.axis('off')

vertSum = np.sum(imageExample, 0)
ax4 = plt.subplot2grid((3, 3), (0, 0), colspan=2, sharex=ax2)
ax4.bar(range(len(vertSum)), vertSum)
ax4.axis('off')

plt.subplots_adjust(wspace=0, hspace=0)
plt.show()

Setting width of barand barhto 1 and color='r'you get something very similar to what you aim for except for the blank spaces that you can probably get rid of somehow.


问:
Class constructor's caller function
Is there a way to get the caller function of the class's constructor?

```<code>class TestClass {
  constructor(options) {
    if(<caller> !== TestClass.create)
      throw new Error('Use TestClass.create() instead')
    this.options = options
  }

  static async create(options) {
    // async options check
    return new TestClass(options)
  }
}

let test = await TestClass.create()
</code>```

I've tried arguments.callee.caller and TestClass.caller but I get the following error:

```<code>Uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them

Uncaught TypeError: 'caller' and 'arguments' are restricted function properties and cannot be accessed in this context.
</code>```

Testing in Chrome 58

答:
You could achieve this in a different way: just refuse any use of the constructor, and let the create method create an object instance with Object.create (which will not call the constructor):

```<code>class TestClass {
    constructor() {
        throw new Error('Use TestClass.create() instead');
    }

    static async create(options) {
        // async options check
        const obj = Object.create(TestClass.prototype);
        obj.options = options;
        return obj;
    }
}
</code>```

Title: Class constructor's caller function

Body:
Is there a way to get the caller function of the class's constructor?

class TestClass {
  constructor(options) {
    if(<caller> !== TestClass.create)
      throw new Error('Use TestClass.create() instead')
    this.options = options
  }

  static async create(options) {
    // async options check
    return new TestClass(options)
  }
}

let test = await TestClass.create()

I've tried arguments.callee.caller and TestClass.caller but I get the following error:

Uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them

Uncaught TypeError: 'caller' and 'arguments' are restricted function properties and cannot be accessed in this context.

Testing in Chrome 58

Body:
You could achieve this in a different way: just refuse any use of the constructor, and let the create method create an object instance with Object.create (which will not call the constructor):

class TestClass {
    constructor() {
        throw new Error('Use TestClass.create() instead');
    }

    static async create(options) {
        // async options check
        const obj = Object.create(TestClass.prototype);
        obj.options = options;
        return obj;
    }
}


答:
A simple solution can be:</p>

```<code>C = [1 2 3 4 0 3 2 5 6 7 1 2 3 4 150 30];
pattern = [1 2 3 4];
numberOfAddition = 2;
outputs = zeros(length(A),length(pattern)+ numberOfAddition); % preallocation
numberOfFoundPattern =  1;
lengthOfConsider = length(C) - length(pattern) - numberOfAddition;
for i = 1:lengthOfConsider
     if(sum(C(i:i+length(pattern)) - pattern) == 0) % find pattern
         outputs(numberOfFoundPattern,:) = C(i:i+length(pattern)+numberOfAddition);
         numberOfFoundPattern = numberOfFoundPattern + 1;
     end
end
outputs = outputs(1:numberOfFoundPattern - 1,:);
</code>```

Title: Extract pattern and subsequent n elements from array and count number of occurences

Body:
A simple solution can be:

C = [1 2 3 4 0 3 2 5 6 7 1 2 3 4 150 30];
pattern = [1 2 3 4];
numberOfAddition = 2;
outputs = zeros(length(A),length(pattern)+ numberOfAddition); % preallocation
numberOfFoundPattern =  1;
lengthOfConsider = length(C) - length(pattern) - numberOfAddition;
for i = 1:lengthOfConsider
     if(sum(C(i:i+length(pattern)) - pattern) == 0) % find pattern
         outputs(numberOfFoundPattern,:) = C(i:i+length(pattern)+numberOfAddition);
         numberOfFoundPattern = numberOfFoundPattern + 1;
     end
end
outputs = outputs(1:numberOfFoundPattern - 1,:);


问:
Toggling ul inside an li only animates when closing
I'm trying to open a checkbox of ingredients and it does that just without the animation.

as mentioned on the subject here follows my code:

HTML

```<code><div class="col-xs-12">
    <div class="recipePicContainer">
        <div id="checkBoxes">
                <li class="recipe"></li>
                       <ul>
                           <ul><input type="checkbox"> ingredient 1</ul>
                           <ul><input type="checkbox"> ingredient 2</ul>
                           <ul><input type="checkbox"> ingredient 3</ul>
                           <ul><input type="checkbox"> ingredient 4</ul>
                           <ul>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</ul>
                       </ul>
                </div>
            </div>
        </div>
</code>```

Javascript

```<code> var main = function() {
     $(document).ready(function(){
         $('ul').hide();
         $('.recipe').click(function () {
             $('ul').toggle("slow");
         });
    }); }; $(document).ready(main);
</code>```

Thanx guys!

答:
Is this what you're looking for? Fading it in with .fadeIn(). Also added an ID to the ul containing all the checkboxes.

$(document).ready(function(){
     $('#ingredients').hide();
     $('.recipe').click(function () {
         $('#ingredients').fadeIn();
     });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-xs-12">
  <div class="recipePicContainer">
    <div id="checkBoxes">
        <li class="recipe">Click me</li>
           <ul id="ingredients">
             <ul><input type="checkbox"> ingredient 1</ul>
             <ul><input type="checkbox"> ingredient 2</ul>
             <ul><input type="checkbox"> ingredient 3</ul>
             <ul><input type="checkbox"> ingredient 4</ul>
             <ul>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</ul>
         </ul>
    </div>
  </div>
</div></code>```

Body:
I'm trying to open a checkbox of ingredients and it does that just without the animation.

as mentioned on the subject here follows my code:

HTML

<input type="checkbox"> ingredient 1

<input type="checkbox"> ingredient 2

<input type="checkbox"> ingredient 3

<input type="checkbox"> ingredient 4

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Javascript

 var main = function() {
     $(document).ready(function(){
         $('ul').hide();
         $('.recipe').click(function () {
             $('ul').toggle("slow");
         });
    }); }; $(document).ready(main);

Thanx guys!

Body:
Is this what you're looking for? Fading it in with .fadeIn(). Also added an ID to the ul containing all the checkboxes.

$(document).ready(function(){
     $('#ingredients').hide();
     $('.recipe').click(function () {
         $('#ingredients').fadeIn();
     });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-xs-12">
  <div class="recipePicContainer">
    <div id="checkBoxes">
        <li class="recipe">Click me</li>
           <ul id="ingredients">
             <ul><input type="checkbox"> ingredient 1</ul>
             <ul><input type="checkbox"> ingredient 2</ul>
             <ul><input type="checkbox"> ingredient 3</ul>
             <ul><input type="checkbox"> ingredient 4</ul>
             <ul>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</ul>
         </ul>
    </div>
  </div>
</div>


问:
Nice way of doing dual column validation
I'm using Rails 3 for this one.  I've got a collections model, a user model and an intermediate subscription model.  This way a user can subscribe to multiple collections, with a particular role.  However, I don't want a user to be able to subscribe to the same collection twice.

So in my Subscription model I've got something like:

```<code>validate :subscription_duplicates

def subscription_duplicates
  self.errors.add_to_base "This user is already subscribed" if Subscription.where(:user_id => self.user.id, :collection_id => self.collection.id)
end
</code>```

However this seems ugly.  Also, it breaks when I want to do something like the following in my collection controller:

```<code>def create
  @collection = Collection.new(params[:collection])
  @collection.subscriptions.build(:user => current_user, :role => Subscription::ROLES['owner'])
  @collection.save
  respond_with(@collection)
end
</code>```

When I do the build the subscription does not have an id so I get a "Called id for nil" error.

Thanks for any guidance!

答:
use validates_uniqueness_of</p>

```<code>validates_uniqueness_of :user_id, :scope => :collection_id
</code>```

Body:
I'm using Rails 3 for this one.  I've got a collections model, a user model and an intermediate subscription model.  This way a user can subscribe to multiple collections, with a particular role.  However, I don't want a user to be able to subscribe to the same collection twice.

So in my Subscription model I've got something like:

validate :subscription_duplicates

def subscription_duplicates
  self.errors.add_to_base "This user is already subscribed" if Subscription.where(:user_id => self.user.id, :collection_id => self.collection.id)
end

However this seems ugly.  Also, it breaks when I want to do something like the following in my collection controller:

def create
  @collection = Collection.new(params[:collection])
  @collection.subscriptions.build(:user => current_user, :role => Subscription::ROLES['owner'])
  @collection.save
  respond_with(@collection)
end

When I do the build the subscription does not have an id so I get a "Called id for nil" error.

Thanks for any guidance!

Body:
use validates_uniqueness_of

validates_uniqueness_of :user_id, :scope => :collection_id


问:
How to group SQL Value if the column is same value
Needed help with SQL, tried for a while and still cant figure it out

MY Create Table

```<code>CREATE TABLE Data
(
    Sender              VARCHAR(255),
    Receiver            VARCHAR(255),
    MSG                 VARCHAR(255),
);
</code>```

After Insert VALUES

```<code>SEND1   REC1    Hey whats up
SEND1   REC2    Yoo how are you
SEND1   REC1    Nothing much
</code>```

What I've been trying to do is to

```<code>Select * FROM DATA WHERE Sender = 'SEND1'
</code>```

However, I just wanted to show the second row and third row, basically if the SENDER and RECEIVER is same as previous row, ignore the previous row and took the last row only and no duplication of the same same SENDER and RECEIVER

Thanks

I am using SQL-SERVER

What I meant is to always take the last row of the same 'Sender' and 'Receiver', the first row and third row has same sender and receiver, so when I select statement, I just want the last one

答:
Assuming that you have unique/PK id column and higher value means latest record. Then you can use:

```<code>select DATA.* from DATA
join(
    select max(id) as maxid
    from DATA
    group by Sender, Receiver
)t
on DATA.id = t.maxid
</code>```

Body:
Needed help with SQL, tried for a while and still cant figure it out

MY Create Table

CREATE TABLE Data
(
    Sender              VARCHAR(255),
    Receiver            VARCHAR(255),
    MSG                 VARCHAR(255),
);

After Insert VALUES

SEND1   REC1    Hey whats up
SEND1   REC2    Yoo how are you
SEND1   REC1    Nothing much

What I've been trying to do is to

Select * FROM DATA WHERE Sender = 'SEND1'

However, I just wanted to show the second row and third row, basically if the SENDER and RECEIVER is same as previous row, ignore the previous row and took the last row only and no duplication of the same same SENDER and RECEIVER

Thanks

I am using SQL-SERVER

What I meant is to always take the last row of the same 'Sender' and 'Receiver', the first row and third row has same sender and receiver, so when I select statement, I just want the last one

Body:
Assuming that you have unique/PK id column and higher value means latest record. Then you can use:

select DATA.* from DATA
join(
    select max(id) as maxid
    from DATA
    group by Sender, Receiver
)t
on DATA.id = t.maxid


问:
I need a batch program to find the folder name inside another folder
For example

consider:

```<code>H:\reports\test\12345\dailynews.pdf
</code>```

I want to send this PDF through mail by using MSSQL job (sql server 2008 R2).
But every time when another job creates the pdf file the location changes.
like

```<code>H:\reports\test\48596\dailynews.pdf
</code>```

I need a batch program to find the folder name which is present after the test folder.

答:
Regarding the given info, I would suggest to
split the string at the backslashes and extract the 4th element like this:

```<code>set p=H:\reports\test\12345\dailynews.pdf
for /F "delims=\ tokens=4" %%a in ("%p%") do echo %%a
</code>```

Note the double quotes ("%p%"), so it gets interpreted as string (and not as a filename or command).

If you want to make sure, that the 3rd element is the test folder, then I would suggest:

```<code>set p=H:\reports\test\12345\dailynews.pdf
set o=H:\reports\live\55555\dailynews.pdf

for /F "delims=\ tokens=3,4" %%a in ("%p%") do if "%%a"=="test" echo %%b
for /F "delims=\ tokens=3,4" %%a in ("%o%") do if "%%a"=="test" echo %%b
</code>```

Outputs 12345 but not 55555, which is in the live folder.

Edit:
I realized that my answer left out completely, how one can detect the newest dailynews.pdf, which is what the OP probably looking for.
Like the dailynews routine runs at 21.00, and you want to mail that report at 22.00. (Again, yet another assumption.)

IMO, the tricky part is to parse and compare the date/time info of the files.
A simple dir dailynews.txt /S /O:-D does not work with subdirs.

So...

```<code>@echo off
cls

set base=H:\reports\test
set filename=dailynews.pdf

set current_date=19000101
set current_time=0000
set current_file=

::debug output
dir "%filename%" /S /O:-D

:: inspect each entry
for /F "usebackq" %%a in (`dir "%filename%" /S /B /O:-D`) do call :inspect "%%a"

:: all done, quit
goto :quit

:: subroutine for comparing current with actual newest entry
:inspect
echo %1

set _date=
set _time=

:: get comparable date time info
:: change to your regional date/time settings/locale! (german here)
:: maybe check SO for other locales
for /F "usebackq tokens=1,2,3,4,5 delims=.: " %%a in (`dir %1^|findstr "%filename%"`) do echo %%a %%b %%c %%d %%e&set _date=%%c%%b%%a&set _time=%%d%%e

:: we have to split in two components, otherwise it seems too big for comparing
if /I %_date% LSS %current_date% goto :eof
if /I %_time% LSS %current_time% goto :eof

:: this one is newer! set new values
set current_date=%_date%
set current_time=%_time%
set current_file=%1

goto :eof

:quit
set current_
</code>```

Performance may get worse if you dont clean up the basedir at some time.

Body:
For example

consider:

H:\reports\test\12345\dailynews.pdf

I want to send this PDF through mail by using MSSQL job (sql server 2008 R2).
But every time when another job creates the pdf file the location changes.
like

H:\reports\test\48596\dailynews.pdf

I need a batch program to find the folder name which is present after the test folder.

Body:
Regarding the given info, I would suggest to
split the string at the backslashes and extract the 4th element like this:

set p=H:\reports\test\12345\dailynews.pdf
for /F "delims=\ tokens=4" %%a in ("%p%") do echo %%a

Note the double quotes ("%p%"), so it gets interpreted as string (and not as a filename or command).

If you want to make sure, that the 3rd element is the test folder, then I would suggest:

set p=H:\reports\test\12345\dailynews.pdf
set o=H:\reports\live\55555\dailynews.pdf

for /F "delims=\ tokens=3,4" %%a in ("%p%") do if "%%a"=="test" echo %%b
for /F "delims=\ tokens=3,4" %%a in ("%o%") do if "%%a"=="test" echo %%b

Outputs 12345 but not 55555, which is in the live folder.

Edit:
I realized that my answer left out completely, how one can detect the newest dailynews.pdf, which is what the OP probably looking for.
Like the dailynews routine runs at 21.00, and you want to mail that report at 22.00. (Again, yet another assumption.)

IMO, the tricky part is to parse and compare the date/time info of the files.
A simple dir dailynews.txt /S /O:-D does not work with subdirs.

So...

@echo off
cls

set base=H:\reports\test
set filename=dailynews.pdf

set current_date=19000101
set current_time=0000
set current_file=

::debug output
dir "%filename%" /S /O:-D

:: inspect each entry
for /F "usebackq" %%a in (`dir "%filename%" /S /B /O:-D`) do call :inspect "%%a"

:: all done, quit
goto :quit

:: subroutine for comparing current with actual newest entry
:inspect
echo %1

set _date=
set _time=

:: get comparable date time info
:: change to your regional date/time settings/locale! (german here)
:: maybe check SO for other locales
for /F "usebackq tokens=1,2,3,4,5 delims=.: " %%a in (`dir %1^|findstr "%filename%"`) do echo %%a %%b %%c %%d %%e&set _date=%%c%%b%%a&set _time=%%d%%e

:: we have to split in two components, otherwise it seems too big for comparing
if /I %_date% LSS %current_date% goto :eof
if /I %_time% LSS %current_time% goto :eof

:: this one is newer! set new values
set current_date=%_date%
set current_time=%_time%
set current_file=%1

goto :eof

:quit
set current_

Performance may get worse if you dont clean up the basedir at some time.


问:
Pass an object to a function or sub procedure
I am trying to pass and excel work book off to a sub procedure with out having to open and close it again.

I tried this

```<code>Dim ExcelApp As New Excel.Application
Dim ws As Object

Public Function cert()
Set ws = ExcelApp.Workbooks.Open(FileDir).Sheets(1)
If CheckForMutipleUIC(ws) = True Then <---- this is where I call the Function
....
</code>```

The function opens to this

```<code>Public Function CheckForMutipleUIC(ByVal ws As Excel.Workbook) As Boolean
'    Dim ExcelApp As New Excel.Application
'    DataFleet = CurrentProject.Path & "\Extract\Fleet.xls"
'    Set ws1 = ExcelApp.Workbooks.Open(DataFleet).Sheets(1)
UICCheck = ws.Range("GD2").Value
For Each Cell In ws.Range("GD2:GD10000").cells
    If Cell.Text <> "" Then
        If Cell.Value <> UICCheck Then
            Err.Raise 513, "VICILauncher-DataValidation-CheckForMultipleUIC", "Multiple UICS Found in extract. Please Make sure the correct UIC is being Extracted"
        End If
    End If
Next
CheckForMutipleUIC = True
Exit Function
</code>```

But I guess I'm not passing the Excel object properly. How are applications objects passed to sub with out close and reopening.

答:
You may have to use ByRef (and the correct declaration as already mentioned):

```<code>Public Function CheckForMutipleUIC(ByRef ws As Excel.Worksheet) As Boolean
</code>```

Body:
I am trying to pass and excel work book off to a sub procedure with out having to open and close it again.

I tried this

Dim ExcelApp As New Excel.Application
Dim ws As Object

Public Function cert()
Set ws = ExcelApp.Workbooks.Open(FileDir).Sheets(1)
If CheckForMutipleUIC(ws) = True Then <---- this is where I call the Function
....

The function opens to this

Public Function CheckForMutipleUIC(ByVal ws As Excel.Workbook) As Boolean
'    Dim ExcelApp As New Excel.Application
'    DataFleet = CurrentProject.Path & "\Extract\Fleet.xls"
'    Set ws1 = ExcelApp.Workbooks.Open(DataFleet).Sheets(1)
UICCheck = ws.Range("GD2").Value
For Each Cell In ws.Range("GD2:GD10000").cells
    If Cell.Text <> "" Then
        If Cell.Value <> UICCheck Then
            Err.Raise 513, "VICILauncher-DataValidation-CheckForMultipleUIC", "Multiple UICS Found in extract. Please Make sure the correct UIC is being Extracted"
        End If
    End If
Next
CheckForMutipleUIC = True
Exit Function

But I guess I'm not passing the Excel object properly. How are applications objects passed to sub with out close and reopening.

Body:
You may have to use ByRef (and the correct declaration as already mentioned):

Public Function CheckForMutipleUIC(ByRef ws As Excel.Worksheet) As Boolean


答:
Do the ingredients need to be separate ul elements? Changing those to li elements fixed the issue.

I also recommend using classes on your elements and selecting based on those classes, rather than selecting and toggling all ul elements on the page.

var main = function() {
  $(document).ready(function() {
    $('ul').hide();
    $('.recipe').click(function() {
      $('ul').toggle("slow");
    });
  });
};
$(document).ready(main);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-xs-12">
  <div class="recipePicContainer">
    <div id="checkBoxes">
      <li class="recipe">Click</li>
      <ul>
        <li><input type="checkbox"> ingredient 1</li>
        <li><input type="checkbox"> ingredient 2</li>
        <li><input type="checkbox"> ingredient 3</li>
        <li><input type="checkbox"> ingredient 4</li>
        <li>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
      </ul>
    </div>
  </div>
</div></code>```

Title: Toggling ul inside an li only animates when closing

Body:
Do the ingredients need to be separate ul elements? Changing those to li elements fixed the issue.

I also recommend using classes on your elements and selecting based on those classes, rather than selecting and toggling all ul elements on the page.

var main = function() {
  $(document).ready(function() {
    $('ul').hide();
    $('.recipe').click(function() {
      $('ul').toggle("slow");
    });
  });
};
$(document).ready(main);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-xs-12">
  <div class="recipePicContainer">
    <div id="checkBoxes">
      <li class="recipe">Click</li>
      <ul>
        <li><input type="checkbox"> ingredient 1</li>
        <li><input type="checkbox"> ingredient 2</li>
        <li><input type="checkbox"> ingredient 3</li>
        <li><input type="checkbox"> ingredient 4</li>
        <li>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
      </ul>
    </div>
  </div>
</div>


问:
Disable sorting for a few cells in datatables jQuery
Simply I'm trying to make it ignore sorting if the cell has ?

this is my table:

```<code>ID | name  | supply
1  | John  | 12
2  | Kayle | ?
3  | Tim   | 24
</code>```

when you sort supply by asc

```<code>ID | name  | supply
1  | John  | 12
3  | Tim   | 24
2  | Kayle | ?
</code>```

when you sort supply by desc

```<code>ID | name  | supply
3  | Tim   | 24
1  | John  | 12
2  | Kayle | ?
</code>```

IS there a way to do it?

答:
You need to use Absolute position sorting plug-in.

For example:

```<code>var nameType = $.fn.dataTable.absoluteOrder({
    value: '?', position: 'bottom'
});

var table = $('#example').DataTable({
    columnDefs: [
        { targets: 0, type: nameType }
    ]
});
</code>```

You need to include absolute.js file in addition to DataTables CSS/JS files.

See this example for code and demonstration.

Body:
Simply I'm trying to make it ignore sorting if the cell has ?

this is my table:

ID | name  | supply
1  | John  | 12
2  | Kayle | ?
3  | Tim   | 24

when you sort supply by asc

ID | name  | supply
1  | John  | 12
3  | Tim   | 24
2  | Kayle | ?

when you sort supply by desc

ID | name  | supply
3  | Tim   | 24
1  | John  | 12
2  | Kayle | ?

IS there a way to do it?

Body:
You need to use Absolute position sorting plug-in.

For example:

var nameType = $.fn.dataTable.absoluteOrder({
    value: '?', position: 'bottom'
});

var table = $('#example').DataTable({
    columnDefs: [
        { targets: 0, type: nameType }
    ]
});

You need to include absolute.js file in addition to DataTables CSS/JS files.

See this example for code and demonstration.


问:
To get the 3rd line from a file as string (w/o new line)
instead of using while loops.

or instead of doing the following to get the 3rd line from a file.

is there a better way ?

perhaps with fseek ? if so how.

```<code>FILE *fp;
fp = fopen(path, "r");

char line_one[100];
char line_two[100];
char line_three[100];

fgets(line_one, sizeof line_one, fp);
fgets(line_two, sizeof line_two, fp);
fgets(line_three, sizeof line_three, fp);
fclose(fp);

line_three[strcspn(line_three, "\n")] = 0;
</code>```

答:
try

```<code>fseek(fb,200,SEEK_SET);
fread(buffer,sizeof(char),100,fb)
</code>```

where buffer an array to read in

Body:
instead of using while loops.

or instead of doing the following to get the 3rd line from a file.

is there a better way ?

perhaps with fseek ? if so how.

FILE *fp;
fp = fopen(path, "r");

char line_one[100];
char line_two[100];
char line_three[100];

fgets(line_one, sizeof line_one, fp);
fgets(line_two, sizeof line_two, fp);
fgets(line_three, sizeof line_three, fp);
fclose(fp);

line_three[strcspn(line_three, "\n")] = 0;

Body:
try

fseek(fb,200,SEEK_SET);
fread(buffer,sizeof(char),100,fb)

where buffer an array to read in


答:
Check this

https://jsfiddle.net/sandmehta2014/ccy7s0pe/

I just changed following:

```<code><li class="recipe">
                       <ul>
                           <li><input type="checkbox"> ingredient 1</li>
                           <li><input type="checkbox"> ingredient 2</li>
                           <li><input type="checkbox"> ingredient 3</li>
                           <li><input type="checkbox"> ingredient 4</li>
                           <li>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
                       </ul>
                      </li>
</code>```

I guess you have taken ul in place of li.

Body:
Check this

https://jsfiddle.net/sandmehta2014/ccy7s0pe/

I just changed following:

<li class="recipe">
                       <ul>
                           <li><input type="checkbox"> ingredient 1</li>
                           <li><input type="checkbox"> ingredient 2</li>
                           <li><input type="checkbox"> ingredient 3</li>
                           <li><input type="checkbox"> ingredient 4</li>
                           <li>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
                       </ul>
                      </li>

I guess you have taken ul in place of li.


问:
Visual Studio C# Plot a Local Map
I have a GPS module that give me GPS value. I crop an image of a map(Google) around my area. I want to use the image(map) and plot it from the GPS value with visual studio c# (winform) locally without connecting to the internet. Any sample code so that I can start the project?
Thank you.</p>

答:
without internet it may not possible.
and one more thing that you must have location access from your device.</p>

Title: Visual Studio C# Plot a Local Map


问:
Disable click propagation for href
This code snippet explains my case:

$("#b").click(function(e) {
  e.stopPropagation();
});

$("#b").click(function() {
  alert("trigger div");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a {
  display: block;
  position: relative;
  width: 100px;
  height: 100px;
  background-color: gray;
}

div {
  position: absolute;
  width: 50px;
  height: 50px;
  top: 0;
  left: 0;
  background-color: red;
}</code>```

Test

```

The problem is that I only want to trigger the click function from the div and not the href from the a tag. In a similar question I found event.stopPropagation(), but that does not work in this case.

答:
without javascript:

#a {
  display: block;
  position: absolute;
  width: 100px;
  height: 100px;
  background-color: gray;
}

div {
  position: absolute;
  width: 50px;
  height: 50px;
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
<div onclick="alert('trigger div')">test</div>
</code>```

Title: Disable click propagation for href

Body:
This code snippet explains my case:

$("#b").click(function(e) {
  e.stopPropagation();
});

$("#b").click(function() {
  alert("trigger div");
});

a {
  display: block;
  position: relative;
  width: 100px;
  height: 100px;
  background-color: gray;
}

div {
  position: absolute;
  width: 50px;
  height: 50px;
  top: 0;
  left: 0;
  background-color: red;
}

Test

The problem is that I only want to trigger the click function from the div and not the href from the a tag. In a similar question I found event.stopPropagation(), but that does not work in this case.

Body:
without javascript:

#a {
  display: block;
  position: absolute;
  width: 100px;
  height: 100px;
  background-color: gray;
}

div {
  position: absolute;
  width: 50px;
  height: 50px;
  background-color: red;
}

<a href="stackoverflow.com" id="a">
<a href="#"><div onclick="alert('trigger div')">test</div></a>
</a>


问:
transform xml to xsl
I'm calling a web service, it is returning result in XML format. How do I convert returning XML into XSL and display that in web browser?</p>

答:
You use XSLT to convert XML into something else.  XSLT is a full programming language which takes some time to learn, but fortunately is fully available in the current version of Java.

You might find this link interesting: http://onjava.com/pub/a/onjava/excerpt/java_xslt_ch5/index.html

Title: transform xml to xsl


问:
Cannot use object of type stdClass as array error in laravel 5.4
I am using Laravel 5.4 when I get the image using id with map function and return the image directory I got this error

This is function inside controller

```<code> $shipping = DB::table('shipping')
            ->select('shipping.id','products.name','shipping.is_return','shipping.pro_id as pid','shipping.tracking_url')
            ->join('products','shipping.pro_id','=','products.id')
            ->orderBy('shipping.id', 'desc')
            ->limit('5')->get();

        $shipping->map(function ($ship) {
           $directory = 'uploads/products/images/'.$ship->pid;
           if (is_dir($directory)) {
            $files = scandir ($directory);
            $img_file = $directory.'/'.$files[2];
            $ship->front_img = $img_file;
            print_r($ship['front_img']);exit;
           }
         });
</code>```

When I try to print the output it shows the error.

答:
You are trying to get value using array but $ship is object

```<code>$shipping = DB::table('shipping')->select('shipping.id','products.name','shipping.is_return','shipping.pro_id as pid','shipping.tracking_url')
            ->join('products','shipping.pro_id','=','products.id')
            ->orderBy('shipping.id', 'desc')
            ->limit('5')->get();

        $shipping->map(function ($ship) {
           $directory = 'uploads/products/images/'.$ship->pid;
           if (is_dir($directory)) {
            $files = scandir ($directory);
            $img_file = $directory.'/'.$files[2];
            $ship->front_img = $img_file;
            print_r($ship->front_img);exit; //change here
           }
         });
</code>```

Body:
I am using Laravel 5.4 when I get the image using id with map function and return the image directory I got this error

This is function inside controller

 $shipping = DB::table('shipping')
            ->select('shipping.id','products.name','shipping.is_return','shipping.pro_id as pid','shipping.tracking_url')
            ->join('products','shipping.pro_id','=','products.id')
            ->orderBy('shipping.id', 'desc')
            ->limit('5')->get();

        $shipping->map(function ($ship) {
           $directory = 'uploads/products/images/'.$ship->pid;
           if (is_dir($directory)) {
            $files = scandir ($directory);
            $img_file = $directory.'/'.$files[2];
            $ship->front_img = $img_file;
            print_r($ship['front_img']);exit;
           }
         });

When I try to print the output it shows the error.

Body:
You are trying to get value using array but $ship is object

$shipping = DB::table('shipping')->select('shipping.id','products.name','shipping.is_return','shipping.pro_id as pid','shipping.tracking_url')
            ->join('products','shipping.pro_id','=','products.id')
            ->orderBy('shipping.id', 'desc')
            ->limit('5')->get();

        $shipping->map(function ($ship) {
           $directory = 'uploads/products/images/'.$ship->pid;
           if (is_dir($directory)) {
            $files = scandir ($directory);
            $img_file = $directory.'/'.$files[2];
            $ship->front_img = $img_file;
            print_r($ship->front_img);exit; //change here
           }
         });