问:
SAS fill gap in serial numbers
I have a dataset &RAWDATA that's similar to the following sample:

```<code>| Symbol | Date     | Time | BB | BO | MIDPRICE |
|--------|----------|------|----|----|----------|
| AAPL   | 20130102 | 2    | 2  | 3  | 2.5      |
| AAPL   | 20130102 | 3    | 1  | 3  | 1.5      |
| ...    |          |      |    |    |          |
| AAPL   | 20130102 | 100  | 3  | 4  |  3.5     |
| FB     | 20130102 | 1    | 3  | 6  | 4.5      |
| FB     | 20130102 | 3    | 3  | 5  | 4        |
| ...    |          |      |    |    |          |
| FB     | 20130102 | 100  | 3  | 4  |  3.5     |
</code>```

There is only one row for each Symbol at a specific time.

Now, I want to process this dataset so that the time variable starts from 1 and is continuous. If there is no record at a specific time, then create a new record at that time, set all values to the previous record.

The correct output should be something like:

```<code>| Symbol | Date     | Time | BB | BO | MIDPRICE |
|--------|----------|------|----|----|----------|
| AAPL   | 20130102 | 1    | 2  | 3  | 2.5      |
| AAPL   | 20130102 | 2    | 2  | 3  | 2.5      |
| AAPL   | 20130102 | 3    | 1  | 3  | 1.5      |
| ...    |          |      |    |    |          |
| AAPL   | 20130102 | 100  | 3  | 4  |  3.5     |
| FB     | 20130102 | 1    | 3  | 6  | 4.5      |
| FB     | 20130102 | 2    | 3  | 6  | 4.5      |
| FB     | 20130102 | 3    | 3  | 5  | 4        |
| ...    |          |      |    |    |          |
| FB     | 20130102 | 100  | 3  | 4  |  3.5     |
</code>```

I have tried the following code, but it doesn't seem to work well:

```<code>/*
 * Macro to fill in the gap seconds
 */
%MACRO GAP_SEC(RAWDATA);
  data GAPDATA;
    SET &RAWDATA; by symbol date;
    retain SYMBOL DATE TIME BB BO MIDPRICE;
    LAG_SYMBOL = lag(SYMBOL);
    LAG_DATE = lag(DATE);
    LAG_TIME = lag(TIME);
    LAG_BB = lag(BB);
    LAG_BO = lag(BO);
    LAG_MIDPRICE = lag(MIDPRICE);
    if first.symbol and first.date then
   DO;
    if TIME NE 1;
    N = TIME - 1;
    DO WHILE(N>1);
    SYMBOL=SYMBOL;
    BB=BB;
    BO=BO;
    MIDPRICE = MIDPRICE;
    TIME=TIME-1;
    output;
    n=n-1;
    END;
   END;
else
do;
    TIME_DIFF = TIME - LAG_TIME;
    if TIME_DIFF > 1 then
        DO;
            M=TIME_DIFF;
            DO WHILE(M>1);
              SYMBOL = LAG_SYMBOL;
              TIME = TIME + 1;
              DATE = LAG_DATE;
              BB = LAG_BB;
              BO = LAG_BO;
              MIDPRICE = LAG_MIDPRICE;
              output;
              M=M-1;
            END;
        END;
    end;
    drop LAG_SYMBOL LAG_DATE LAG_TIME LAG_BB LAG_BO LAG_MIDPRICE TIME_DIFF N M;
  run;
  /* Add new obs to original data set */
  proc append base=&RAWDATA data=GAPDATA;
  run;
  proc sort data=&RAWDATA force; by Symbol Date Time; run;
%mend;
</code>```

It will not fill the gap, and it also generate duplicate records with the same time and same symbol. (Note that in the original dataset, there is only one record for each symbol at a specific time). For example, the dataset might become:

```<code>| Symbol | Date     | Time | BB | BO | MIDPRICE |
|--------|----------|------|----|----|----------|
| AAPL   | 20130102 | 2    | 2  | 3  | 2.5      |
| AAPL   | 20130102 | 2    | 2  | 3  | 2.5      |
| AAPL   | 20130102 | 3    | 1  | 3  | 1.5      |
| ...    |          |      |    |    |          |
| AAPL   | 20130102 | 100  | 3  | 4  |  3.5     |
| FB     | 20130102 | 1    | 3  | 6  | 4.5      |
| FB     | 20130102 | 1    | 3  | 6  | 4.5      |
| FB     | 20130102 | 3    | 3  | 5  | 4        |
| ...    |          |      |    |    |          |
| FB     | 20130102 | 100  | 3  | 4  |  3.5     |
</code>```

What I did wrong here?

Besides, I also want all symbols end at the same time. For example, the max time can go is 100 - it cannot increase infinitely.

UPDATE:

If there is no record for time 1, I am thinking to ignore it first, and do something in the later code:

```<code>  set &RAWDATA; by Symbol;
    if not missing(Symbol);
    /* retain the price from last second */
    retain MIDPRICE CUM_RETURN;
    LAG_MIDPRICE = lag(MIDPRICE);
    LAG_CUMRETURN = lag(CUM_RETURN);
    /* Make sure we are calculating the same ticker*/
    return_sec = (MIDPRICE - LAG_MIDPRICE) / LAG_MIDPRICE;
    if first.symbol then
    do;
      CUM_RETURN = 0;
      return_sec = 0;
    end;
    CUM_RETURN  = sum(CUM_RETURN, return_sec);
    RMIN = 0.01/MIDPRICE;
    drop LAG_MIDPRICE LAG_CUMRETURN BB BO MIDPRICE CUM_RETURN RMIN;
  run;
</code>```

As you can see, I am calculating the returns for the symbols later. So, if there is no time 1, instead of setting the BB, BO or MIDPRICE to 0, I want to set the return_sec of time 1 to 0 until the first record appears.

答:
Use PROC EXPAND from SAS/ETS.  That allows you to expand a series.  The METHOD=STEP option will carry the last non-missing value forward.

I modified the example data for FB to test a variable that does not end at 100.

```<code>data have;
infile datalines delimiter="|";
informat symbol $6.
         date anydtdte.;
format date date9.;
input Symbol $ Date time bid offer mid;
datalines;
AAPL   | 20130102 | 2    | 2  | 3  | 2.5
AAPL   | 20130102 | 3    | 1  | 3  | 1.5
AAPL   | 20130102 | 100  | 3  | 4  |  3.5
FB     | 20130102 | 1    | 3  | 6  | 4.5
FB     | 20130102 | 3    | 3  | 5  | 4
FB     | 20130102 | 90  | 3  | 4  |  3.5
;
</code>```

This data step adds the values from the last value up to 100.

```<code>data have;
set have;
by symbol date;

if last.date then do;
    if time ^= 100 then do;
        do time=time to 100;
            output;
        end;
    end;
    else
        output;
end;
else
    output;
run;
</code>```

PROC EXPAND fills in the gaps.

```<code>proc expand data=have out=want to=day method=step;
by symbol date;
id time;
convert bid;
convert offer;
convert mid;
run;
</code>```

PROC EXPAND tries to be helpful and set time to a date.  Just change the format.

```<code>proc datasets lib=work nolist;
modify want;
format time best.;
run;
quit;
</code>```

Title: SAS fill gap in serial numbers

Body:
I have a dataset &RAWDATA that's similar to the following sample:

| Symbol | Date     | Time | BB | BO | MIDPRICE |
|--------|----------|------|----|----|----------|
| AAPL   | 20130102 | 2    | 2  | 3  | 2.5      |
| AAPL   | 20130102 | 3    | 1  | 3  | 1.5      |
| ...    |          |      |    |    |          |
| AAPL   | 20130102 | 100  | 3  | 4  |  3.5     |
| FB     | 20130102 | 1    | 3  | 6  | 4.5      |
| FB     | 20130102 | 3    | 3  | 5  | 4        |
| ...    |          |      |    |    |          |
| FB     | 20130102 | 100  | 3  | 4  |  3.5     |

There is only one row for each Symbol at a specific time.

Now, I want to process this dataset so that the time variable starts from 1 and is continuous. If there is no record at a specific time, then create a new record at that time, set all values to the previous record.

The correct output should be something like:

| Symbol | Date     | Time | BB | BO | MIDPRICE |
|--------|----------|------|----|----|----------|
| AAPL   | 20130102 | 1    | 2  | 3  | 2.5      |
| AAPL   | 20130102 | 2    | 2  | 3  | 2.5      |
| AAPL   | 20130102 | 3    | 1  | 3  | 1.5      |
| ...    |          |      |    |    |          |
| AAPL   | 20130102 | 100  | 3  | 4  |  3.5     |
| FB     | 20130102 | 1    | 3  | 6  | 4.5      |
| FB     | 20130102 | 2    | 3  | 6  | 4.5      |
| FB     | 20130102 | 3    | 3  | 5  | 4        |
| ...    |          |      |    |    |          |
| FB     | 20130102 | 100  | 3  | 4  |  3.5     |

I have tried the following code, but it doesn't seem to work well:

/*
 * Macro to fill in the gap seconds
 */
%MACRO GAP_SEC(RAWDATA);
  data GAPDATA;
    SET &RAWDATA; by symbol date;
    retain SYMBOL DATE TIME BB BO MIDPRICE;
    LAG_SYMBOL = lag(SYMBOL);
    LAG_DATE = lag(DATE);
    LAG_TIME = lag(TIME);
    LAG_BB = lag(BB);
    LAG_BO = lag(BO);
    LAG_MIDPRICE = lag(MIDPRICE);
    if first.symbol and first.date then
   DO;
    if TIME NE 1;
    N = TIME - 1;
    DO WHILE(N>1);
    SYMBOL=SYMBOL;
    BB=BB;
    BO=BO;
    MIDPRICE = MIDPRICE;
    TIME=TIME-1;
    output;
    n=n-1;
    END;
   END;
else
do;
    TIME_DIFF = TIME - LAG_TIME;
    if TIME_DIFF > 1 then
        DO;
            M=TIME_DIFF;
            DO WHILE(M>1);
              SYMBOL = LAG_SYMBOL;
              TIME = TIME + 1;
              DATE = LAG_DATE;
              BB = LAG_BB;
              BO = LAG_BO;
              MIDPRICE = LAG_MIDPRICE;
              output;
              M=M-1;
            END;
        END;
    end;
    drop LAG_SYMBOL LAG_DATE LAG_TIME LAG_BB LAG_BO LAG_MIDPRICE TIME_DIFF N M;
  run;
  /* Add new obs to original data set */
  proc append base=&RAWDATA data=GAPDATA;
  run;
  proc sort data=&RAWDATA force; by Symbol Date Time; run;
%mend;

It will not fill the gap, and it also generate duplicate records with the same time and same symbol. (Note that in the original dataset, there is only one record for each symbol at a specific time). For example, the dataset might become:

| Symbol | Date     | Time | BB | BO | MIDPRICE |
|--------|----------|------|----|----|----------|
| AAPL   | 20130102 | 2    | 2  | 3  | 2.5      |
| AAPL   | 20130102 | 2    | 2  | 3  | 2.5      |
| AAPL   | 20130102 | 3    | 1  | 3  | 1.5      |
| ...    |          |      |    |    |          |
| AAPL   | 20130102 | 100  | 3  | 4  |  3.5     |
| FB     | 20130102 | 1    | 3  | 6  | 4.5      |
| FB     | 20130102 | 1    | 3  | 6  | 4.5      |
| FB     | 20130102 | 3    | 3  | 5  | 4        |
| ...    |          |      |    |    |          |
| FB     | 20130102 | 100  | 3  | 4  |  3.5     |

What I did wrong here?

Besides, I also want all symbols end at the same time. For example, the max time can go is 100 - it cannot increase infinitely.

UPDATE:

If there is no record for time 1, I am thinking to ignore it first, and do something in the later code:

  set &RAWDATA; by Symbol;
    if not missing(Symbol);
    /* retain the price from last second */
    retain MIDPRICE CUM_RETURN;
    LAG_MIDPRICE = lag(MIDPRICE);
    LAG_CUMRETURN = lag(CUM_RETURN);
    /* Make sure we are calculating the same ticker*/
    return_sec = (MIDPRICE - LAG_MIDPRICE) / LAG_MIDPRICE;
    if first.symbol then
    do;
      CUM_RETURN = 0;
      return_sec = 0;
    end;
    CUM_RETURN  = sum(CUM_RETURN, return_sec);
    RMIN = 0.01/MIDPRICE;
    drop LAG_MIDPRICE LAG_CUMRETURN BB BO MIDPRICE CUM_RETURN RMIN;
  run;

As you can see, I am calculating the returns for the symbols later. So, if there is no time 1, instead of setting the BB, BO or MIDPRICE to 0, I want to set the return_sec of time 1 to 0 until the first record appears.

Body:
Use PROC EXPAND from SAS/ETS.  That allows you to expand a series.  The METHOD=STEP option will carry the last non-missing value forward.

I modified the example data for FB to test a variable that does not end at 100.

data have;
infile datalines delimiter="|";
informat symbol $6.
         date anydtdte.;
format date date9.;
input Symbol $ Date time bid offer mid;
datalines;
AAPL   | 20130102 | 2    | 2  | 3  | 2.5
AAPL   | 20130102 | 3    | 1  | 3  | 1.5
AAPL   | 20130102 | 100  | 3  | 4  |  3.5
FB     | 20130102 | 1    | 3  | 6  | 4.5
FB     | 20130102 | 3    | 3  | 5  | 4
FB     | 20130102 | 90  | 3  | 4  |  3.5
;

This data step adds the values from the last value up to 100.

data have;
set have;
by symbol date;

if last.date then do;
    if time ^= 100 then do;
        do time=time to 100;
            output;
        end;
    end;
    else
        output;
end;
else
    output;
run;

PROC EXPAND fills in the gaps.

proc expand data=have out=want to=day method=step;
by symbol date;
id time;
convert bid;
convert offer;
convert mid;
run;

PROC EXPAND tries to be helpful and set time to a date.  Just change the format.

proc datasets lib=work nolist;
modify want;
format time best.;
run;
quit;


来源: stackexchange

问:
Playing the same music file in the same time on speaker and earpiece, Android
Is it possible to do it on android? Ofc I'm talking about phones that use only one speaker for media playback. My phone is Nexus5X. I dont want to root it or mess with system files cause of warranty. So can an app without root be made to do smth like that?
<br>p.s. I tried SoundAbout didnt work. </p>

答:
I think you want to play a music file in phone speaker as well as Head Phone. If Yes means,  It's Possible.

```<code>// Read the music file from the asset folder
            afd = this.getAssets().openFd("background_music.mp3");
// Creation of new media player;
            player = new MediaPlayer();
// Set the player music source.
            player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
               player.setAudioStreamType(AudioManager.STREAM_ALARM);
// Set the looping and play the music.
            player.setLooping(true);
            player.prepare();
            player.start();
</code>```

Here player.setAudioStreamType(AudioManager.STREAM_ALARM); will act as alarm service, means the audio in the asset folder will play in both headphones and speaker.

Hope it will Help you....

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to do it on android? Ofc I'm talking about phones that use only one speaker for media playback. My phone is Nexus5X. I dont want to root it or mess with system files cause of warranty. So can an app without root be made to do smth like that?

p.s. I tried SoundAbout didnt work.

Body:
I think you want to play a music file in phone speaker as well as Head Phone. If Yes means,  It's Possible.

// Read the music file from the asset folder
            afd = this.getAssets().openFd("background_music.mp3");
// Creation of new media player;
            player = new MediaPlayer();
// Set the player music source.
            player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
               player.setAudioStreamType(AudioManager.STREAM_ALARM);
// Set the looping and play the music.
            player.setLooping(true);
            player.prepare();
            player.start();

Here player.setAudioStreamType(AudioManager.STREAM_ALARM); will act as alarm service, means the audio in the asset folder will play in both headphones and speaker.

Hope it will Help you....


问:
TestMain not run
I have a test package in go which tests some stuff that depend on reading a configuration. I want to read that configuration once before running all tests so I'm trying to use TestMain(m *testing.M):

main.go:

```<code>package tests

import (
    ...
)

var logger = logging.MustGetLogger("tests")

func TestMain(m *testing.M) {
    logger.Info("Initializing test suite")

    viper.SetConfigName("config")
    viper.AddConfigPath("..\\..\\")
    err := viper.ReadInConfig()
    if err == nil {
        os.Exit(m.Run())
    } else {
        logger.Fatal("Could not read configuration")
    }
}
</code>```

And I have another file in the same directory (and package) with a test.

repository_test.go:

```<code>package tests

import (
    ...
)

func TestCreation(t *testing.T) {
    aa := myModule.CreateRepository()
    assert.NotNil(t, aa)
}
</code>```

My problem is that the test fails because the configuration is not read from the file. When I try to debug the test in Gogland a breakpoint inside TestMain is not hit. When I run the tests from command line I don't see any printouts from TestMain.

Is there something special I should do to make it work? From what I read online I understood that if I define TestMain(m *testing.M) then it's going to run just once for the package and that's where I'm supposed to write any setup or teardown code.

答:
TestMain is only executed in test files (suffix _test.go).

Move the function to the repository_test.go file to fix this.

Title: TestMain not run

Body:
I have a test package in go which tests some stuff that depend on reading a configuration. I want to read that configuration once before running all tests so I'm trying to use TestMain(m *testing.M):

main.go:

package tests

import (
    ...
)

var logger = logging.MustGetLogger("tests")

func TestMain(m *testing.M) {
    logger.Info("Initializing test suite")

    viper.SetConfigName("config")
    viper.AddConfigPath("..\\..\\")
    err := viper.ReadInConfig()
    if err == nil {
        os.Exit(m.Run())
    } else {
        logger.Fatal("Could not read configuration")
    }
}

And I have another file in the same directory (and package) with a test.

repository_test.go:

package tests

import (
    ...
)

func TestCreation(t *testing.T) {
    aa := myModule.CreateRepository()
    assert.NotNil(t, aa)
}

My problem is that the test fails because the configuration is not read from the file. When I try to debug the test in Gogland a breakpoint inside TestMain is not hit. When I run the tests from command line I don't see any printouts from TestMain.

Is there something special I should do to make it work? From what I read online I understood that if I define TestMain(m *testing.M) then it's going to run just once for the package and that's where I'm supposed to write any setup or teardown code.


问:
Windows Forms Application Performance
My app has many controls on its surface, and more are added dynamically at runtime.

Although i am using tabs to limit the number of controls shown, and double-buffering too, it still flickers and stutters when it has to redraw (resize, maximize, etc).

What are your tips and tricks to improve WinForms app performance?

答:
I know of two things you can do but they don't always apply to all situations.

You're going to get better performance if you're using absolute positioning for each control (myNewlyCreatedButton.Location.X/Y) as opposed to using a flow layout panel or a table layout panel. WinForms has to do a lot less math trying to figure out where controls should be placed.

If there is a single operation in which you're adding/removing/modifying a lot of controls, call "SuspendLayout()" on the container of the affected controls (whether it is a panel or the whole form), and when you're done with your work call "ResumeLayout()" on the same panel. If you don't, the form will have to do a layout pass each and every time you add/remove/modify a control, which cost a lot more time.  see: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.suspendlayout(VS.80).aspx

Although, I'm not sure how these approaches could apply when resizing a window.

OwnerDisplayName: Shuft

ContentLicense: CC BY-SA 2.5

Title: Windows Forms Application Performance

OwnerDisplayName: Jon von Gillern

LastEditorDisplayName: Jon von Gillern


问:
socket.gaierror: [Errno -2] Name or service not known urllib.error.URLError: <urlopen error [Errno -2] Name or service not known>
I was looking this tutorial on how to implement convolutional neural networks.

I followed the instructions there so now I have this code:

```<code>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from subprocess import check_output
print(check_output(["ls", "../input"]).decode("utf8"))
import tensorflow as tf
from tensorflow.contrib import learn
from tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib

tf.logging.set_verbosity(tf.logging.INFO)

def cnn_model_fn(features, labels, mode):
  """Model function for CNN."""
  # Input Layer
  input_layer = tf.reshape(features, [-1, 28, 28, 1])

  # Convolutional Layer #1
  conv1 = tf.layers.conv2d(
      inputs=input_layer,
      filters=32,
      kernel_size=[5, 5],
      padding="same",
      activation=tf.nn.relu)

  # Pooling Layer #1
  pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)

  # Convolutional Layer #2 and Pooling Layer #2
  conv2 = tf.layers.conv2d(
      inputs=pool1,
      filters=64,
      kernel_size=[5, 5],
      padding="same",
      activation=tf.nn.relu)
  pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)

  # Dense Layer
  pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64])
  dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu)
  dropout = tf.layers.dropout(
      inputs=dense, rate=0.4, training=mode == learn.ModeKeys.TRAIN)

  # Logits Layer
  logits = tf.layers.dense(inputs=dropout, units=10)

  loss = None
  train_op = None

  # Calculate Loss (for both TRAIN and EVAL modes)
  if mode != learn.ModeKeys.INFER:
    onehot_labels = tf.one_hot(indices=tf.cast(labels, tf.int32), depth=10)
    loss = tf.losses.softmax_cross_entropy(
        onehot_labels=onehot_labels, logits=logits)

  # Configure the Training Op (for TRAIN mode)
  if mode == learn.ModeKeys.TRAIN:
    train_op = tf.contrib.layers.optimize_loss(
        loss=loss,
        global_step=tf.contrib.framework.get_global_step(),
        learning_rate=0.001,
        optimizer="SGD")

  # Generate Predictions
  predictions = {
      "classes": tf.argmax(
          input=logits, axis=1),
      "probabilities": tf.nn.softmax(
          logits, name="softmax_tensor")
  }

  # Return a ModelFnOps object
  return model_fn_lib.ModelFnOps(
      mode=mode, predictions=predictions, loss=loss, train_op=train_op)

def main():
    print("In main")
    # Load training and eval data
    mnist = learn.datasets.load_dataset("mnist")
    train_data = tf.train.string_input_producer(tf.train.match_filenames_once("../inputs/train/*.jpg")) # Returns np.array
    train_labels = np.asarray(train_labels.csv, dtype=np.float32)
    test_data = tf.train.string_input_producer(tf.train.match_filenames_once("../inputs/test/*.jpg")) # Returns np.array
    # eval_labels = np.asarray(mnist.test.labels, dtype=np.int32)

    # Create the Estimator
    mnist_classifier = learn.Estimator(
          model_fn=cnn_model_fn, model_dir="/tmp/mnist_convnet_model")

    # Set up logging for predictions
    tensors_to_log = {"probabilities": "softmax_tensor"}
    logging_hook = tf.train.LoggingTensorHook(
      tensors=tensors_to_log, every_n_iter=50)

    mnist_classifier.fit(
        x=train_data,
        y=train_labels,
        batch_size=100,
        steps=20000,
        monitors=[logging_hook])

    # Configure the accuracy metric for evaluation
    metrics = {
        "accuracy":
            learn.MetricSpec(
                metric_fn=tf.metrics.accuracy, prediction_key="classes"),
    }

    # Evaluate the model and print results
    eval_results = mnist_classifier.evaluate(
        x=eval_data, y=eval_labels, metrics=metrics)
    print(eval_results)

main()
</code>```

For this code, I am getting this error:

```<code>Traceback (most recent call last):
  File "/opt/conda/lib/python3.6/urllib/request.py", line 1318, in do_open
10.0s
3
    encode_chunked=req.has_header('Transfer-encoding'))
  File "/opt/conda/lib/python3.6/http/client.py", line 1239, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/opt/conda/lib/python3.6/http/client.py", line 1285, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "/opt/conda/lib/python3.6/http/client.py", line 1234, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "/opt/conda/lib/python3.6/http/client.py", line 1026, in _send_output
    self.send(msg)
  File "/opt/conda/lib/python3.6/http/client.py", line 964, in send
    self.connect()
  File "/opt/conda/lib/python3.6/http/client.py", line 1392, in connect
    super().connect()
  File "/opt/conda/lib/python3.6/http/client.py", line 936, in connect
    (self.host,self.port), self.timeout, self.source_address)
  File "/opt/conda/lib/python3.6/socket.py", line 704, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  File "/opt/conda/lib/python3.6/socket.py", line 743, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "../src/script.py", line 130, in <module>
    main()
  File "../src/script.py", line 93, in main
    mnist = learn.datasets.load_dataset("mnist")
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/__init__.py", line 73, in load_dataset
10.1s
4
    return DATASETS[name]()
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py", line 279, in load_mnist
10.2s
5
    return read_data_sets(train_dir)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py", line 235, in read_data_sets
    SOURCE_URL + TRAIN_IMAGES)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/base.py", line 208, in maybe_download
10.2s
6
    temp_file_name, _ = urlretrieve_with_retry(source_url)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/base.py", line 165, in wrapped_fn
    return fn(*args, **kwargs)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/base.py", line 190, in urlretrieve_with_retry
    return urllib.request.urlretrieve(url, filename)
  File "/opt/conda/lib/python3.6/urllib/request.py", line 248, in urlretrieve
    with contextlib.closing(urlopen(url, data)) as fp:
  File "/opt/conda/lib/python3.6/urllib/request.py", line 223, in urlopen
10.2s
7
    return opener.open(url, data, timeout)
  File "/opt/conda/lib/python3.6/urllib/request.py", line 526, in open
    response = self._open(req, data)
  File "/opt/conda/lib/python3.6/urllib/request.py", line 544, in _open
    '_open', req)
  File "/opt/conda/lib/python3.6/urllib/request.py", line 504, in _call_chain
    result = func(*args)
  File "/opt/conda/lib/python3.6/urllib/request.py", line 1361, in https_open
    context=self._context, check_hostname=self._check_hostname)
  File "/opt/conda/lib/python3.6/urllib/request.py", line 1320, in do_open
    raise URLError(err)
urllib.error.URLError: <urlopen error [Errno -2] Name or service not known>
</code>```

This message seems very unclear to me. Any idea what could be the cause of this?

答:
Seems like your script is failing in this line:

```<code>mnist = learn.datasets.load_dataset("mnist")
</code>```

because it can't find the mnist dataset locally (on disk), tries to download it, but it (for some reason) can not.

Try downloading that dataset to MNIST-data directory (Check the source for load_dataset(), which calls load_mnist() with default train_dir='MNIST-data'. Eventually, read_data_sets tries do load train/test images/labels from disk, but if not found in ./MNIST-data, tries to download them from train-images-idx3-ubyte.gz, etc.)

Body:
I was looking this tutorial on how to implement convolutional neural networks.

I followed the instructions there so now I have this code:

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from subprocess import check_output
print(check_output(["ls", "../input"]).decode("utf8"))
import tensorflow as tf
from tensorflow.contrib import learn
from tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib

tf.logging.set_verbosity(tf.logging.INFO)

def cnn_model_fn(features, labels, mode):
  """Model function for CNN."""
  # Input Layer
  input_layer = tf.reshape(features, [-1, 28, 28, 1])

  # Convolutional Layer #1
  conv1 = tf.layers.conv2d(
      inputs=input_layer,
      filters=32,
      kernel_size=[5, 5],
      padding="same",
      activation=tf.nn.relu)

  # Pooling Layer #1
  pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)

  # Convolutional Layer #2 and Pooling Layer #2
  conv2 = tf.layers.conv2d(
      inputs=pool1,
      filters=64,
      kernel_size=[5, 5],
      padding="same",
      activation=tf.nn.relu)
  pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)

  # Dense Layer
  pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64])
  dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu)
  dropout = tf.layers.dropout(
      inputs=dense, rate=0.4, training=mode == learn.ModeKeys.TRAIN)

  # Logits Layer
  logits = tf.layers.dense(inputs=dropout, units=10)

  loss = None
  train_op = None

  # Calculate Loss (for both TRAIN and EVAL modes)
  if mode != learn.ModeKeys.INFER:
    onehot_labels = tf.one_hot(indices=tf.cast(labels, tf.int32), depth=10)
    loss = tf.losses.softmax_cross_entropy(
        onehot_labels=onehot_labels, logits=logits)

  # Configure the Training Op (for TRAIN mode)
  if mode == learn.ModeKeys.TRAIN:
    train_op = tf.contrib.layers.optimize_loss(
        loss=loss,
        global_step=tf.contrib.framework.get_global_step(),
        learning_rate=0.001,
        optimizer="SGD")

  # Generate Predictions
  predictions = {
      "classes": tf.argmax(
          input=logits, axis=1),
      "probabilities": tf.nn.softmax(
          logits, name="softmax_tensor")
  }

  # Return a ModelFnOps object
  return model_fn_lib.ModelFnOps(
      mode=mode, predictions=predictions, loss=loss, train_op=train_op)

def main():
    print("In main")
    # Load training and eval data
    mnist = learn.datasets.load_dataset("mnist")
    train_data = tf.train.string_input_producer(tf.train.match_filenames_once("../inputs/train/*.jpg")) # Returns np.array
    train_labels = np.asarray(train_labels.csv, dtype=np.float32)
    test_data = tf.train.string_input_producer(tf.train.match_filenames_once("../inputs/test/*.jpg")) # Returns np.array
    # eval_labels = np.asarray(mnist.test.labels, dtype=np.int32)

    # Create the Estimator
    mnist_classifier = learn.Estimator(
          model_fn=cnn_model_fn, model_dir="/tmp/mnist_convnet_model")

    # Set up logging for predictions
    tensors_to_log = {"probabilities": "softmax_tensor"}
    logging_hook = tf.train.LoggingTensorHook(
      tensors=tensors_to_log, every_n_iter=50)

    mnist_classifier.fit(
        x=train_data,
        y=train_labels,
        batch_size=100,
        steps=20000,
        monitors=[logging_hook])

    # Configure the accuracy metric for evaluation
    metrics = {
        "accuracy":
            learn.MetricSpec(
                metric_fn=tf.metrics.accuracy, prediction_key="classes"),
    }

    # Evaluate the model and print results
    eval_results = mnist_classifier.evaluate(
        x=eval_data, y=eval_labels, metrics=metrics)
    print(eval_results)

main()

For this code, I am getting this error:

Traceback (most recent call last):
  File "/opt/conda/lib/python3.6/urllib/request.py", line 1318, in do_open
10.0s
3
    encode_chunked=req.has_header('Transfer-encoding'))
  File "/opt/conda/lib/python3.6/http/client.py", line 1239, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/opt/conda/lib/python3.6/http/client.py", line 1285, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "/opt/conda/lib/python3.6/http/client.py", line 1234, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "/opt/conda/lib/python3.6/http/client.py", line 1026, in _send_output
    self.send(msg)
  File "/opt/conda/lib/python3.6/http/client.py", line 964, in send
    self.connect()
  File "/opt/conda/lib/python3.6/http/client.py", line 1392, in connect
    super().connect()
  File "/opt/conda/lib/python3.6/http/client.py", line 936, in connect
    (self.host,self.port), self.timeout, self.source_address)
  File "/opt/conda/lib/python3.6/socket.py", line 704, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  File "/opt/conda/lib/python3.6/socket.py", line 743, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "../src/script.py", line 130, in <module>
    main()
  File "../src/script.py", line 93, in main
    mnist = learn.datasets.load_dataset("mnist")
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/__init__.py", line 73, in load_dataset
10.1s
4
    return DATASETS[name]()
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py", line 279, in load_mnist
10.2s
5
    return read_data_sets(train_dir)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py", line 235, in read_data_sets
    SOURCE_URL + TRAIN_IMAGES)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/base.py", line 208, in maybe_download
10.2s
6
    temp_file_name, _ = urlretrieve_with_retry(source_url)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/base.py", line 165, in wrapped_fn
    return fn(*args, **kwargs)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/base.py", line 190, in urlretrieve_with_retry
    return urllib.request.urlretrieve(url, filename)
  File "/opt/conda/lib/python3.6/urllib/request.py", line 248, in urlretrieve
    with contextlib.closing(urlopen(url, data)) as fp:
  File "/opt/conda/lib/python3.6/urllib/request.py", line 223, in urlopen
10.2s
7
    return opener.open(url, data, timeout)
  File "/opt/conda/lib/python3.6/urllib/request.py", line 526, in open
    response = self._open(req, data)
  File "/opt/conda/lib/python3.6/urllib/request.py", line 544, in _open
    '_open', req)
  File "/opt/conda/lib/python3.6/urllib/request.py", line 504, in _call_chain
    result = func(*args)
  File "/opt/conda/lib/python3.6/urllib/request.py", line 1361, in https_open
    context=self._context, check_hostname=self._check_hostname)
  File "/opt/conda/lib/python3.6/urllib/request.py", line 1320, in do_open
    raise URLError(err)
urllib.error.URLError: <urlopen error [Errno -2] Name or service not known>

This message seems very unclear to me. Any idea what could be the cause of this?

Body:
Seems like your script is failing in this line:

mnist = learn.datasets.load_dataset("mnist")

because it can't find the mnist dataset locally (on disk), tries to download it, but it (for some reason) can not.

Try downloading that dataset to MNIST-data directory (Check the source for load_dataset(), which calls load_mnist() with default train_dir='MNIST-data'. Eventually, read_data_sets tries do load train/test images/labels from disk, but if not found in ./MNIST-data, tries to download them from train-images-idx3-ubyte.gz, etc.)


问:
Multiple module.exports in a node js file
How does the Nodejs engine decides when a file has multiple module.exports and it is being required by another file ?
How does the final closure is being calculated ?

答:
It uses the value that module.exports has when the execution of the module has finished:

```<code>module.exports = { foo: 'bar' };
module.exports = { a: 17.8 };    // overwrite "module.exports"
module.exports = 5;              // and again
module.exports = { b: 123 };     // and again
</code>```

Now, when you require the module, you will get { b: 123 }.

module.exports is not a magic keyword, it's just a variable that you can set to tell NodeJS what should be exported.

Body:
It uses the value that module.exports has when the execution of the module has finished:

module.exports = { foo: 'bar' };
module.exports = { a: 17.8 };    // overwrite "module.exports"
module.exports = 5;              // and again
module.exports = { b: 123 };     // and again

Now, when you require the module, you will get { b: 123 }.

module.exports is not a magic keyword, it's just a variable that you can set to tell NodeJS what should be exported.


问:
Create video streaming server in indy
I am trying to create video streaming server using Indy Http server. I am using ranged requests to send large files. One chunk of data is 10 Mb long. If video file which requests client is smaller than 10 Mb then it is all ok and vido is played. But if file size is longer than 10 Mb I return first chunk of data. Then client asks me for another chunk of data from the end of file and then my client says that it is unrecognizable video format. Can someone tell me where is problem in my code.

my server code

```<code>procedure TForm1.Button1Click(Sender: TObject);
begin
  Caption := 'Running';
  FServer := TIdHTTPServer.Create(Self);
  FServer.DefaultPort := 7070;
  FServer.OnCommandGet:=@External_Get;
  FServer.Active := True;
end;

procedure TForm1.External_Get(AContext: TIdContext;
  ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
var
  FS: TFileStream;
  Ranges: TIdEntityRanges;
  Range: TIdEntityRange;
begin
  Ranges := ARequestInfo.Ranges;
  Range := Ranges.Ranges[0];

  FS := TFileStream.Create('/home/user/Desktop/large_file.mp4', fmOpenRead or fmShareDenyWrite);
  AResponseInfo.ContentType := 'video/mp4';
  AResponseInfo.AcceptRanges := 'bytes';
  AResponseInfo.ContentStream := TIdHTTPRangeStream.Create(
    FS,
    Range.StartPos,
    Range.StartPos + 1024*1024*10,
    True
  );
  AResponseInfo.FreeContentStream := True;

  AResponseInfo.ContentRangeStart := TIdHTTPRangeStream(AResponseInfo.ContentStream).RangeStart;
  AResponseInfo.ContentRangeEnd := TIdHTTPRangeStream(AResponseInfo.ContentStream).RangeEnd;
  AResponseInfo.ContentRangeInstanceLength := AResponseInfo.ContentRangeEnd - Range.StartPos + 1;
  AResponseInfo.ContentLength := FS.Size;
  AResponseInfo.ResponseNo := 206;
end;
</code>```

And here is my client code (I use firefox):

```<code><!DOCTYPE html>
<html>
<head>
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
    <meta content="utf-8" http-equiv="encoding">
</head>
<body>

<video width="400" controls>
  <source src="http://localhost:7070/test38.mp4" type="video/mp4">
  Your browser does not support HTML5 video.
</video>

</body>
</html>
</code>```

答:
There are several errors in your server code.

You are not validating that a range is actually being requested, or even respecting an end range if one is present.

You are setting the AResponseInfo.ContentLength property to the full size of the file, even when you are not sending the full file at one time.  That value belongs in the AResponseInfo.ContentRangeInstanceLength property instead when sending a ranged response. You must set ContentLength to the size of the data actually being sent in the response, which in this case is your current range chunk.  It is best not to set the ContentLength at all, you can let the server calculate it for you based on the assigned ContentStream.

You are setting the AResponseInfo.ResponseNo property to 206 unconditionally, even if a range is not requested at all, or if the requested range cannot be satisfied.  TIdHTTPRangeStream performs validations in its constructor and sets its ResponseCode property accordingly.  That is the value you should be assigning to ResponseNo.

Try something more like this instead:

```<code>procedure TForm1.External_Get(AContext: TIdContext;
  ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
var
  FS: TFileStream;
  Range: TIdEntityRange;
  StartPos, EndPos: Int64;
begin
  if not FileExists('/home/user/Desktop/large_file.mp4') then
  begin
    AResponseInfo.ResponseNo := 404;
    Exit;
  end;

  try
    FS := TFileStream.Create('/home/user/Desktop/large_file.mp4', fmOpenRead or fmShareDenyWrite);
  except
    AResponseInfo.ResponseNo := 500;
    Exit;
  end;

  AResponseInfo.ContentType := 'video/mp4';
  AResponseInfo.AcceptRanges := 'bytes';

  if ARequestInfo.Ranges.Count = 1 then
  begin
    Range := ARequestInfo.Ranges.Ranges[0];

    StartPos := Range.StartPos;
    EndPos := Range.EndPos;

    if StartPos >= 0 then
    begin
      // requesting prefix range from BOF
      if EndPos >= 0 then
        EndPos := IndyMin(EndPos, StartPos + (1024*1024*10) - 1)
      else
        EndPos := StartPos + (1024*1024*10) - 1;
    end else
    begin
      // requesting suffix range from EOF
      if EndPos >= 0 then
        EndPos := IndyMin(EndPos, 1024*1024*10)
      else
        EndPos := (1024*1024*10);
    end;

    AResponseInfo.ContentStream := TIdHTTPRangeStream.Create(FS, StartPos, EndPos);
    AResponseInfo.ResponseNo := TIdHTTPRangeStream(AResponseInfo.ContentStream).ResponseCode;

    if AResponseInfo.ResponseNo = 206 then
    begin
      AResponseInfo.ContentRangeStart := TIdHTTPRangeStream(AResponseInfo.ContentStream).RangeStart;
      AResponseInfo.ContentRangeEnd := TIdHTTPRangeStream(AResponseInfo.ContentStream).RangeEnd;
      AResponseInfo.ContentRangeInstanceLength := FS.Size;
    end;
  end else
  begin
    AResponseInfo.ContentStream := FS;
    AResponseInfo.ResponseNo := 200;
  end;
end;
</code>```

Title: Create video streaming server in indy

Body:
I am trying to create video streaming server using Indy Http server. I am using ranged requests to send large files. One chunk of data is 10 Mb long. If video file which requests client is smaller than 10 Mb then it is all ok and vido is played. But if file size is longer than 10 Mb I return first chunk of data. Then client asks me for another chunk of data from the end of file and then my client says that it is unrecognizable video format. Can someone tell me where is problem in my code.

my server code

procedure TForm1.Button1Click(Sender: TObject);
begin
  Caption := 'Running';
  FServer := TIdHTTPServer.Create(Self);
  FServer.DefaultPort := 7070;
  FServer.OnCommandGet:=@External_Get;
  FServer.Active := True;
end;

procedure TForm1.External_Get(AContext: TIdContext;
  ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
var
  FS: TFileStream;
  Ranges: TIdEntityRanges;
  Range: TIdEntityRange;
begin
  Ranges := ARequestInfo.Ranges;
  Range := Ranges.Ranges[0];

  FS := TFileStream.Create('/home/user/Desktop/large_file.mp4', fmOpenRead or fmShareDenyWrite);
  AResponseInfo.ContentType := 'video/mp4';
  AResponseInfo.AcceptRanges := 'bytes';
  AResponseInfo.ContentStream := TIdHTTPRangeStream.Create(
    FS,
    Range.StartPos,
    Range.StartPos + 1024*1024*10,
    True
  );
  AResponseInfo.FreeContentStream := True;

  AResponseInfo.ContentRangeStart := TIdHTTPRangeStream(AResponseInfo.ContentStream).RangeStart;
  AResponseInfo.ContentRangeEnd := TIdHTTPRangeStream(AResponseInfo.ContentStream).RangeEnd;
  AResponseInfo.ContentRangeInstanceLength := AResponseInfo.ContentRangeEnd - Range.StartPos + 1;
  AResponseInfo.ContentLength := FS.Size;
  AResponseInfo.ResponseNo := 206;
end;

And here is my client code (I use firefox):

<!DOCTYPE html>

    <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
    <meta content="utf-8" http-equiv="encoding">

<video width="400" controls>
  <source src="http://localhost:7070/test38.mp4" type="video/mp4">
  Your browser does not support HTML5 video.
</video>

Body:
There are several errors in your server code.

You are not validating that a range is actually being requested, or even respecting an end range if one is present.

You are setting the AResponseInfo.ContentLength property to the full size of the file, even when you are not sending the full file at one time.  That value belongs in the AResponseInfo.ContentRangeInstanceLength property instead when sending a ranged response. You must set ContentLength to the size of the data actually being sent in the response, which in this case is your current range chunk.  It is best not to set the ContentLength at all, you can let the server calculate it for you based on the assigned ContentStream.

You are setting the AResponseInfo.ResponseNo property to 206 unconditionally, even if a range is not requested at all, or if the requested range cannot be satisfied.  TIdHTTPRangeStream performs validations in its constructor and sets its ResponseCode property accordingly.  That is the value you should be assigning to ResponseNo.

Try something more like this instead:

procedure TForm1.External_Get(AContext: TIdContext;
  ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
var
  FS: TFileStream;
  Range: TIdEntityRange;
  StartPos, EndPos: Int64;
begin
  if not FileExists('/home/user/Desktop/large_file.mp4') then
  begin
    AResponseInfo.ResponseNo := 404;
    Exit;
  end;

  try
    FS := TFileStream.Create('/home/user/Desktop/large_file.mp4', fmOpenRead or fmShareDenyWrite);
  except
    AResponseInfo.ResponseNo := 500;
    Exit;
  end;

  AResponseInfo.ContentType := 'video/mp4';
  AResponseInfo.AcceptRanges := 'bytes';

  if ARequestInfo.Ranges.Count = 1 then
  begin
    Range := ARequestInfo.Ranges.Ranges[0];

    StartPos := Range.StartPos;
    EndPos := Range.EndPos;

    if StartPos >= 0 then
    begin
      // requesting prefix range from BOF
      if EndPos >= 0 then
        EndPos := IndyMin(EndPos, StartPos + (1024*1024*10) - 1)
      else
        EndPos := StartPos + (1024*1024*10) - 1;
    end else
    begin
      // requesting suffix range from EOF
      if EndPos >= 0 then
        EndPos := IndyMin(EndPos, 1024*1024*10)
      else
        EndPos := (1024*1024*10);
    end;

    AResponseInfo.ContentStream := TIdHTTPRangeStream.Create(FS, StartPos, EndPos);
    AResponseInfo.ResponseNo := TIdHTTPRangeStream(AResponseInfo.ContentStream).ResponseCode;

    if AResponseInfo.ResponseNo = 206 then
    begin
      AResponseInfo.ContentRangeStart := TIdHTTPRangeStream(AResponseInfo.ContentStream).RangeStart;
      AResponseInfo.ContentRangeEnd := TIdHTTPRangeStream(AResponseInfo.ContentStream).RangeEnd;
      AResponseInfo.ContentRangeInstanceLength := FS.Size;
    end;
  end else
  begin
    AResponseInfo.ContentStream := FS;
    AResponseInfo.ResponseNo := 200;
  end;
end;


问:
Error detection, suggestions and auto-completion seems not to work in Netbeans 8.2, why?
Since pushing my web project (written in jsp created using netbeans 8.2) to git, netbeans seems not detecting errors, giving suggestions or autocompleting my code anymore. But when i copy files from the project and paste them to a new created web project; Error detection, suggestions and auto-completion work for some time, until I restart the IDE, it stops to working again. What's the problem and how do I solve it?</p>

答: I installed Netbeans 8.0.2 and used my project it. My problem is now fixed.</p>


问:
Pushing single file change in the azure app service deployment
I have an asp.net core web application and I deploy the application from my Visual Studio 2015 by publishing. But every time I change something I need to publish the whole application again.

Is there any way to deploy the application partially? For example, if there is a very small change in a file, I can only send that file in the app service directly without publishing the entire application again?

答:
Yes. You have a few options.

If it's a change to a text file, you can edit the file directly on the server by navigating to https://[yourAppName].scm.azurewebsites.net. Log in with your credentials that you use to access the portal.azure.com site. Navigate to Debug Console -> CMD. This will give you a sort of online file explorer. You can choose any file to edit right there in the browser. This is handy for those small edits. But beware making edits on the server and forgetting to commit them to your source control management solution.

For binary files, you can upload them directly via FTP. You can find your FTP creds by downloading your web app's publish profile on the Overview blade for your web app. FTP into the server and replace any file that you like.

ContentLicense: CC BY-SA 4.0


问:
NYT article search API not returning results for certain queries
I have a set of queries and I am trying to get web_urls using the NYT article search API. But I am seeing that it works for q2 below but not for q1.

q1: Seattle+Jacob Vigdor+the University of Washington

q2: Seattle+Jacob Vigdor+University of Washington

If you paste the url below with your API key in the web browser, you get an empty result.

Search request for q1

api.nytimes.com/svc/search/v2/articlesearch.json?q=Seattle+Jacob%20Vigdor+the%20University%20of%20Washington&begin_date=20170626&api-key=XXXX

Empty results for q1

{"response":{"meta":{"hits":0,"time":27,"offset":0},"docs":[]},"status":"OK","copyright":"Copyright (c) 2013 The New York Times Company.  All Rights Reserved."}

Instead if you paste the following in your web browser (without the article 'the' in the query) you get non-empty results

Search request for q2

api.nytimes.com/svc/search/v2/articlesearch.json?q=Seattle+Jacob%20Vigdor+University%20of%20Washington&begin_date=20170626&api-key=XXXX

Non-empty results for q2

{"response":{"meta":{"hits":1,"time":22,"offset":0},"docs":[{"web_url":"https://www.nytimes.com/aponline/2017/06/26/us/ap-us-seattle-minimum-wage.html","snippet":"Seattle's $15-an-hour minimum wage law has cost the city jobs, according to a study released Monday that contradicted another new study published last week....","lead_paragraph":"Seattle's $15-an-hour minimum wage law has cost the city jobs, according to a study released Monday that contradicted another new study published last week.","abstract":null,"print_page":null,"blog":[],"source":"AP","multimedia":[],"headline":{"main":"New Study of Seattle's $15 Minimum Wage Says It Costs Jobs","print_headline":"New Study of Seattle's $15 Minimum Wage Says It Costs Jobs"},"keywords":[],"pub_date":"2017-06-26T15:16:28+0000","document_type":"article","news_desk":"None","section_name":"U.S.","subsection_name":null,"byline":{"person":[],"original":"By THE ASSOCIATED PRESS","organization":"THE ASSOCIATED PRESS"},"type_of_material":"News","_id":"5951255195d0e02550996fb3","word_count":643,"slideshow_credits":null}]},"status":"OK","copyright":"Copyright (c) 2013 The New York Times Company.  All Rights Reserved."}

Interestingly, both queries work fine on the api test page
http://developer.nytimes.com/article_search_v2.json#/Console/

Also, if you look at the article below returned by q2, you see that the query term in q1, 'the University of Washington' does occur in it and it should have returned this article.
https://www.nytimes.com//aponline//2017//06//26//us//ap-us-seattle-minimum-wage.html

I am confused about this behaviour of the API. Any ideas what's going on? Am I missing something?

答:
I think you need to change encoding of spaces (%20) to + (%2B):

In your example,

```<code>q=Seattle+Jacob%20Vigdor+the%20University%20of%20Washington
</code>```

When I submit from the page on the site, it uses %2B:

```<code>q=Seattle%2BJacob+Vigdor%2Bthe+University+of+Washington
</code>```

How are you URL encoding? One way to fix it would be to replace your spaces with + before URL encoding.

Also, you may need to replace %20 with +. There are various schemes for URL encoding, so the best way would depend on how you are doing it.

Body:
I think you need to change encoding of spaces (%20) to + (%2B):

In your example,

q=Seattle+Jacob%20Vigdor+the%20University%20of%20Washington

When I submit from the page on the site, it uses %2B:

q=Seattle%2BJacob+Vigdor%2Bthe+University+of+Washington

How are you URL encoding? One way to fix it would be to replace your spaces with + before URL encoding.

Also, you may need to replace %20 with +. There are various schemes for URL encoding, so the best way would depend on how you are doing it.


问:
CSS: margin/padding on IE cause floats to be placed incorrectly
I'm having trouble getting IE7 to float my elements correctly (FF and Chrome work as expected). I'd like to have the "Delete" buttons (here a span with class "sbutton") to be floated all the way to the right. On IE the sbutton no the first line floats all the way to right as expected, but the subsequent lines float just to the left of the sbutton above them:

```<code>Something some other text ----------------------------------[Delete]
Something Else some other text ---------------------[Delete]--------
</code>```

This is related to paddings and margins on the sbutton:

```<code>.sbutton {
    background-color: #2E3239; color: white; border: 1px solid gray;
    font-family: "Trebuchet MS"; font-size: 90%; padding: 1px 3px; margin: 2px;
    -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px;
}
</code>```

If I remove the padding and margin they all float as expected.

Here's the HMTL:

```<code><li>
     <span class="left"><b>Something</b> (#1102) some other text</span>
     <span class="right"><a href="#" class="sbutton">Delete</a></span>
</li>
<li>
     <span class="left"><b>Something Else</b> (#1103) some other text</span>
     <span class="right"><a href="#" class="sbutton">Delete</a></span>
</li>
</code>```

I get similar behavior on FF and Chrome if I remove the outer span (the one with class "right").

Why is this happening, and what's the right way to do this?

答: @parand - it's not necessary because IE has a different box model than FF or Webkit (which is the engine that powers chrome & safari, among others). By forcing this clear, it's a workaround from the differences.</p>

Body:
I'm having trouble getting IE7 to float my elements correctly (FF and Chrome work as expected). I'd like to have the "Delete" buttons (here a span with class "sbutton") to be floated all the way to the right. On IE the sbutton no the first line floats all the way to right as expected, but the subsequent lines float just to the left of the sbutton above them:

Something some other text ----------------------------------[Delete]
Something Else some other text ---------------------[Delete]--------

This is related to paddings and margins on the sbutton:

.sbutton {
    background-color: #2E3239; color: white; border: 1px solid gray;
    font-family: "Trebuchet MS"; font-size: 90%; padding: 1px 3px; margin: 2px;
    -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px;
}

If I remove the padding and margin they all float as expected.

Here's the HMTL:

     Something (#1102) some other text
     Delete

     Something Else (#1103) some other text
     Delete

I get similar behavior on FF and Chrome if I remove the outer span (the one with class "right").

Why is this happening, and what's the right way to do this?


问:
How to get laravel command arguments outside command, e.g. in service provider?
I can get arguments in command with this code:

```<code>$this->argument();
</code>```

But how to get arguments outside ?

If I look at source of argument() function I see :

```<code>public function argument($key = null)
{
    if (is_null($key)) {
        return $this->input->getArguments();
    }

    return $this->input->getArgument($key);
}
</code>```

I want to detect when command "php artisan migrate:refresh --seed" is running because I want some part of code in models run at localhost enviroment but not in localhost enviroment during seeding...

答:
I has the same problem building a Laravel SAAS app on AWS, in base to this project I modify my ServiceProvider for this:

```<code><?php

namespace App\Providers;

use Illuminate\Console\Events\ArtisanStarting;
use Illuminate\Support\ServiceProvider;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\EventDispatcher\EventDispatcher;

class MultitenantServiceProvider extends ServiceProvider{

protected $consoleDispatcher = false;
protected $commands_with_tenant = [
    'migrate', 'migrate:refresh', 'migrate:install', 'migrate:reset', 'migrate:rollback',
    'migrate:status', 'passport:client', 'passport:install', 'passport:keys'
];

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot(){
    if( $this->app->runningInConsole() ){
        $this->registerTenantOption();
        $this->verifyTenantOption();
    }
    // Multitenant re-configure in case of HTTP request
}

/**
 * Register any application services.
 *
 * @return void
 */
public function register(){
    $this->app->singleton('multitenant', function ($app){
        // Register your Multitenant
    });
}

protected function registerTenantOption(){
    $this->app['events']->listen(ArtisanStarting::class, function($event){
        $definition = $event->artisan->getDefinition();
        $definition->addOption(
            new InputOption('--tenant', null, InputOption::VALUE_OPTIONAL, 'The tenant subdomain the command should be run for. Use * or all for every tenant.')
        );
        $event->artisan->setDefinition($definition);
        $event->artisan->setDispatcher($this->getConsoleDispatcher());
    });
}

protected function verifyTenantOption(){
    $this->getConsoleDispatcher()->addListener(ConsoleEvents::COMMAND, function(ConsoleCommandEvent $event){
        if( in_array($event->getCommand()->getName() , $this->commands_with_tenant) ){
            $tenant = $event->getInput()->getParameterOption('--tenant', null);
            if (!is_null($tenant)){
                if ($tenant == 'all'){
                    // Do something with 'all'
                }
                else{
                    // Do something with $tenant
                }
            }
            else{
                $event->getOutput('<error>This command need that specified a tenant client</error>');
                $event->disableCommand();
            }
        }
    });
}

protected function getConsoleDispatcher(){
    if (!$this->consoleDispatcher){
        $this->consoleDispatcher = app(EventDispatcher::class);
    }
    return $this->consoleDispatcher;
}
</code>```

In this class, there is an array with the commands that are needed to verify and use a multitenant config.

Body:
I can get arguments in command with this code:

$this->argument();

But how to get arguments outside ?

If I look at source of argument() function I see :

public function argument($key = null)
{
    if (is_null($key)) {
        return $this->input->getArguments();
    }

    return $this->input->getArgument($key);
}

I want to detect when command "php artisan migrate:refresh --seed" is running because I want some part of code in models run at localhost enviroment but not in localhost enviroment during seeding...

Body:
I has the same problem building a Laravel SAAS app on AWS, in base to this project I modify my ServiceProvider for this:

<?php

namespace App\Providers;

use Illuminate\Console\Events\ArtisanStarting;
use Illuminate\Support\ServiceProvider;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\EventDispatcher\EventDispatcher;

class MultitenantServiceProvider extends ServiceProvider{

protected $consoleDispatcher = false;
protected $commands_with_tenant = [
    'migrate', 'migrate:refresh', 'migrate:install', 'migrate:reset', 'migrate:rollback',
    'migrate:status', 'passport:client', 'passport:install', 'passport:keys'
];

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot(){
    if( $this->app->runningInConsole() ){
        $this->registerTenantOption();
        $this->verifyTenantOption();
    }
    // Multitenant re-configure in case of HTTP request
}

/**
 * Register any application services.
 *
 * @return void
 */
public function register(){
    $this->app->singleton('multitenant', function ($app){
        // Register your Multitenant
    });
}

protected function registerTenantOption(){
    $this->app['events']->listen(ArtisanStarting::class, function($event){
        $definition = $event->artisan->getDefinition();
        $definition->addOption(
            new InputOption('--tenant', null, InputOption::VALUE_OPTIONAL, 'The tenant subdomain the command should be run for. Use * or all for every tenant.')
        );
        $event->artisan->setDefinition($definition);
        $event->artisan->setDispatcher($this->getConsoleDispatcher());
    });
}

protected function verifyTenantOption(){
    $this->getConsoleDispatcher()->addListener(ConsoleEvents::COMMAND, function(ConsoleCommandEvent $event){
        if( in_array($event->getCommand()->getName() , $this->commands_with_tenant) ){
            $tenant = $event->getInput()->getParameterOption('--tenant', null);
            if (!is_null($tenant)){
                if ($tenant == 'all'){
                    // Do something with 'all'
                }
                else{
                    // Do something with $tenant
                }
            }
            else{
                $event->getOutput('<error>This command need that specified a tenant client</error>');
                $event->disableCommand();
            }
        }
    });
}

protected function getConsoleDispatcher(){
    if (!$this->consoleDispatcher){
        $this->consoleDispatcher = app(EventDispatcher::class);
    }
    return $this->consoleDispatcher;
}

In this class, there is an array with the commands that are needed to verify and use a multitenant config.


问:
Is it possible to use different version of node for different node script at the same time
I am currently using nvm. Is it possible to use specific node version for specific script? For example...

With node 6

```<code>forever start -a -l $MYPATH/forever.log -e $MYPATH/err.log -c "node --max_old_space_size=20" $MYPATH/script_with_node_version_6.js
</code>```

With node 8

```<code>forever start -a -l $MYPATH/forever.log -e $MYPATH/err.log -c "node --max_old_space_size=20" $MYPATH/script_with_node_version_8.js
</code>```

答:
For Windows, you should be able to do this by explicitly pointing to your executible. Since you mention you're using nvm (assuming nvm-windows), you can check out where your versioned node.js installations live.

```<code>nvm root
</code>```

Current Root: C:\Users\you\AppData\Roaming\nvm

Or - wherever this command returns. Then simply point to them in your specified scripts instead of your $PATH node

```<code>forever start -c "C:\Users\you\AppData\Roaming\nvm\v6.11.0\node.exe v6.js"

forever start -c "C:\Users\you\AppData\Roaming\nvm\v8.1.2\node.exe v8.js"
</code>```

If you're on a linux box or leveraging bash on Windows you may be able to capitalize on some of the nice features nvm offers. Notably, nvm exec

Or, you can run any arbitrary command in a subshell with the desired
  version of node:

This may look as such...

```<code>forever start -c "nvm exec 8.1.2 node v8.js"
</code>```

Check out their examples, you may be able to streamline your command even more as your top comment suggests...

Body:
I am currently using nvm. Is it possible to use specific node version for specific script? For example...

With node 6

forever start -a -l $MYPATH/forever.log -e $MYPATH/err.log -c "node --max_old_space_size=20" $MYPATH/script_with_node_version_6.js

With node 8

forever start -a -l $MYPATH/forever.log -e $MYPATH/err.log -c "node --max_old_space_size=20" $MYPATH/script_with_node_version_8.js

Body:
For Windows, you should be able to do this by explicitly pointing to your executible. Since you mention you're using nvm (assuming nvm-windows), you can check out where your versioned node.js installations live.

nvm root

Current Root: C:\Users\you\AppData\Roaming\nvm

Or - wherever this command returns. Then simply point to them in your specified scripts instead of your $PATH node

forever start -c "C:\Users\you\AppData\Roaming\nvm\v6.11.0\node.exe v6.js"

forever start -c "C:\Users\you\AppData\Roaming\nvm\v8.1.2\node.exe v8.js"

If you're on a linux box or leveraging bash on Windows you may be able to capitalize on some of the nice features nvm offers. Notably, nvm exec

Or, you can run any arbitrary command in a subshell with the desired
  version of node:

This may look as such...

forever start -c "nvm exec 8.1.2 node v8.js"

Check out their examples, you may be able to streamline your command even more as your top comment suggests...


问:
OnItemClickListener vs OnclickListener in listview android
This is gonna be long due to code. So I have a question about OnItemclickListener vs OnclickListener,and here I have two codes one for each and both worked, so is there any preference to use one of the two or can I use anyone???
Here is code with OnItemClickListener

```<code>public class MainActivity extends AppCompatActivity {
    private ArrayList<String> numbers=new ArrayList<String>();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); //a listview with id "list"

        ListView numberLV = (ListView) findViewById(R.id.list);
        numbers.add("one");
        numbers.add("two");
        numbers.add("three");
        numbers.add("four");
        // and so on
        listAdapter itemadapter=new listAdapter(this,numbers);
        numberLV.setAdapter(itemadapter);
        numberLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String num=numbers.get(position);
                String display="You have clicked "+num;
                Toast.makeText(MainActivity.this,display,Toast.LENGTH_SHORT).show();
            }
        });
    }
}
class listAdapter extends ArrayAdapter<String> {
    public listAdapter(@NonNull Context context, ArrayList<String> numbers){
        super(context,0,numbers);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View listItemView = convertView;
        if(listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_num, parent, false);
        }
        TextView tvnum=(TextView) listItemView.findViewById(R.id.numbersTV);
        String num=getItem(position);
        tvnum.setText(num);
        return listItemView;
    }
}
</code>```

and here's one with OnClickListener

```<code>public class MainActivity extends AppCompatActivity {
    private ArrayList<String> numbers=new ArrayList<String>();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); //a listview with id "list"

        ListView numberLV = (ListView) findViewById(R.id.list);
        numbers.add("one");
        numbers.add("two");
        numbers.add("three");
        numbers.add("four");
        // and so on
        listAdapter itemadapter=new listAdapter(this,numbers);
        numberLV.setAdapter(itemadapter);
    }
}
class listAdapter extends ArrayAdapter<String> {
    public listAdapter(@NonNull Context context, ArrayList<String> numbers){
        super(context,0,numbers);
    }

    @NonNull
    @Override
    public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View listItemView = convertView;
        if(listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_num, parent, false);
        }
        TextView tvnum=(TextView) listItemView.findViewById(R.id.numbersTV);
        String num=getItem(position);
        tvnum.setText(num);
        listItemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String display="You have clicked "+getItem(position);
                Toast.makeText(getContext(),display,Toast.LENGTH_SHORT).show();
            }
        });
        return listItemView;
    }
}
</code>```

Both codes worked normally for me, but the confusion was whether the second one was right or wrong??

答:
Adapter

The setOnItemClickListener is the preferred way of attaching the click listener on the items of the adapter as mentioned by the first comment above.

View

In your second scenario, where you have  setOnClickListener attached on individual item inside the getView method which is also valid because the ItemView in this case is an indirect subclass on View on which setOnClickListener originally declared.

Body:
This is gonna be long due to code. So I have a question about OnItemclickListener vs OnclickListener,and here I have two codes one for each and both worked, so is there any preference to use one of the two or can I use anyone???
Here is code with OnItemClickListener

public class MainActivity extends AppCompatActivity {
    private ArrayList<String> numbers=new ArrayList<String>();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); //a listview with id "list"

        ListView numberLV = (ListView) findViewById(R.id.list);
        numbers.add("one");
        numbers.add("two");
        numbers.add("three");
        numbers.add("four");
        // and so on
        listAdapter itemadapter=new listAdapter(this,numbers);
        numberLV.setAdapter(itemadapter);
        numberLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String num=numbers.get(position);
                String display="You have clicked "+num;
                Toast.makeText(MainActivity.this,display,Toast.LENGTH_SHORT).show();
            }
        });
    }
}
class listAdapter extends ArrayAdapter<String> {
    public listAdapter(@NonNull Context context, ArrayList<String> numbers){
        super(context,0,numbers);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View listItemView = convertView;
        if(listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_num, parent, false);
        }
        TextView tvnum=(TextView) listItemView.findViewById(R.id.numbersTV);
        String num=getItem(position);
        tvnum.setText(num);
        return listItemView;
    }
}

and here's one with OnClickListener

public class MainActivity extends AppCompatActivity {
    private ArrayList<String> numbers=new ArrayList<String>();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); //a listview with id "list"

        ListView numberLV = (ListView) findViewById(R.id.list);
        numbers.add("one");
        numbers.add("two");
        numbers.add("three");
        numbers.add("four");
        // and so on
        listAdapter itemadapter=new listAdapter(this,numbers);
        numberLV.setAdapter(itemadapter);
    }
}
class listAdapter extends ArrayAdapter<String> {
    public listAdapter(@NonNull Context context, ArrayList<String> numbers){
        super(context,0,numbers);
    }

    @NonNull
    @Override
    public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View listItemView = convertView;
        if(listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_num, parent, false);
        }
        TextView tvnum=(TextView) listItemView.findViewById(R.id.numbersTV);
        String num=getItem(position);
        tvnum.setText(num);
        listItemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String display="You have clicked "+getItem(position);
                Toast.makeText(getContext(),display,Toast.LENGTH_SHORT).show();
            }
        });
        return listItemView;
    }
}

Both codes worked normally for me, but the confusion was whether the second one was right or wrong??


问:
Atom - Force Tab Width 2
I just switched from Sublime Text to Atom in order to turn completely open source.

I have trouble with something very very simple: I want Atom to use always (!) and under any circumstances tab width 2 and replace tab with spaces. This setting is so simple in gedit or Sublime Text, but no matter what I am trying: When I start a new file, tab size is 2 (good!). When I use an existing file, tab size is sometimes 4. I find that a bit annoying.

My current setting in Editor are seen in the screenshot:

答:
This is what worked for me.

Disable all non-default packages

Open ~/.atom/config.cson, and append this (same level than the "*" element)

:

```<code>".python.source":
  editor:
    autoIndent: true
    tabLength: 2
</code>```

Re-enable all packages.

I got this help from someone else. Not my own discovery. However, for confidentiality, I cannot cite the source.

Title: Atom - Force Tab Width 2

Body:
This is what worked for me.

Disable all non-default packages

Open ~/.atom/config.cson, and append this (same level than the "*" element)

:

".python.source":
  editor:
    autoIndent: true
    tabLength: 2

Re-enable all packages.

I got this help from someone else. Not my own discovery. However, for confidentiality, I cannot cite the source.


问:
acs package in R: Cannot download dataset, error message is inscrutable
I am trying to use the acs package in R to download Census data for a basic map, but I am unable to download the data and I'm receiving a confusing error message.

My code is as follows:

```<code>#Including all packages here in case this is somehow the issue

install.packages(c("choroplethr", "choroplethrMaps", "tidycensus", "tigris", "leaflet", "acs", "sf"))

library(choroplethr)
library(choroplethrMaps)
library(tidycensus)
library(tigris)
library(leaflet)
library(acs)
library(sf)
library(tidyverse)

api.key.install("my_api_key")

SD_geo <- geo.make(state="CA", county = 73, tract = "*", block.group = "*")

median_income <- acs.fetch(endyear = 2015, span = 5, geography = SD_geo, table.number = "B19013", col.names="pretty")
</code>```

Everything appears to work until the final command, when I receive the following error message:

```<code>trying URL 'http://web.mit.edu/eglenn/www/acs/acs-variables/acs_5yr_2015_var.xml.gz'
Content type 'application/xml' length 735879 bytes (718 KB)
downloaded 718 KB

Error in if (url.test["statusMessage"] != "OK") { :
  missing value where TRUE/FALSE needed
In addition: Warning message:
In (function (endyear, span = 5, dataset = "acs", keyword, table.name,  :
  XML variable lookup tables for this request
  seem to be missing from ' https://api.census.gov/data/2015/acs5/variables.xml ';
  temporarily downloading and using archived copies instead;
  since this is *much* slower, recommend running
  acs.tables.install()
</code>```

This is puzzling to me because 1) it appears like something is in fact being downloaded at first? and 2)   'Error in if (url.test["statusMessage"] != "OK") { :
      missing value where TRUE/FALSE needed' makes no sense to me. It doesn't align with any of the arguments in the function.

I have tried:

Downloading the tables using acs.tables.install() as recommended in the second half of the error message. Doesn't help.

Changing the endyear and span to be sure that I'm falling within the years of data supported by the API. I seem to be, according to the API documentation. Have also used the package default arguments with no luck.

Using 'variable =' and the code for the variable as found in the official API documentation. This returns only the two lines with the mysterious "Error in if..." message.

Removing colnames = "pretty"

I'm going to just download the datafile as a CSV and read it into R for now, but I'd like to be able to perform this function from the script for future maps. Any information on what's going on here would be appreciated. I am running R version 3.3.2. Also, I'm new to using this package and the API. But I'm following the documentation and can't find evidence that I'm doing anything wrong.

Tutorial I am working off of:
http://zevross.com/blog/2015/10/14/manipulating-and-mapping-us-census-data-in-r-using-the-acs-tigris-and-leaflet-packages-3/#get-the-tabular-data-acs

And documentation of the acs package: http://eglenn.scripts.mit.edu/citystate/wp-content/uploads/2013/02/wpid-working_with_acs_R2.pdf

答:
Your code runs for me.  My guess would be that the Census API was temporarily down.

As you loaded tidycensus and you'd like to do some mapping, you might also consider the following code:

```<code>library(tidycensus)
census_api_key("your key here") # use `install = TRUE` to install the key
options(tigris_use_cache = TRUE) # optional - to cache the Census shapefile

median_income <- get_acs(geography = "block group",
                         variables = "B19013_001",
                         state = "CA", county = "San Diego",
                         geometry = TRUE)
</code>```

This will get you the data you need, along with feature geometry for mapping, as a tidy data frame.

Body:
I am trying to use the acs package in R to download Census data for a basic map, but I am unable to download the data and I'm receiving a confusing error message.

My code is as follows:

#Including all packages here in case this is somehow the issue

install.packages(c("choroplethr", "choroplethrMaps", "tidycensus", "tigris", "leaflet", "acs", "sf"))

library(choroplethr)
library(choroplethrMaps)
library(tidycensus)
library(tigris)
library(leaflet)
library(acs)
library(sf)
library(tidyverse)

api.key.install("my_api_key")

SD_geo <- geo.make(state="CA", county = 73, tract = "*", block.group = "*")

median_income <- acs.fetch(endyear = 2015, span = 5, geography = SD_geo, table.number = "B19013", col.names="pretty")

Everything appears to work until the final command, when I receive the following error message:

trying URL 'http://web.mit.edu/eglenn/www/acs/acs-variables/acs_5yr_2015_var.xml.gz'
Content type 'application/xml' length 735879 bytes (718 KB)
downloaded 718 KB

Error in if (url.test["statusMessage"] != "OK") { :
  missing value where TRUE/FALSE needed
In addition: Warning message:
In (function (endyear, span = 5, dataset = "acs", keyword, table.name,  :
  XML variable lookup tables for this request
  seem to be missing from ' https://api.census.gov/data/2015/acs5/variables.xml ';
  temporarily downloading and using archived copies instead;
  since this is *much* slower, recommend running
  acs.tables.install()

This is puzzling to me because 1) it appears like something is in fact being downloaded at first? and 2)   'Error in if (url.test["statusMessage"] != "OK") { :
      missing value where TRUE/FALSE needed' makes no sense to me. It doesn't align with any of the arguments in the function.

I have tried:

Downloading the tables using acs.tables.install() as recommended in the second half of the error message. Doesn't help.

Changing the endyear and span to be sure that I'm falling within the years of data supported by the API. I seem to be, according to the API documentation. Have also used the package default arguments with no luck.

Using 'variable =' and the code for the variable as found in the official API documentation. This returns only the two lines with the mysterious "Error in if..." message.

Removing colnames = "pretty"

I'm going to just download the datafile as a CSV and read it into R for now, but I'd like to be able to perform this function from the script for future maps. Any information on what's going on here would be appreciated. I am running R version 3.3.2. Also, I'm new to using this package and the API. But I'm following the documentation and can't find evidence that I'm doing anything wrong.

Tutorial I am working off of:
http://zevross.com/blog/2015/10/14/manipulating-and-mapping-us-census-data-in-r-using-the-acs-tigris-and-leaflet-packages-3/#get-the-tabular-data-acs

And documentation of the acs package: http://eglenn.scripts.mit.edu/citystate/wp-content/uploads/2013/02/wpid-working_with_acs_R2.pdf

Body:
Your code runs for me.  My guess would be that the Census API was temporarily down.

As you loaded tidycensus and you'd like to do some mapping, you might also consider the following code:

library(tidycensus)
census_api_key("your key here") # use `install = TRUE` to install the key
options(tigris_use_cache = TRUE) # optional - to cache the Census shapefile

median_income <- get_acs(geography = "block group",
                         variables = "B19013_001",
                         state = "CA", county = "San Diego",
                         geometry = TRUE)

This will get you the data you need, along with feature geometry for mapping, as a tidy data frame.


问:
SQL pivot 1:M rows into string columns
I have a 1:M recordset that I need to pivot into columns where the results are concatenated.

Create sample data:

```<code>CREATE TABLE #temptable
(
    ID int,
    Division int,
    Material int
);

 insert into #temptable
 Values
 (999, 1, 1)
 ,(999, 1, 2)
 ,(999, 1, 3)
 ,(999, 2, 1)
 ,(999, 2, 6)
 ,(999, 3, 2)
</code>```

Sample data:

```<code>ID     Division     Material
----  ----------   ----------
999       1            1
999       1            2
999       1            3
999       2            1
999       2            6
999       3            2
</code>```

I need the results to look like this, where the materials for each division are concatenated:

```<code> ID   Division-1   Division-2   Division-3
----  ----------   ----------   ----------
999     1,2,3          1,6          2
</code>```

答:
Try this :

```<code>SELECT ID,
       [1] AS 'Division-1',
       [2] AS 'Division-2',
       [3] AS 'Division-3'
FROM
(
    SELECT DISTINCT
           a.ID,
           a.Division,
           LEFT(r.ResourceName, LEN(r.ResourceName) - 1) ResourceName
    FROM #temptable a
         CROSS APPLY
    (
        SELECT CAST(Material AS VARCHAR(10))+','
        FROM #temptable t
        WHERE a.[ID] = t.[ID]
              AND a.Division = t.Division
        FOR XML PATH('')
    ) r(ResourceName)
) src PIVOT(MAX(ResourceName) FOR Division IN([1],
                                              [2],
                                              [3])) piv;
</code>```

brief explanation
We need to create pivot over comma separated structure.

Below query converts column value into comma separated rows.

```<code>SELECT a.ID,
       a.Division,
       LEFT(r.ResourceName, LEN(r.ResourceName) - 1) ResourceName
FROM #temptable a
     CROSS APPLY
(
    SELECT CAST(Material AS VARCHAR(10))+','
    FROM #temptable t
    WHERE a.[ID] = t.[ID]
          AND a.Division = t.Division
    FOR XML PATH('')
) r(ResourceName);
</code>```

After that we create pivot over it.

Title: SQL pivot 1:M rows into string columns

Body:
I have a 1:M recordset that I need to pivot into columns where the results are concatenated.

Create sample data:

CREATE TABLE #temptable
(
    ID int,
    Division int,
    Material int
);

 insert into #temptable
 Values
 (999, 1, 1)
 ,(999, 1, 2)
 ,(999, 1, 3)
 ,(999, 2, 1)
 ,(999, 2, 6)
 ,(999, 3, 2)

Sample data:

ID     Division     Material
----  ----------   ----------
999       1            1
999       1            2
999       1            3
999       2            1
999       2            6
999       3            2

I need the results to look like this, where the materials for each division are concatenated:

 ID   Division-1   Division-2   Division-3
----  ----------   ----------   ----------
999     1,2,3          1,6          2

Body:
Try this :

SELECT ID,
       [1] AS 'Division-1',
       [2] AS 'Division-2',
       [3] AS 'Division-3'
FROM
(
    SELECT DISTINCT
           a.ID,
           a.Division,
           LEFT(r.ResourceName, LEN(r.ResourceName) - 1) ResourceName
    FROM #temptable a
         CROSS APPLY
    (
        SELECT CAST(Material AS VARCHAR(10))+','
        FROM #temptable t
        WHERE a.[ID] = t.[ID]
              AND a.Division = t.Division
        FOR XML PATH('')
    ) r(ResourceName)
) src PIVOT(MAX(ResourceName) FOR Division IN([1],
                                              [2],
                                              [3])) piv;

brief explanation
We need to create pivot over comma separated structure.

Below query converts column value into comma separated rows.

SELECT a.ID,
       a.Division,
       LEFT(r.ResourceName, LEN(r.ResourceName) - 1) ResourceName
FROM #temptable a
     CROSS APPLY
(
    SELECT CAST(Material AS VARCHAR(10))+','
    FROM #temptable t
    WHERE a.[ID] = t.[ID]
          AND a.Division = t.Division
    FOR XML PATH('')
) r(ResourceName);

After that we create pivot over it.


问:
How to make a Textbox editable on click and add a button to the side Angular
I am trying to add a feature just like stack overflow comments where clicking on the edit link the div transforms to a text box and we get a submit button .

But the problem is i have multiple comments which i am populating via ngFor how do i remove the property readonly from the selected div in which the edit has been clicked .

This is what i have tried.

```<code>    <div class="tab-content">
        <div id="email" class="tab-pane active">
            <div *ngFor="let i of comments; let index = index" [@flyInOut]>
                <div class="well">
                    <input type=”text” value="{{i.comment}}" [readonly]="false" /><span>
                        Edited <time>{{today | amDifference: i.createdAt :'minutes'
                            : false}}</time> before
                    </span><a><i
                        class="align remove glyphicon glyphicon-remove-sign glyphicon-white"
                        (click)="edit(index)"></i></a>
                </div>
            </div>
        </div>
    </div>
</code>```

I also i would love to have something like checking time i have already done the backend part of same how to only enable the edit button for the comment where the amDifference is less than 5 mins and then we show a delete option.

答:
You can use ngIf-Else to provide a second template to show like such:</p>

```<code><div class="tab-content">
    <div id="email" class="tab-pane active">
        <div *ngFor="let i of comments; let index = index" [@flyInOut]>
            <div *ngIf="i.editMode; else editBlock" class="well">
                <!-- Show stuff here -->
                <a>
                    <i class="align remove glyphicon glyphicon-remove-sign glyphicon-white"
                       (click)="i.editMode=true">
                    </i>
                </a>
            </div>
            <ng-template #editblock>
                <div class="well">
                    <!-- Edit stuff here -->
                    <input type="button" (click)="i.editMode=false" value="Done"/>
                </div>
            </ng-template>
        </div>
    </div>
</div>
</code>```

Body:
I am trying to add a feature just like stack overflow comments where clicking on the edit link the div transforms to a text box and we get a submit button .

But the problem is i have multiple comments which i am populating via ngFor how do i remove the property readonly from the selected div in which the edit has been clicked .

This is what i have tried.

                    <input type=”text” value="{{i.comment}}" [readonly]="false" />
                        Edited <time>{{today | amDifference: i.createdAt :'minutes'
                            : false}}</time> before

I also i would love to have something like checking time i have already done the backend part of same how to only enable the edit button for the comment where the amDifference is less than 5 mins and then we show a delete option.

Body:
You can use ngIf-Else to provide a second template to show like such:

<div class="tab-content">
    <div id="email" class="tab-pane active">
        <div *ngFor="let i of comments; let index = index" [@flyInOut]>
            <div *ngIf="i.editMode; else editBlock" class="well">
                <!-- Show stuff here -->
                <a>
                    <i class="align remove glyphicon glyphicon-remove-sign glyphicon-white"
                       (click)="i.editMode=true">
                    </i>
                </a>
            </div>
            <ng-template #editblock>
                <div class="well">
                    <!-- Edit stuff here -->
                    <input type="button" (click)="i.editMode=false" value="Done"/>
                </div>
            </ng-template>
        </div>
    </div>
</div>


问:
MySQL > Compare and Report Time differences from certain rows only
I'm working on a new report and I'm having trouble figuring out the logic.  I have a table similar to the following:

M=Message (There is only one per thread)
R=Response (There can be any number of responses)
N=Note (Not needed for the report and can be excluded via additional WHERE statement).
For each thread_id get the time for the type=M column and then the get FIRST type=R time, compare those two times and report such as

.thread_col {
  width: 80px;
}

.report_col {
  width: 200px;
}

th {
  text-align: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <th class='thread_col'>Thread</th>
    <th class='report_col'>Time to First Response</th>
  </tr>
  <tr>
    <td>2</td>
    <td>124 Minutes</td>
  </tr>
  <tr>
    <td>3</td>
    <td>18 Minutes</td>
  </tr>
  <tr>
    <td>4</td>
    <td>22 Minutes</td>
  </tr>
</table></code>```

I've tried some things but my MySQL is a little rusty. I assume we'll need sub-queries in there?

答:
This sound like a self-join to me:

```<code>SELECT t.*, MIN(t1.created)
FROM t
LEFT JOIN t as t1 ON t1.thread_id = t.thread_id AND t1.type = 'R'
WHERE t.type = 'M'
GROUP BY t.thread_id
</code>```

You select all types M from the table, then join the lowest response time to it.
Must be a LEFT JOIN, because not all messages actually have a response. And you need the group, because they could have more than one response.

You then have the two times and can calculate the difference in minutes in PHP for the output.

Body:
I'm working on a new report and I'm having trouble figuring out the logic.  I have a table similar to the following:

M=Message (There is only one per thread)
R=Response (There can be any number of responses)
N=Note (Not needed for the report and can be excluded via additional WHERE statement).
For each thread_id get the time for the type=M column and then the get FIRST type=R time, compare those two times and report such as

.thread_col {
  width: 80px;
}

.report_col {
  width: 200px;
}

th {
  text-align: left;
}

    Thread
    Time to First Response

    2
    124 Minutes

    3
    18 Minutes

    4
    22 Minutes

I've tried some things but my MySQL is a little rusty. I assume we'll need sub-queries in there?

Body:
This sound like a self-join to me:

SELECT t.*, MIN(t1.created)
FROM t
LEFT JOIN t as t1 ON t1.thread_id = t.thread_id AND t1.type = 'R'
WHERE t.type = 'M'
GROUP BY t.thread_id

You select all types M from the table, then join the lowest response time to it.
Must be a LEFT JOIN, because not all messages actually have a response. And you need the group, because they could have more than one response.

You then have the two times and can calculate the difference in minutes in PHP for the output.


问:
File.open fails to open relative path if path is bigger than certain size
```<code>require 'FileUtils'
path = '../tmp/brpm_storage/FGRKKSSUI/lentkriskeditor/1.2.5/20170705121128/lentkriskeditor-1.2.5-dist/lentkriskeditor-1.2.5/jre/jre1.8.0_131/lib/desktop/icons/HighContrast/48x48/mimetypes/gnome-mime-application-x-java-jnlp-file.png'

FileUtils.mkdir_p(File.dirname(path))

File.open(path, 'wb') {|file|
# File.open(File.expand_path(path), 'wb') {|file|  # Full path always works
    file.write('Hello')
}
</code>```

fails

```<code>tmp.rb:6:in `initialize': No such file or directory - ../tmp/brpm_storage/FGRKKSSUI/lentkriskeditor/1.2.5/20170705121128/lentkriskeditor-1.2.5-dist/lentkriskeditor-1.2.5/jre/jre1.8.0_131/lib/desktop/icons/HighContrast/48x48/mimetypes/gnome-mime-application-x-java-jnlp-file.png (Errno::ENOENT)
"C:/src3/branches/PSENG-5315/BMC/utils/tmp/brpm_storage/FGRKKSSUI/lentkriskeditor/1.2.5/20170705121128/lentkriskeditor-1.2.5-dist/lentkriskeditor-1.2.5/jre/jre1.8.0_131/lib/desktop/icons/HighContrast/48x48/mimetypes/gnome-mime-application-x-java-jnlp-file.png"
    from C:/src3/branches/PSENG-5315/BMC/utils/yatra_logic/tmp.rb:6:in `open'
    from C:/src3/branches/PSENG-5315/BMC/utils/yatra_logic/tmp.rb:6:in `<top (required)>'
    from -e:1:in `load'
    from -e:1:in `<main>'
</code>```

I noticed this phenomena in ruby 1.9.3 v551 and 2.0.0. With JRuby everything works as expected. I wonder what is the culprit?

```<code>c:\Ruby200\bin\ruby.exe -v
ruby 2.0.0p0 (2013-02-24) [i386-mingw32]
</code>```

答:
See Why does the 260 character path length limit exist in Windows? and https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx

Certain Windows APIs have a file path string-length limit of 260 'characters.' (I assume that refers to a Windows CP-1252 character.)

I suspect that JRuby navigates file paths through the JVM, which works around this limitation.  See How does Java circumvent the windows MAX_PATH WinAPI limitation.

Body:
require 'FileUtils'
path = '../tmp/brpm_storage/FGRKKSSUI/lentkriskeditor/1.2.5/20170705121128/lentkriskeditor-1.2.5-dist/lentkriskeditor-1.2.5/jre/jre1.8.0_131/lib/desktop/icons/HighContrast/48x48/mimetypes/gnome-mime-application-x-java-jnlp-file.png'

FileUtils.mkdir_p(File.dirname(path))

File.open(path, 'wb') {|file|
# File.open(File.expand_path(path), 'wb') {|file|  # Full path always works
    file.write('Hello')
}

fails

tmp.rb:6:in `initialize': No such file or directory - ../tmp/brpm_storage/FGRKKSSUI/lentkriskeditor/1.2.5/20170705121128/lentkriskeditor-1.2.5-dist/lentkriskeditor-1.2.5/jre/jre1.8.0_131/lib/desktop/icons/HighContrast/48x48/mimetypes/gnome-mime-application-x-java-jnlp-file.png (Errno::ENOENT)
"C:/src3/branches/PSENG-5315/BMC/utils/tmp/brpm_storage/FGRKKSSUI/lentkriskeditor/1.2.5/20170705121128/lentkriskeditor-1.2.5-dist/lentkriskeditor-1.2.5/jre/jre1.8.0_131/lib/desktop/icons/HighContrast/48x48/mimetypes/gnome-mime-application-x-java-jnlp-file.png"
    from C:/src3/branches/PSENG-5315/BMC/utils/yatra_logic/tmp.rb:6:in `open'
    from C:/src3/branches/PSENG-5315/BMC/utils/yatra_logic/tmp.rb:6:in `<top (required)>'
    from -e:1:in `load'
    from -e:1:in `'

I noticed this phenomena in ruby 1.9.3 v551 and 2.0.0. With JRuby everything works as expected. I wonder what is the culprit?

c:\Ruby200\bin\ruby.exe -v
ruby 2.0.0p0 (2013-02-24) [i386-mingw32]


问:
Getting text from XPath but want elements?
I am new to XPath so please bear with me. Basic question.

I want to select text, including the elements as well.  Example input below:

```<code><node1>
    <node2>
        <node3>A1</node3>
        <node3>A2</node3>
        <node3>A3</node3>
        <node3>A4</node3>
    </node2>
</node1>
</code>```

I wish to copy the content of node 2 including the tags, which is:

```<code><node2>
    <node3>A1</node3>
    <node3>A2</node3>
    <node3>A3</node3>
    <node3>A4</node3>
</node2>
</code>```

However, if I use the XPath /node1/node2/, I only get values A1 A2 A3 A4 (not the node2 and node3 tags).

答: The xpath /node1/node2 should return a list of nodes. Each node, depending on what language you are using contains attributes such as nodeName or nodeValue that you could use to access both the contained text and the name of the tag.

Body:
I am new to XPath so please bear with me. Basic question.

I want to select text, including the elements as well.  Example input below:

<node1>
    <node2>
        <node3>A1</node3>
        <node3>A2</node3>
        <node3>A3</node3>
        <node3>A4</node3>
    </node2>
</node1>

I wish to copy the content of node 2 including the tags, which is:

<node2>
    <node3>A1</node3>
    <node3>A2</node3>
    <node3>A3</node3>
    <node3>A4</node3>
</node2>

However, if I use the XPath /node1/node2/, I only get values A1 A2 A3 A4 (not the node2 and node3 tags).


问:
What return ostream::write?
Cplusplus say "The ostream object (* this)" but I do not understand. Return ostream object's pointer? I have try print this value with cout function but I print always 0. And how can this value be useful?</p>

答:
Generally in C++, methods' classes that don't have to return a specific value, like in this case (or with string for example), return *this.

Every object in C++ has access to its own address through an important pointer called this pointer. The this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this may be used to refer to the invoking object.

Thanks to this, you can use the method chaining, this is an example:

```<code>char c[]="This this this";
std::cout << (std::cout.write(c,4) << " hello ") << std::endl;
</code>```

Output:
This hello 0x600e08

In this example I used operator chaining on purpose, but it's the same with methods.

0x600e08 is address of your basic_ostream object.

Title: What return ostream::write?

Body:
Generally in C++, methods' classes that don't have to return a specific value, like in this case (or with string for example), return *this.

Every object in C++ has access to its own address through an important pointer called this pointer. The this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this may be used to refer to the invoking object.

Thanks to this, you can use the method chaining, this is an example:

char c[]="This this this";
std::cout << (std::cout.write(c,4) << " hello ") << std::endl;

Output:
This hello 0x600e08

In this example I used operator chaining on purpose, but it's the same with methods.

0x600e08 is address of your basic_ostream object.