问:
Can I use strcmp without pointers?
I have to make a program which takes a file of DNA sequences and a DNA subsequence from command arguments and find each time the subsequence and how many times it occurs. I'm having troubles with strcmp in line 36 and 42. Currently the way I have it I figured out through GDB that I am comparing the address of the strings and not the actual strings. But if I remove the & I get an error. I'm not sure what is the correct way to go about this is. TIA

```<code>#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    // place subsequence in string
    char *subsequence = argv[2];
    // get length of subsequence
    int seqLength = strlen(subsequence);
    // define file type and open for reading
    FILE *inputFile = fopen(argv[1], "r");
    // get each line using while loop
    char inputLine[200]; // string variable to store each line
    int i, j, lineLength, counter = 0, flag = -1;

    while (fgets(inputLine, 200, inputFile) != NULL) { // loop through each line
        lineLength = strlen(inputLine);

        for (i = 0; i < lineLength; i++) { // loop through each char in the line
            if (strcmp(&inputLine[i], &subsequence[0]) == 0) {
            // if current char matches beginning of sequence loop through
            // each of the remaining chars and check them against
            // corresponding chars in the sequence

                flag = 0;

                for (j = i + 1; j - i < seqLength; j++) {
                    if (strcmp(&inputLine[j], &subsequence[j - i]) != 0) {
                        flag = 1;
                        break;
                    }
                }

                if (flag == 0) {
                    counter++;
                }
            }
        }
    }

    fclose(inputFile);
    printf("%s appears %d time(s)\n", subsequence, counter);
    return 0;
}
</code>```

dna.txt:

```<code>GGAAGTAGCAGGCCGCATGCTTGGAGGTAAAGTTCATGGTTCCCTGGCCC
</code>```

input:

```<code>./dnaSearch dna.txt GTA
</code>```

expected output:

```<code>GTA appears 2 times
</code>```

答:
As others have mentioned, you don't need to call strcmp the first time since you're only checking a single character.  You can just compare them directly:

```<code>if (inputLine[i] == subsequence[0]) {
</code>```

However, there's a must simpler way of doing what you want.  Since you're looking for a substring inside of another string, you can use the strstr function to do that:

```<code>while (fgets(inputLine, 200, inputFile) != NULL) { // loop through each line
    char *sub = inputLine;
    while ((sub = strstr(sub, subsequence) != NULL) {
        counter++;
        sub++;
    }
}
</code>```

The strstr function will return a pointer inside the string to search of the substring that was found, or NULL if none was found.  In the above code, if the substring is found the counter is incremented, then the substring pointer is moved up to continue the search.

Title: Can I use strcmp without pointers?

Body:
I have to make a program which takes a file of DNA sequences and a DNA subsequence from command arguments and find each time the subsequence and how many times it occurs. I'm having troubles with strcmp in line 36 and 42. Currently the way I have it I figured out through GDB that I am comparing the address of the strings and not the actual strings. But if I remove the & I get an error. I'm not sure what is the correct way to go about this is. TIA

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    // place subsequence in string
    char *subsequence = argv[2];
    // get length of subsequence
    int seqLength = strlen(subsequence);
    // define file type and open for reading
    FILE *inputFile = fopen(argv[1], "r");
    // get each line using while loop
    char inputLine[200]; // string variable to store each line
    int i, j, lineLength, counter = 0, flag = -1;

    while (fgets(inputLine, 200, inputFile) != NULL) { // loop through each line
        lineLength = strlen(inputLine);

        for (i = 0; i < lineLength; i++) { // loop through each char in the line
            if (strcmp(&inputLine[i], &subsequence[0]) == 0) {
            // if current char matches beginning of sequence loop through
            // each of the remaining chars and check them against
            // corresponding chars in the sequence

                flag = 0;

                for (j = i + 1; j - i < seqLength; j++) {
                    if (strcmp(&inputLine[j], &subsequence[j - i]) != 0) {
                        flag = 1;
                        break;
                    }
                }

                if (flag == 0) {
                    counter++;
                }
            }
        }
    }

    fclose(inputFile);
    printf("%s appears %d time(s)\n", subsequence, counter);
    return 0;
}

dna.txt:

GGAAGTAGCAGGCCGCATGCTTGGAGGTAAAGTTCATGGTTCCCTGGCCC

input:

./dnaSearch dna.txt GTA

expected output:

GTA appears 2 times

Body:
As others have mentioned, you don't need to call strcmp the first time since you're only checking a single character.  You can just compare them directly:

if (inputLine[i] == subsequence[0]) {

However, there's a must simpler way of doing what you want.  Since you're looking for a substring inside of another string, you can use the strstr function to do that:

while (fgets(inputLine, 200, inputFile) != NULL) { // loop through each line
    char *sub = inputLine;
    while ((sub = strstr(sub, subsequence) != NULL) {
        counter++;
        sub++;
    }
}

The strstr function will return a pointer inside the string to search of the substring that was found, or NULL if none was found.  In the above code, if the substring is found the counter is incremented, then the substring pointer is moved up to continue the search.


来源: stackexchange

问:
ERROR: argument is of length zero in shiny::runApp
What is wrong? I get ERROR: argument is of length zero in shiny::runApp when I run

```<code>library(shiny)
runApp("C:\\R\\4p\\frontEnd2\\shiny")
</code>```

Sometimes it works, sometimes not. When I restart it usually begin to work again.

答: Finally I found it manually. UI has using a variable from global which was numeric and UI was treating it as a factor levels(x)[1]

ContentLicense: CC BY-SA 3.0

Body:
What is wrong? I get ERROR: argument is of length zero in shiny::runApp when I run

library(shiny)
runApp("C:\\R\\4p\\frontEnd2\\shiny")

Sometimes it works, sometimes not. When I restart it usually begin to work again.

ContentLicense: CC BY-SA 4.0


问:
Get SubKeys of Json in JavaScript
I have this code, but it doesn't prints subkeys....

```<code>    for (var key in result) {
        if (!result.hasOwnProperty(key)) continue;
        var obj = result[key];
        for (var prop in obj) {
            if (!obj.hasOwnProperty(prop)) continue;
            alert(prop + " = " + obj[prop]);
        }
    }
</code>```

When is an object print: someKey[Object object]

my result (example):

[ { "branch_id": 992, "sale_id": 24422, "identifier": "", "emitter": { "id": 68, "tax_id": "", "address": { "street": "Carretera a buenavista km 21", "country_code": "MEX", } } } ]

答:
You can use a recursive approach. For any key, if it contains an object value, you can once again call the same function again.

const data = [{ "branch_id": 992, "sale_id": 24422, "identifier": "", "emitter": { "id": 68, "tax_id": "", "address": { "street": "Carretera a buenavista km 21", "country_code": "MEX", } } } ];

const ObjectKey = o => {
  Object.keys(o).forEach(k => {
    if(typeof o[k] === 'object'){
      ObjectKey(o[k]);
    } else {
      console.log(k, " ", o[k]);
    }
  });
}

data.forEach(o => {
  ObjectKey(o);
});```

Title: Get SubKeys of Json in JavaScript

Body:
I have this code, but it doesn't prints subkeys....

    for (var key in result) {
        if (!result.hasOwnProperty(key)) continue;
        var obj = result[key];
        for (var prop in obj) {
            if (!obj.hasOwnProperty(prop)) continue;
            alert(prop + " = " + obj[prop]);
        }
    }

When is an object print: someKey[Object object]

my result (example):

[ { "branch_id": 992, "sale_id": 24422, "identifier": "", "emitter": { "id": 68, "tax_id": "", "address": { "street": "Carretera a buenavista km 21", "country_code": "MEX", } } } ]


问:
Python BeautifulSoup scraping web page that has protection
I am new to Python. My recent project is to get the odd information from a website.

Here is the URL:

http://bet.hkjc.com/default.aspx?url=football/odds/odds_allodds.aspx&lang=EN&tmatchid=120998

I am using Python and BeautifulSoup to process, i cant see any odd data when get the html by

```<code>soup.prettify()
</code>```

The result from above code i got is only logical code, variable and function. i think the page have some protection to the data

what should i do to get the odd information from the protected web page?

答: It looks like it's not protected, but just generated with javascript. And beautifulsoup can't handle JS. The first work-around most people come to is automating a web browser using something like selenium. You can use this to get the html after the JS has run, and then parse with beautifulsoup as needed. </p>

Body:
I am new to Python. My recent project is to get the odd information from a website.

Here is the URL:

http://bet.hkjc.com/default.aspx?url=football/odds/odds_allodds.aspx&lang=EN&tmatchid=120998

I am using Python and BeautifulSoup to process, i cant see any odd data when get the html by

soup.prettify()

The result from above code i got is only logical code, variable and function. i think the page have some protection to the data

what should i do to get the odd information from the protected web page?


问:
how to launch a sequential code on gpu
I have a CPU code:

```<code> `if(number_of_pushed_particles<N&&number_of_alive_particles<K)
 {
   push_particle();
   number_of_pushed_particles++;
 }`
</code>```

Here number_of_pushed_particles, number_of_alive_particles, K and N are int, K and N are const. The function push_particle() is:

```<code> `push_particle()
 {
   particles[LIFE].id=++MAX_ELEMENT;
   particles[LIFE].rx=0.0;
   particles[LIFE].ry=0.0;
   particles[LIFE].rz=0.0;
   ...
   ++LIFE;
 }
</code>```

`Particle is a structure of floats.The array Particle particles[0:GL], integer variables LIFE and MAX_ELEMENT are statically allocated on the device. That is why i do not want to use #pragma acc update host/device before/after calling the push_particle() function and lose time for copying data. How can i launch this sequential code on the GPU?

答:
The OpenACC 2.6 standard which was just ratified includes a "serial" region but it will be a bit before this support is added to the various compiler implementations.

The current method is to use a "parallel" region and set "num_gangs(1)" and "vector_length(1)".

Something like:

```<code>push_particle()
 {
#pragma acc parallel num_gangs(1) vector_length(1) present(particles)
{
   particles[LIFE].id=++MAX_ELEMENT;
   particles[LIFE].rx=0.0;
   particles[LIFE].ry=0.0;
   particles[LIFE].rz=0.0;
   ...
   ++LIFE;
}
</code>```

}

Title: how to launch a sequential code on gpu

Body:
I have a CPU code:

 `if(number_of_pushed_particles<N&&number_of_alive_particles<K)
 {
   push_particle();
   number_of_pushed_particles++;
 }`

Here number_of_pushed_particles, number_of_alive_particles, K and N are int, K and N are const. The function push_particle() is:

 `push_particle()
 {
   particles[LIFE].id=++MAX_ELEMENT;
   particles[LIFE].rx=0.0;
   particles[LIFE].ry=0.0;
   particles[LIFE].rz=0.0;
   ...
   ++LIFE;
 }

`Particle is a structure of floats.The array Particle particles[0:GL], integer variables LIFE and MAX_ELEMENT are statically allocated on the device. That is why i do not want to use #pragma acc update host/device before/after calling the push_particle() function and lose time for copying data. How can i launch this sequential code on the GPU?

Body:
The OpenACC 2.6 standard which was just ratified includes a "serial" region but it will be a bit before this support is added to the various compiler implementations.

The current method is to use a "parallel" region and set "num_gangs(1)" and "vector_length(1)".

Something like:

push_particle()
 {
#pragma acc parallel num_gangs(1) vector_length(1) present(particles)
{
   particles[LIFE].id=++MAX_ELEMENT;
   particles[LIFE].rx=0.0;
   particles[LIFE].ry=0.0;
   particles[LIFE].rz=0.0;
   ...
   ++LIFE;
}

}


问:
Android ListView setSelection() does not seem to work
I have a ListActivity that implements onListItemClick() and calls a doSomething() function of the class. The latter contains l.setSelection(position) where l is the ListView object.

Now there is a onClickListener() listening for a button click that perfoms some actions and that too calls doSomething().

In the first case, the selected item get positioned appropriately, but in the latter, nothing happens.

Any clues about this strange behaviour and how I might make it work?

答:
maybe you need to use function:</p>

```<code>ListView.setItemChecked(int position, boolean checked);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
maybe you need to use function:

ListView.setItemChecked(int position, boolean checked);


问:
Amazon Lex (Chatbot) access in custom wordpress plugin
Please let me know how can i access Amazon Lex API in my custom wordpress plugin? How to call API, and which API i should call, how it will work in php wordpress?

Thanks.

答:
There are two APIs you can use depending on what you're trying to accomplish. If you want to interact with a chatbot that has already been created you'd use the runtime API. Here is a link for the documentation to that.

http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/LexRuntime.html

If you need to create or modify a chatbot you'd use the Model Building Service API. Here is a link to that documentation.

http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/LexModelBuildingService.html


问:
In OpenShift 3, how to run a docker image that requires root?
In OpenShift 3, how can deploy a docker image that requires root?</p>

答:
Easier command to grant containers in specific project to run as any UID, including root, is:

```<code>oc adm policy add-scc-to-user anyuid -z default -n myproject
</code>```

This would need to be run as a cluster admin. A normal user, or even a project admin, cannot run this command.

If using OpenShift Online you will not be able to do this.

Body:
Easier command to grant containers in specific project to run as any UID, including root, is:

oc adm policy add-scc-to-user anyuid -z default -n myproject

This would need to be run as a cluster admin. A normal user, or even a project admin, cannot run this command.

If using OpenShift Online you will not be able to do this.


问:
How can I fix "Design editor is unavailable until a successful build" error?
I started to learn Android Studio. I try to echo out simple "Hello World":

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:id="@+id/activity_main"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    android:paddingBottom="16dp"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

</RelativeLayout>
</code>```

but when I clicked "design" view, this error is showing?

Design editor is unavailable until a successful build

How can I fix this error.

I just noticed that my xml code is causing error. Is that why this may be not working?

答:
Do this

Build -> Rebuild Project

Body:
I started to learn Android Studio. I try to echo out simple "Hello World":

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:id="@+id/activity_main"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    android:paddingBottom="16dp"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

</RelativeLayout>

but when I clicked "design" view, this error is showing?

Design editor is unavailable until a successful build

How can I fix this error.

I just noticed that my xml code is causing error. Is that why this may be not working?

Body:
Do this

Build -> Rebuild Project


问:
Greasemonkey change div id class
I'm trying to change the class to "sidebar" and style height to "50%" of this div (Facebook):

```<code><div id="pagelet_ticker" class="hidden_elem" style="height: 0px;">
</code>```

I don't know why the following Greasemonkey script is not working. Any suggestions are much appreciated. Thank you!
---Edited to reflect the changes suggested --- still not working

```<code>// ==UserScript==
// @name           Ticker
// @namespace      Ticker
// @description    Ticker
// @include        https://www.facebook.com
// ==/UserScript==

var query = document.querySelector('#pagelet_ticker'); //added #
        query.setAttribute("class", "sidebar");
        query.setAttribute("style", "height: 50%;");  //changed attribute to style
</code>```

答:
Does this work for you?

var query = document.querySelector('#pagelet_ticker'); //added #
query.classList.add('sidebar');
query.style.height = "50%";  //changed attribute to style```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.sidebar {
  background-color: red;
}</code>```

Wee
```

Title: Greasemonkey change div id class

Body:
I'm trying to change the class to "sidebar" and style height to "50%" of this div (Facebook):

I don't know why the following Greasemonkey script is not working. Any suggestions are much appreciated. Thank you!
---Edited to reflect the changes suggested --- still not working

// ==UserScript==
// @name           Ticker
// @namespace      Ticker
// @description    Ticker
// @include        https://www.facebook.com
// ==/UserScript==

var query = document.querySelector('#pagelet_ticker'); //added #
        query.setAttribute("class", "sidebar");
        query.setAttribute("style", "height: 50%;");  //changed attribute to style

Body:
Does this work for you?

var query = document.querySelector('#pagelet_ticker'); //added #
query.classList.add('sidebar');
query.style.height = "50%";  //changed attribute to style

.sidebar {
  background-color: red;
}

<div id="pagelet_ticker" class="hidden_elem" style="height: 0px;">Wee</div>


问:
Tensorflow GradientBoostedDecisionTreeClassifier error : "Dense float feature must be a matrix"
I am getting the error:

“tensorflow.python.framework.errors_impl.InvalidArgumentError: Dense float feature must be a matrix.” when training with estimator tensorflow.contrib.boosted_trees.estimator_batch.estimator.GradientBoostedDecisionTreeClassifier. I am using Tensorflow version 1.4.0. The same code works correctly if I change estimator to tf.contrib.learn.DNNClassifier. In the code, dictionary of features are passed in “Train_input_fn” in tf.contrib.learn.Experiment.

Anyone faced similar error before?

```<code>#'tensorflow==1.4.0'

import tensorflow as tf
import argparse
import sys
import os
from tensorflow.contrib.boosted_trees.estimator_batch.estimator import GradientBoostedDecisionTreeClassifier
from tensorflow.contrib.boosted_trees.proto import learner_pb2
from tensorflow_transform.tf_metadata import metadata_io
from tensorflow_transform.saved import input_fn_maker
from tensorflow.contrib.learn.python.learn import learn_runner

RAW_METADATA_DIR="raw_metadata"
CONTRACTED_METADATA_DIR="contracted_metadata"
TRANSFORMED_METADATA_DIR="transformed_metadata"

TRANSFORMED_TRAIN_DATA_FILE_PREFIX="train"
TRANSFORMED_EVAL_DATA_FILE_PREFIX="eval"
DATA_FILE_SUFFIX=".tfrecord.gz"
TRANSFORM_FN_DIR="transform_fn"
TARGET_FEATURE_COLUMN='target_field'

FEATURE_NUMERICAL_COLUMN_NAMES = [
  'feature1',
  'feature2',
  'feature3',
  'feature4',
  'feature5'
  ]

FEATURE_INTEGER_COLUMN_NAMES = [ # comment out fields that are not features
  'feature6',
  'feature7',
  'feature8',
  'feature9',
  'feature10'
]

def _parse_arguments(argv):
  """Parses command line arguments."""
  parser = argparse.ArgumentParser(
      description="Runs training on data.")
  parser.add_argument(
      "--model_dir", required=True, type=str,
      help="The directory where model outputs will be written")
  parser.add_argument(
      "--input_dir", required=True, type=str,
      help=("GCS or local directory containing tensorflow-transform outputs."))
  parser.add_argument(
      "--batch_size", default=30, required=False, type=int,
      help=("Batch size to use during training."))
  parser.add_argument(
      "--num_epochs", default=100, required=False, type=int,
      help=("Number of epochs through the training set"))
  args, _ = parser.parse_known_args(args=argv[1:])
  return args

def get_eval_metrics():
    return {
        "accuracy":
            tf.contrib.learn.MetricSpec(
                metric_fn=tf.contrib.metrics.streaming_accuracy,
                prediction_key=tf.contrib.learn.PredictionKey.CLASSES),
        "precision":
            tf.contrib.learn.MetricSpec(
                metric_fn=tf.contrib.metrics.streaming_precision,
                prediction_key=tf.contrib.learn.PredictionKey.CLASSES),
        "recall":
            tf.contrib.learn.MetricSpec(
                metric_fn=tf.contrib.metrics.streaming_recall,
                prediction_key=tf.contrib.learn.PredictionKey.CLASSES)
        }

def read_and_decode_single_record(input_dir, num_epochs,
        mode=tf.contrib.learn.ModeKeys.TRAIN):
  if mode == tf.contrib.learn.ModeKeys.TRAIN:
      num_epochs = num_epochs
      file_prefix = TRANSFORMED_TRAIN_DATA_FILE_PREFIX
  else:
      num_epochs = 1
      file_prefix = TRANSFORMED_EVAL_DATA_FILE_PREFIX

  transformed_metadata = metadata_io.read_metadata(os.path.join(input_dir,
      TRANSFORMED_METADATA_DIR))
  input_file_names = tf.train.match_filenames_once(os.path.join(input_dir,
      '{}*{}'.format(file_prefix, DATA_FILE_SUFFIX)))
  filename_queue = tf.train.string_input_producer(input_file_names,
          num_epochs=num_epochs, shuffle=True)

  reader = tf.TFRecordReader(options=tf.python_io.TFRecordOptions(
      tf.python_io.TFRecordCompressionType.GZIP))
  _, serialized_example = reader.read(filename_queue)

  features = tf.parse_single_example(
      serialized = serialized_example,
      features=transformed_metadata.schema.as_feature_spec()
  )
  return features

def read_dataset(input_dir, num_epochs, batch_size, mode=tf.contrib.learn.ModeKeys.TRAIN):
  def _input_fn():
    min_after_dequeue = 10000
    features = read_and_decode_single_record(input_dir, num_epochs, mode)
    features = tf.train.shuffle_batch(
            tensors=features,
            batch_size=batch_size,
            min_after_dequeue=min_after_dequeue,
            capacity=(min_after_dequeue + 3) * batch_size)
    target = features.pop(TARGET_FEATURE_COLUMN)
    return features, target
  return _input_fn

def specify_feature_columns():
    feature_columns = [
        tf.contrib.layers.real_valued_column(column_name = column_name)
        for column_name in FEATURE_NUMERICAL_COLUMN_NAMES]
    feature_columns.extend([
        tf.contrib.layers.real_valued_column(column_name = column_name)
        for column_name in FEATURE_INTEGER_COLUMN_NAMES])
    return feature_columns

def build_estimator(model_dir, config, params):
    print "Using gradient boosted decision trees estimator \n"
    learner_config = learner_pb2.LearnerConfig()
    learner_config.learning_rate_tuner.fixed.learning_rate = 0.1
    learner_config.regularization.l1 = 0.0
    learner_config.regularization.l2 = 4.0 / params.batch_size
    learner_config.constraints.max_tree_depth = 4
    learner_config.growing_mode = learner_pb2.LearnerConfig.WHOLE_TREE
    return GradientBoostedDecisionTreeClassifier(
        learner_config=learner_config,
        examples_per_layer=params.batch_size,
        num_trees=100,
        center_bias=False,
        feature_columns=specify_feature_columns()
        # feature_engineering_fn=feature_engineering_fn
        )

def get_experiment_fn(args):
    config = tf.contrib.learn.RunConfig(save_checkpoints_steps=1000)
    def experiment_fn(output_dir):
      return tf.contrib.learn.Experiment(
            estimator = build_estimator(model_dir = output_dir,
                                              config = config,
                                              params = args),
            train_input_fn = read_dataset(args.input_dir,
                args.num_epochs, args.batch_size,
                mode=tf.contrib.learn.ModeKeys.TRAIN),
            eval_input_fn = read_dataset(args.input_dir,
                args.num_epochs, args.batch_size,
                mode=tf.contrib.learn.ModeKeys.EVAL),
            eval_metrics = get_eval_metrics())
    return experiment_fn

def run(args):
    learn_runner.run(get_experiment_fn(args), args.model_dir)

if __name__ == '__main__':
    args = _parse_arguments(sys.argv)
    run(args)
</code>```

The full error trace:

```<code>WARNING:tensorflow:Using temporary folder as model directory: /var/folders/mg/sd4_qlyj4_lbh5ggfn6frvcr00fk8_/T/tmpPFhins
WARNING:tensorflow:From /Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/monitors.py:267: __init__ (from tensorflow.contrib.learn.python.learn.monitors) is deprecated and will be removed after 2016-12-05.
Instructions for updating:
Monitors are deprecated. Please use tf.train.SessionRunHook.
WARNING:tensorflow:Casting <dtype: 'int64'> labels to bool.
WARNING:tensorflow:Casting <dtype: 'int64'> labels to bool.
WARNING:tensorflow:Error encountered when serializing resources.
Type is unsupported, or the types of the items don't match field type in CollectionDef.
'_Resource' object has no attribute 'name'
2017-11-16 13:38:39.919664: I tensorflow/core/platform/cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX AVX2 FMA
WARNING:tensorflow:Error encountered when serializing resources.
Type is unsupported, or the types of the items don't match field type in CollectionDef.
'_Resource' object has no attribute 'name'
2017-11-16 13:38:48.810825: W tensorflow/core/framework/op_kernel.cc:1192] Invalid argument: Dense float feature must be a matrix.
2017-11-16 13:38:48.810825: W tensorflow/core/framework/op_kernel.cc:1192] Invalid argument: Dense float feature must be a matrix.
Traceback (most recent call last):
  File "./trainer/task.py", line 162, in <module>
    run(args)
  File "./trainer/task.py", line 157, in run
    learn_runner.run(get_experiment_fn(args), args.model_dir)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/learn_runner.py", line 218, in run
    return _execute_schedule(experiment, schedule)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/learn_runner.py", line 46, in _execute_schedule
    return task()
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/experiment.py", line 625, in train_and_evaluate
    self.train(delay_secs=0)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/experiment.py", line 367, in train
    hooks=self._train_monitors + extra_hooks)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/experiment.py", line 812, in _call_train
    monitors=hooks)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/util/deprecation.py", line 316, in new_func
    return func(*args, **kwargs)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 480, in fit
    loss = self._train_model(input_fn=input_fn, hooks=hooks)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 1040, in _train_model
    _, loss = mon_sess.run([model_fn_ops.train_op, model_fn_ops.loss])
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/training/monitored_session.py", line 521, in run
    run_metadata=run_metadata)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/training/monitored_session.py", line 892, in run
    run_metadata=run_metadata)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/training/monitored_session.py", line 967, in run
    raise six.reraise(*original_exc_info)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/training/monitored_session.py", line 952, in run
    return self._sess.run(*args, **kwargs)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/training/monitored_session.py", line 1024, in run
    run_metadata=run_metadata)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/training/monitored_session.py", line 827, in run
    return self._sess.run(*args, **kwargs)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 889, in run
    run_metadata_ptr)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1120, in _run
    feed_dict_tensor, options, run_metadata)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1317, in _do_run
    options, run_metadata)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1336, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: Dense float feature must be a matrix.
     [[Node: gbdt_1/GradientTreesPartitionExamples = GradientTreesPartitionExamples[num_dense_float_features=10, num_sparse_float_features=0, num_sparse_int_features=0, use_locking=true, _device="/job:localhost/replica:0/task:0/device:CPU:0"](ensemble_model, shuffle_batch:16, shuffle_batch:18, shuffle_batch:20, shuffle_batch:21, shuffle_batch:22, shuffle_batch:23, shuffle_batch:24, shuffle_batch:25, shuffle_batch:26, shuffle_batch:27, ^gbdt_1/TreeEnsembleStats)]]

Caused by op u'gbdt_1/GradientTreesPartitionExamples', defined at:
  File "./trainer/task.py", line 162, in <module>
    run(args)
  File "./trainer/task.py", line 157, in run
    learn_runner.run(get_experiment_fn(args), args.model_dir)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/learn_runner.py", line 218, in run
    return _execute_schedule(experiment, schedule)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/learn_runner.py", line 46, in _execute_schedule
    return task()
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/experiment.py", line 625, in train_and_evaluate
    self.train(delay_secs=0)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/experiment.py", line 367, in train
    hooks=self._train_monitors + extra_hooks)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/experiment.py", line 812, in _call_train
    monitors=hooks)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/util/deprecation.py", line 316, in new_func
    return func(*args, **kwargs)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 480, in fit
    loss = self._train_model(input_fn=input_fn, hooks=hooks)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 986, in _train_model
    model_fn_ops = self._get_train_ops(features, labels)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 1202, in _get_train_ops
    return self._call_model_fn(features, labels, model_fn_lib.ModeKeys.TRAIN)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 1166, in _call_model_fn
    model_fn_results = self._model_fn(features, labels, **kwargs)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/boosted_trees/estimator_batch/model.py", line 98, in model_builder
    predictions_dict = gbdt_model.predict(mode)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/boosted_trees/python/training/functions/gbdt_batch.py", line 463, in predict
    ensemble_stamp, mode)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/boosted_trees/python/training/functions/gbdt_batch.py", line 392, in _predict_and_return_dict
    use_locking=True)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/boosted_trees/python/ops/gen_prediction_ops.py", line 117, in gradient_trees_partition_examples
    use_locking=use_locking, name=name)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 787, in _apply_op_helper
    op_def=op_def)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2956, in create_op
    op_def=op_def)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1470, in __init__
    self._traceback = self._graph._extract_stack()  # pylint: disable=protected-access

InvalidArgumentError (see above for traceback): Dense float feature must be a matrix.
     [[Node: gbdt_1/GradientTreesPartitionExamples = GradientTreesPartitionExamples[num_dense_float_features=10, num_sparse_float_features=0, num_sparse_int_features=0, use_locking=true, _device="/job:localhost/replica:0/task:0/device:CPU:0"](ensemble_model, shuffle_batch:16, shuffle_batch:18, shuffle_batch:20, shuffle_batch:21, shuffle_batch:22, shuffle_batch:23, shuffle_batch:24, shuffle_batch:25, shuffle_batch:26, shuffle_batch:27, ^gbdt_1/TreeEnsembleStats)]]
</code>```

答:
I am guessing that the parsing spec created by tf.transform is different from what we normally get.
Can you share the output of transformed_metadata.schema.as_feature_spec()?

As a work-around try adding this line to your input_fn after features = tf.train.shuffle_batch(...):

features = {feature_name: tf.reshape(feature_value, [-1, 1]) for
            feature_name, feature_value in features.items()}

Body:
I am getting the error:

“tensorflow.python.framework.errors_impl.InvalidArgumentError: Dense float feature must be a matrix.” when training with estimator tensorflow.contrib.boosted_trees.estimator_batch.estimator.GradientBoostedDecisionTreeClassifier. I am using Tensorflow version 1.4.0. The same code works correctly if I change estimator to tf.contrib.learn.DNNClassifier. In the code, dictionary of features are passed in “Train_input_fn” in tf.contrib.learn.Experiment.

Anyone faced similar error before?

#'tensorflow==1.4.0'

import tensorflow as tf
import argparse
import sys
import os
from tensorflow.contrib.boosted_trees.estimator_batch.estimator import GradientBoostedDecisionTreeClassifier
from tensorflow.contrib.boosted_trees.proto import learner_pb2
from tensorflow_transform.tf_metadata import metadata_io
from tensorflow_transform.saved import input_fn_maker
from tensorflow.contrib.learn.python.learn import learn_runner

RAW_METADATA_DIR="raw_metadata"
CONTRACTED_METADATA_DIR="contracted_metadata"
TRANSFORMED_METADATA_DIR="transformed_metadata"

TRANSFORMED_TRAIN_DATA_FILE_PREFIX="train"
TRANSFORMED_EVAL_DATA_FILE_PREFIX="eval"
DATA_FILE_SUFFIX=".tfrecord.gz"
TRANSFORM_FN_DIR="transform_fn"
TARGET_FEATURE_COLUMN='target_field'

FEATURE_NUMERICAL_COLUMN_NAMES = [
  'feature1',
  'feature2',
  'feature3',
  'feature4',
  'feature5'
  ]

FEATURE_INTEGER_COLUMN_NAMES = [ # comment out fields that are not features
  'feature6',
  'feature7',
  'feature8',
  'feature9',
  'feature10'
]

def _parse_arguments(argv):
  """Parses command line arguments."""
  parser = argparse.ArgumentParser(
      description="Runs training on data.")
  parser.add_argument(
      "--model_dir", required=True, type=str,
      help="The directory where model outputs will be written")
  parser.add_argument(
      "--input_dir", required=True, type=str,
      help=("GCS or local directory containing tensorflow-transform outputs."))
  parser.add_argument(
      "--batch_size", default=30, required=False, type=int,
      help=("Batch size to use during training."))
  parser.add_argument(
      "--num_epochs", default=100, required=False, type=int,
      help=("Number of epochs through the training set"))
  args, _ = parser.parse_known_args(args=argv[1:])
  return args

def get_eval_metrics():
    return {
        "accuracy":
            tf.contrib.learn.MetricSpec(
                metric_fn=tf.contrib.metrics.streaming_accuracy,
                prediction_key=tf.contrib.learn.PredictionKey.CLASSES),
        "precision":
            tf.contrib.learn.MetricSpec(
                metric_fn=tf.contrib.metrics.streaming_precision,
                prediction_key=tf.contrib.learn.PredictionKey.CLASSES),
        "recall":
            tf.contrib.learn.MetricSpec(
                metric_fn=tf.contrib.metrics.streaming_recall,
                prediction_key=tf.contrib.learn.PredictionKey.CLASSES)
        }

def read_and_decode_single_record(input_dir, num_epochs,
        mode=tf.contrib.learn.ModeKeys.TRAIN):
  if mode == tf.contrib.learn.ModeKeys.TRAIN:
      num_epochs = num_epochs
      file_prefix = TRANSFORMED_TRAIN_DATA_FILE_PREFIX
  else:
      num_epochs = 1
      file_prefix = TRANSFORMED_EVAL_DATA_FILE_PREFIX

  transformed_metadata = metadata_io.read_metadata(os.path.join(input_dir,
      TRANSFORMED_METADATA_DIR))
  input_file_names = tf.train.match_filenames_once(os.path.join(input_dir,
      '{}*{}'.format(file_prefix, DATA_FILE_SUFFIX)))
  filename_queue = tf.train.string_input_producer(input_file_names,
          num_epochs=num_epochs, shuffle=True)

  reader = tf.TFRecordReader(options=tf.python_io.TFRecordOptions(
      tf.python_io.TFRecordCompressionType.GZIP))
  _, serialized_example = reader.read(filename_queue)

  features = tf.parse_single_example(
      serialized = serialized_example,
      features=transformed_metadata.schema.as_feature_spec()
  )
  return features

def read_dataset(input_dir, num_epochs, batch_size, mode=tf.contrib.learn.ModeKeys.TRAIN):
  def _input_fn():
    min_after_dequeue = 10000
    features = read_and_decode_single_record(input_dir, num_epochs, mode)
    features = tf.train.shuffle_batch(
            tensors=features,
            batch_size=batch_size,
            min_after_dequeue=min_after_dequeue,
            capacity=(min_after_dequeue + 3) * batch_size)
    target = features.pop(TARGET_FEATURE_COLUMN)
    return features, target
  return _input_fn

def specify_feature_columns():
    feature_columns = [
        tf.contrib.layers.real_valued_column(column_name = column_name)
        for column_name in FEATURE_NUMERICAL_COLUMN_NAMES]
    feature_columns.extend([
        tf.contrib.layers.real_valued_column(column_name = column_name)
        for column_name in FEATURE_INTEGER_COLUMN_NAMES])
    return feature_columns

def build_estimator(model_dir, config, params):
    print "Using gradient boosted decision trees estimator \n"
    learner_config = learner_pb2.LearnerConfig()
    learner_config.learning_rate_tuner.fixed.learning_rate = 0.1
    learner_config.regularization.l1 = 0.0
    learner_config.regularization.l2 = 4.0 / params.batch_size
    learner_config.constraints.max_tree_depth = 4
    learner_config.growing_mode = learner_pb2.LearnerConfig.WHOLE_TREE
    return GradientBoostedDecisionTreeClassifier(
        learner_config=learner_config,
        examples_per_layer=params.batch_size,
        num_trees=100,
        center_bias=False,
        feature_columns=specify_feature_columns()
        # feature_engineering_fn=feature_engineering_fn
        )

def get_experiment_fn(args):
    config = tf.contrib.learn.RunConfig(save_checkpoints_steps=1000)
    def experiment_fn(output_dir):
      return tf.contrib.learn.Experiment(
            estimator = build_estimator(model_dir = output_dir,
                                              config = config,
                                              params = args),
            train_input_fn = read_dataset(args.input_dir,
                args.num_epochs, args.batch_size,
                mode=tf.contrib.learn.ModeKeys.TRAIN),
            eval_input_fn = read_dataset(args.input_dir,
                args.num_epochs, args.batch_size,
                mode=tf.contrib.learn.ModeKeys.EVAL),
            eval_metrics = get_eval_metrics())
    return experiment_fn

def run(args):
    learn_runner.run(get_experiment_fn(args), args.model_dir)

if __name__ == '__main__':
    args = _parse_arguments(sys.argv)
    run(args)

The full error trace:

WARNING:tensorflow:Using temporary folder as model directory: /var/folders/mg/sd4_qlyj4_lbh5ggfn6frvcr00fk8_/T/tmpPFhins
WARNING:tensorflow:From /Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/monitors.py:267: __init__ (from tensorflow.contrib.learn.python.learn.monitors) is deprecated and will be removed after 2016-12-05.
Instructions for updating:
Monitors are deprecated. Please use tf.train.SessionRunHook.
WARNING:tensorflow:Casting <dtype: 'int64'> labels to bool.
WARNING:tensorflow:Casting <dtype: 'int64'> labels to bool.
WARNING:tensorflow:Error encountered when serializing resources.
Type is unsupported, or the types of the items don't match field type in CollectionDef.
'_Resource' object has no attribute 'name'
2017-11-16 13:38:39.919664: I tensorflow/core/platform/cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX AVX2 FMA
WARNING:tensorflow:Error encountered when serializing resources.
Type is unsupported, or the types of the items don't match field type in CollectionDef.
'_Resource' object has no attribute 'name'
2017-11-16 13:38:48.810825: W tensorflow/core/framework/op_kernel.cc:1192] Invalid argument: Dense float feature must be a matrix.
2017-11-16 13:38:48.810825: W tensorflow/core/framework/op_kernel.cc:1192] Invalid argument: Dense float feature must be a matrix.
Traceback (most recent call last):
  File "./trainer/task.py", line 162, in <module>
    run(args)
  File "./trainer/task.py", line 157, in run
    learn_runner.run(get_experiment_fn(args), args.model_dir)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/learn_runner.py", line 218, in run
    return _execute_schedule(experiment, schedule)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/learn_runner.py", line 46, in _execute_schedule
    return task()
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/experiment.py", line 625, in train_and_evaluate
    self.train(delay_secs=0)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/experiment.py", line 367, in train
    hooks=self._train_monitors + extra_hooks)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/experiment.py", line 812, in _call_train
    monitors=hooks)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/util/deprecation.py", line 316, in new_func
    return func(*args, **kwargs)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 480, in fit
    loss = self._train_model(input_fn=input_fn, hooks=hooks)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 1040, in _train_model
    _, loss = mon_sess.run([model_fn_ops.train_op, model_fn_ops.loss])
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/training/monitored_session.py", line 521, in run
    run_metadata=run_metadata)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/training/monitored_session.py", line 892, in run
    run_metadata=run_metadata)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/training/monitored_session.py", line 967, in run
    raise six.reraise(*original_exc_info)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/training/monitored_session.py", line 952, in run
    return self._sess.run(*args, **kwargs)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/training/monitored_session.py", line 1024, in run
    run_metadata=run_metadata)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/training/monitored_session.py", line 827, in run
    return self._sess.run(*args, **kwargs)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 889, in run
    run_metadata_ptr)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1120, in _run
    feed_dict_tensor, options, run_metadata)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1317, in _do_run
    options, run_metadata)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1336, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: Dense float feature must be a matrix.
     [[Node: gbdt_1/GradientTreesPartitionExamples = GradientTreesPartitionExamples[num_dense_float_features=10, num_sparse_float_features=0, num_sparse_int_features=0, use_locking=true, _device="/job:localhost/replica:0/task:0/device:CPU:0"](ensemble_model, shuffle_batch:16, shuffle_batch:18, shuffle_batch:20, shuffle_batch:21, shuffle_batch:22, shuffle_batch:23, shuffle_batch:24, shuffle_batch:25, shuffle_batch:26, shuffle_batch:27, ^gbdt_1/TreeEnsembleStats)]]

Caused by op u'gbdt_1/GradientTreesPartitionExamples', defined at:
  File "./trainer/task.py", line 162, in <module>
    run(args)
  File "./trainer/task.py", line 157, in run
    learn_runner.run(get_experiment_fn(args), args.model_dir)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/learn_runner.py", line 218, in run
    return _execute_schedule(experiment, schedule)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/learn_runner.py", line 46, in _execute_schedule
    return task()
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/experiment.py", line 625, in train_and_evaluate
    self.train(delay_secs=0)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/experiment.py", line 367, in train
    hooks=self._train_monitors + extra_hooks)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/experiment.py", line 812, in _call_train
    monitors=hooks)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/util/deprecation.py", line 316, in new_func
    return func(*args, **kwargs)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 480, in fit
    loss = self._train_model(input_fn=input_fn, hooks=hooks)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 986, in _train_model
    model_fn_ops = self._get_train_ops(features, labels)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 1202, in _get_train_ops
    return self._call_model_fn(features, labels, model_fn_lib.ModeKeys.TRAIN)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 1166, in _call_model_fn
    model_fn_results = self._model_fn(features, labels, **kwargs)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/boosted_trees/estimator_batch/model.py", line 98, in model_builder
    predictions_dict = gbdt_model.predict(mode)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/boosted_trees/python/training/functions/gbdt_batch.py", line 463, in predict
    ensemble_stamp, mode)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/boosted_trees/python/training/functions/gbdt_batch.py", line 392, in _predict_and_return_dict
    use_locking=True)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/contrib/boosted_trees/python/ops/gen_prediction_ops.py", line 117, in gradient_trees_partition_examples
    use_locking=use_locking, name=name)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 787, in _apply_op_helper
    op_def=op_def)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2956, in create_op
    op_def=op_def)
  File "/Users/amolsharma/anaconda/envs/oldpython/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1470, in __init__
    self._traceback = self._graph._extract_stack()  # pylint: disable=protected-access

InvalidArgumentError (see above for traceback): Dense float feature must be a matrix.
     [[Node: gbdt_1/GradientTreesPartitionExamples = GradientTreesPartitionExamples[num_dense_float_features=10, num_sparse_float_features=0, num_sparse_int_features=0, use_locking=true, _device="/job:localhost/replica:0/task:0/device:CPU:0"](ensemble_model, shuffle_batch:16, shuffle_batch:18, shuffle_batch:20, shuffle_batch:21, shuffle_batch:22, shuffle_batch:23, shuffle_batch:24, shuffle_batch:25, shuffle_batch:26, shuffle_batch:27, ^gbdt_1/TreeEnsembleStats)]]


问:
iphone / ipad Enterprise application Distribution
i have enterprise application distribution certificate to distribute application to certain employees in an organization.

Here how to delete a particular device id in that distribution certificate.

for example consider a person is run away from the organization with device means here how'll you restrict user to access the application in that particular device.

ANy idea...

答:
You could implement a startup check where the app will contact a server which holds a blacklist of UDIDs of devices known to be AWOL. The app would ask the server for permission to run upon startup by transmitting the UDID of its host device.

This will of course force your devices to be online (or otherwise able to contact the server) in order to run. If this is not possible under all circumstances, the permission to run could be valid for some time. For example, the app would start up for three days after the permission was last granted before requiring a new permit.


问:
How do I initialize a list with items of another list?
I'd like to initialize list2 (list of object) with each item of list 1 (list of string).

```<code>Dim list1 As New List(Of String) From {"a", "b", "c"}
Dim list2 As New List(Of Object) From {list1.ToArray()}
</code>```

But this doesn't work. List 2 just contains 1 item: the array of list1.
How should this be done?

答:
You can create list2 using the constructor of List(Of Object) type.

Dim list2 As List(Of Object) = New List(Of Object)(list1)
```

Body:
I'd like to initialize list2 (list of object) with each item of list 1 (list of string).

Dim list1 As New List(Of String) From {"a", "b", "c"}
Dim list2 As New List(Of Object) From {list1.ToArray()}

But this doesn't work. List 2 just contains 1 item: the array of list1.
How should this be done?


问:
Correct word-count of a LaTeX document
I'm currently searching for an application or a script that does a correct word count for a LaTeX document.

Up till now, I have only encountered scripts that only work on a single file but what I want is a script that can safely ignore LaTeX keywords and also traverse linked files...ie follow \include and \input links to produce a correct word-count for the whole document.

With vim, I currently use ggVGg CTRL+G but obviously that shows the count for the current file and does not ignore LaTeX keywords.

Does anyone know of any script (or application) that can do this job?

答:
For a very basic article class document I just look at the number of matches for a regex to find words. I use Sublime Text, so this method may not work for you in a different editor, but I just hit Ctrl+F (Command+F on Mac) and then, with regex enabled, search for

```<code>(^|\s+|"|((h|f|te){)|\()\w+
</code>```

which should ignore text declaring a floating environment or captions on figures as well as most kinds of basic equations and \usepackage declarations, while including quotations and parentheticals. It also counts footnotes and \emphasized text and will count \hyperref links as one word. It's not perfect, but it's typically accurate to within a few dozen words or so. You could refine it to work for you, but a script is probably a better solution, since LaTeX source code isn't a regular language. Just thought I'd throw this up here.

Title: Correct word-count of a LaTeX document

Body:
For a very basic article class document I just look at the number of matches for a regex to find words. I use Sublime Text, so this method may not work for you in a different editor, but I just hit Ctrl+F (Command+F on Mac) and then, with regex enabled, search for

(^|\s+|"|((h|f|te){)|\()\w+

which should ignore text declaring a floating environment or captions on figures as well as most kinds of basic equations and \usepackage declarations, while including quotations and parentheticals. It also counts footnotes and \emphasized text and will count \hyperref links as one word. It's not perfect, but it's typically accurate to within a few dozen words or so. You could refine it to work for you, but a script is probably a better solution, since LaTeX source code isn't a regular language. Just thought I'd throw this up here.


问:
Webview is stuck when loading new URL
When loading new URL with loadUrl() the titles changes and it seems to be loading the new webpage, but the view is stuck, I can se how the scrollbar moves and the zoom controllers work but the view is just frozen.
This only happens when a new url is loaded from a NFC Tag it's a very strange behaviour, other than that the webview works perfectly. I have to activities the MainActivity sends a broadcast to the WebViewActivity with the new URL but after that the view is stuck, I tried calling the method in the UIThread but it didn't work.

Here's the setup of the webView, also webclient and chrome client are declared in the last block of code.

```<code>public void setupWebView() {
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setDisplayZoomControls(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    webView.setWebViewClient(webViewClient);
    webView.setWebChromeClient(webChromeClient);
}
</code>```

Here's how I call the method loadUrl(), the broadCastReceiver takes care of the NFC intent.

```<code>    private WebViewClient webViewClient = new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        webView.loadUrl(url);
        return true;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        progressContainer.setVisibility(View.GONE);
    }
};

private WebChromeClient webChromeClient = new WebChromeClient() {
    @Override
    public void onReceivedTitle(WebView view, String title) {
        super.onReceivedTitle(view, title);
        titleView.setText(view.getTitle());
    }
};

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        loadNewUrl(intent);
    }
};

    public void loadNewUrl(Intent i) {
    String fullUrl = i.getExtras().getString(Constants.WEB_URL, "");

    progressContainer.setVisibility(View.VISIBLE);
    webView.post(new Runnable() {
        @Override
        public void run() {
            webView.loadUrl(fullUrl);
        }
    });
}
</code>```

答:
The issue was that I was overriding the onPause method and every time a NFC is detected it calls this method, causing the UI to pause totally and I also was calling the webview onPause. In my MainActivity I have multiple triggers like geolocation, push notifications and they worked fine, except for the NFC trigger.
So seems like when a NFC is detected on a Activity it calls onPause on all the other Activities.

```<code>    @Override
protected void onPause() {
    super.onPause();
    webView.onPause();
}
</code>```

Also in the MainActivity I was using the OnNewIntent() method to catch any intent

```<code>    @Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
         //Handles nfc and sends broadcast
    } else if (Constants.INTENT_PUSH_NOITIFICATION.equals(intent.getAction())) {
         //Handles notification and sends broadcast
}
</code>```

Title: Webview is stuck when loading new URL

Body:
When loading new URL with loadUrl() the titles changes and it seems to be loading the new webpage, but the view is stuck, I can se how the scrollbar moves and the zoom controllers work but the view is just frozen.
This only happens when a new url is loaded from a NFC Tag it's a very strange behaviour, other than that the webview works perfectly. I have to activities the MainActivity sends a broadcast to the WebViewActivity with the new URL but after that the view is stuck, I tried calling the method in the UIThread but it didn't work.

Here's the setup of the webView, also webclient and chrome client are declared in the last block of code.

public void setupWebView() {
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setDisplayZoomControls(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    webView.setWebViewClient(webViewClient);
    webView.setWebChromeClient(webChromeClient);
}

Here's how I call the method loadUrl(), the broadCastReceiver takes care of the NFC intent.

    private WebViewClient webViewClient = new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        webView.loadUrl(url);
        return true;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        progressContainer.setVisibility(View.GONE);
    }
};

private WebChromeClient webChromeClient = new WebChromeClient() {
    @Override
    public void onReceivedTitle(WebView view, String title) {
        super.onReceivedTitle(view, title);
        titleView.setText(view.getTitle());
    }
};

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        loadNewUrl(intent);
    }
};

    public void loadNewUrl(Intent i) {
    String fullUrl = i.getExtras().getString(Constants.WEB_URL, "");

    progressContainer.setVisibility(View.VISIBLE);
    webView.post(new Runnable() {
        @Override
        public void run() {
            webView.loadUrl(fullUrl);
        }
    });
}

Body:
The issue was that I was overriding the onPause method and every time a NFC is detected it calls this method, causing the UI to pause totally and I also was calling the webview onPause. In my MainActivity I have multiple triggers like geolocation, push notifications and they worked fine, except for the NFC trigger.
So seems like when a NFC is detected on a Activity it calls onPause on all the other Activities.

    @Override
protected void onPause() {
    super.onPause();
    webView.onPause();
}

Also in the MainActivity I was using the OnNewIntent() method to catch any intent

    @Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
         //Handles nfc and sends broadcast
    } else if (Constants.INTENT_PUSH_NOITIFICATION.equals(intent.getAction())) {
         //Handles notification and sends broadcast
}


问:
How do I make the buttons stay in their position after they have been clicked and opened a submenu
I have 3 buttons that when clicked they open a submenu, but whenever one is clicked, the other ones move in the page, how can i keep them inline whenever one was clicked?
I've tried changing the positions but then they all become change to be on top of each other, any help will be really appreciated so thank you in advance!

Here is my code:

HTML

```<code><button class="menu-trigger btn-1">1</button>
<ul class="menu">
  <li>test</li>
  <li>test</li>
  <li>test</li>
</ul>
<button class="menu-trigger btn-1">2</button>
<ul class="menu">
  <li>test</li>
  <li>test</li>
  <li>test</li>
</ul>
<button class="menu-trigger btn-1">3</button>
<ul class="menu">
  <li>test</li>
  <li>test</li>
  <li>test</li>
</ul>
</code>```

CSS

```<code>.menu-trigger{
    padding: 10px 25px;
    font-family: 'Roboto', sans-serif;
    font-weight: 500;
    background: transparent;
    outline: none;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    display: inline-block;
    color: lightgray;
}

.menu{
    display: none;
}

.menu.open{
    display:block;
}

.btn-1 {
    border: 2px solid yellow;
}

.btn-1:hover {
  background: #000;
  color: #fff;
}
</code>```

JS

```<code> $(function () {
      $(".menu-trigger").click(function () {
        $(this).next(".menu").toggleClass("open"); // Selects only the next one!
        $(this).html($(this).next(".menu").hasClass("open") ? menu-trigger : menu-trigger);
        return false;
      });
    });
</code>```

答:
You need to change your HTML markup and add some CSS rules to make work, so I did some changes to your code.

you need first to wrap each button with its menu ul, wrap them into ul > li HTML markup

you need to make each li that wrap each <button>
...
 </button> make display: inline-block; and position: relative;

make your ul.menu with position absolute.

Here you have your code already edited.

$(function () {
      $(".menu-trigger").click(function () {
        $(this).next(".menu").toggleClass("open"); // Selects only the next one!
        $(this).html($(this).next(".menu").hasClass("open") ? menu-trigger : menu-trigger);
        return false;
      });
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.menu-trigger{
    padding: 10px 25px;
    font-family: 'Roboto', sans-serif;
    font-weight: 500;
    background: transparent;
    outline: none;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    display: inline-block;
    color: lightgray;
}

.menu-container {
  list-style: none;
  margin: 0;
  padding: 0;
}

.menu-container > li {
  display: inline-block;
  position: relative;
}

.menu{
    position: absolute;
    left: 0;
    display: none;
}

.menu.open{
    display:block;
}

.btn-1 {
    border: 2px solid yellow;
}

.btn-1:hover {
  background: #000;
  color: #fff;
}</code>```

  <button class="menu-trigger btn-1">1</button>

test

test

test

  <button class="menu-trigger btn-1">2</button>

test

test

test

  <button class="menu-trigger btn-1">3</button>

test

test

test

```

I hope you find it helpful

Body:
I have 3 buttons that when clicked they open a submenu, but whenever one is clicked, the other ones move in the page, how can i keep them inline whenever one was clicked?
I've tried changing the positions but then they all become change to be on top of each other, any help will be really appreciated so thank you in advance!

Here is my code:

HTML

<button class="menu-trigger btn-1">1</button>

test

test

test

<button class="menu-trigger btn-1">2</button>

test

test

test

<button class="menu-trigger btn-1">3</button>

test

test

test

CSS

.menu-trigger{
    padding: 10px 25px;
    font-family: 'Roboto', sans-serif;
    font-weight: 500;
    background: transparent;
    outline: none;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    display: inline-block;
    color: lightgray;
}

.menu{
    display: none;
}

.menu.open{
    display:block;
}

.btn-1 {
    border: 2px solid yellow;
}

.btn-1:hover {
  background: #000;
  color: #fff;
}

JS

 $(function () {
      $(".menu-trigger").click(function () {
        $(this).next(".menu").toggleClass("open"); // Selects only the next one!
        $(this).html($(this).next(".menu").hasClass("open") ? menu-trigger : menu-trigger);
        return false;
      });
    });

Body:
You need to change your HTML markup and add some CSS rules to make work, so I did some changes to your code.

you need first to wrap each button with its menu ul, wrap them into ul > li HTML markup

you need to make each li that wrap each <button> <ul>...</ul> </button> make display: inline-block; and position: relative;

make your ul.menu with position absolute.

Here you have your code already edited.

$(function () {
      $(".menu-trigger").click(function () {
        $(this).next(".menu").toggleClass("open"); // Selects only the next one!
        $(this).html($(this).next(".menu").hasClass("open") ? menu-trigger : menu-trigger);
        return false;
      });
    });

.menu-trigger{
    padding: 10px 25px;
    font-family: 'Roboto', sans-serif;
    font-weight: 500;
    background: transparent;
    outline: none;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    display: inline-block;
    color: lightgray;
}

.menu-container {
  list-style: none;
  margin: 0;
  padding: 0;
}

.menu-container > li {
  display: inline-block;
  position: relative;
}

.menu{
    position: absolute;
    left: 0;
    display: none;
}

.menu.open{
    display:block;
}

.btn-1 {
    border: 2px solid yellow;
}

.btn-1:hover {
  background: #000;
  color: #fff;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul class='menu-container'>
<li>
  <button class="menu-trigger btn-1">1</button>
  <ul class="menu">
    <li>test</li>
    <li>test</li>
    <li>test</li>
  </ul>
</li>

<li>
  <button class="menu-trigger btn-1">2</button>
  <ul class="menu">
    <li>test</li>
    <li>test</li>
    <li>test</li>
  </ul>
</li>

<li>
  <button class="menu-trigger btn-1">3</button>
  <ul class="menu">
    <li>test</li>
    <li>test</li>
    <li>test</li>
  </ul>
</li>
</ul>

I hope you find it helpful


问:
Java - Factory, Instance
```<code>public class DataFactory {

    class SYNOP implements IDataSources {}
    class WRF implements IDataSources {}

    public abstract class Factory {
        public abstract IDataSources CreateModel();
    }

    public class SYNOPFactory extends Factory {

        @Override
        public IDataSources CreateModel() {
            return new SYNOP();
        }
    }

    public class WRFFactory extends Factory {

        @Override
        public IDataSources CreateModel() {
            return new WRF();
        }
    }

    public static void main(String[] args) {

        Factory factory = new WRFFactory();

    }
}
</code>```

And i got message error like this:

No enclosing instance of type DataFactory is accessible. Must qualify
  the allocation with an enclosing instance of type DataFactory (e.g.
  x.new A() where x is an instance of DataFactory).

What did i do wrong?

Regards

答:
Ok, so i am doing this like that:

File IDataSources.java

```<code>package pl.weatherPrediction.interfaces;

public interface IDataSources {
    //void getFiles(String url, String folder, String timeStamp);
}
</code>```

File Factory.java

```<code>package pl.weatherPrediction.factory;

import pl.weatherPrediction.interfaces.*;

public abstract class Factory {
    public abstract IDataSources CreateModel();
}
</code>```

File SYNOPFactory.java

```<code>package pl.weatherPrediction.factory;

import pl.weatherPrediction.factory.Factory;
import pl.weatherPrediction.interfaces.IDataSources;

public class SYNOPFactory extends Factory {

class SYNOP implements IDataSources {}

@Override
public IDataSources CreateModel() {
    return new SYNOP();
}
</code>```

}

File WRFFactory.java

```<code>package pl.weatherPrediction.factory;

import pl.weatherPrediction.interfaces.IDataSources;

public class WRFFactory extends Factory {

    class WRF implements IDataSources {}

    @Override
    public IDataSources CreateModel() {
        return new WRF();
    }
}
</code>```

File Main.java

```<code>package pl.weatherPrediction.App;

import pl.weatherPrediction.factory.*;

public class Main {

    public static void main(String[] args) {

        Factory factory = new SYNOPFactory();
        factory.CreateModel();

        factory = new WRFFactory();
        factory.CreateModel();

    }
}
</code>```

Is that correct @davidxxx?

Title: Java - Factory, Instance

Body:
public class DataFactory {

    class SYNOP implements IDataSources {}
    class WRF implements IDataSources {}

    public abstract class Factory {
        public abstract IDataSources CreateModel();
    }

    public class SYNOPFactory extends Factory {

        @Override
        public IDataSources CreateModel() {
            return new SYNOP();
        }
    }

    public class WRFFactory extends Factory {

        @Override
        public IDataSources CreateModel() {
            return new WRF();
        }
    }

    public static void main(String[] args) {

        Factory factory = new WRFFactory();

    }
}

And i got message error like this:

No enclosing instance of type DataFactory is accessible. Must qualify
  the allocation with an enclosing instance of type DataFactory (e.g.
  x.new A() where x is an instance of DataFactory).

What did i do wrong?

Regards

Body:
Ok, so i am doing this like that:

File IDataSources.java

package pl.weatherPrediction.interfaces;

public interface IDataSources {
    //void getFiles(String url, String folder, String timeStamp);
}

File Factory.java

package pl.weatherPrediction.factory;

import pl.weatherPrediction.interfaces.*;

public abstract class Factory {
    public abstract IDataSources CreateModel();
}

File SYNOPFactory.java

package pl.weatherPrediction.factory;

import pl.weatherPrediction.factory.Factory;
import pl.weatherPrediction.interfaces.IDataSources;

public class SYNOPFactory extends Factory {

class SYNOP implements IDataSources {}

@Override
public IDataSources CreateModel() {
    return new SYNOP();
}

}

File WRFFactory.java

package pl.weatherPrediction.factory;

import pl.weatherPrediction.interfaces.IDataSources;

public class WRFFactory extends Factory {

    class WRF implements IDataSources {}

    @Override
    public IDataSources CreateModel() {
        return new WRF();
    }
}

File Main.java

package pl.weatherPrediction.App;

import pl.weatherPrediction.factory.*;

public class Main {

    public static void main(String[] args) {

        Factory factory = new SYNOPFactory();
        factory.CreateModel();

        factory = new WRFFactory();
        factory.CreateModel();

    }
}

Is that correct @davidxxx?


问:
Get arguments and file name from specific path
I'm trying to extract argument and file name from path like below:

```<code>C:\Users\user\Desktop\foo.exe foo://action/bar
</code>```

I tried to use Path.GetFileName but since argument contains directory separators, it returns bar instead of foo.exe

Is there any way to get argument and file name?

答:
Use LastIndexOf to reverse-search the string for the backslash, then Substring to grab everything beyond that:

```<code>int i = path.LastIndexOf(@"\");
return (i > -1 && i < path.Length) ? path.Substring(i + 1) : string.Empty;
</code>```

If you need to separate the filename and argument, use IndexOf to look for the space or Split the result on the space character.

Body:
I'm trying to extract argument and file name from path like below:

C:\Users\user\Desktop\foo.exe foo://action/bar

I tried to use Path.GetFileName but since argument contains directory separators, it returns bar instead of foo.exe

Is there any way to get argument and file name?

Body:
Use LastIndexOf to reverse-search the string for the backslash, then Substring to grab everything beyond that:

int i = path.LastIndexOf(@"\");
return (i > -1 && i < path.Length) ? path.Substring(i + 1) : string.Empty;

If you need to separate the filename and argument, use IndexOf to look for the space or Split the result on the space character.


问:
Load Google Cloud Storage data into bigtable
Is there an easy way or example to load Google Cloud Storage data into bigtable?

I have lots of json files generated by pyspark and i wish to load data into bigtable.

But I can not find an easy way to do that!

I have tried the python code from google-cloud-python and it work fined, but it just read data line by line into bigtable which was strange for me.

Any help would be greatly appreciated.

答:
There is no simple tool to read data in Cloud Bigtable.  Here are some options:

Import the files using Dataflow.  This requires java development, and learning the Dataflow programming model.

Use Python (possibly with Pyspark) to read those json files, and write to Cloud Bigtable using a method called mutate_rows which write to Bigtable in bulk.

FYI, I work on the Cloud Bigtable team.  I'm a Java developer, so I opt for #1.  Our team has been working to improve our python experience.  The extended team recently added some reliability improvements to make sure that mutate_rows is resilient for large jobs.  We do not yet have any good examples of integrating with PySpark or Apache Beam's python SDK, but they are on our radar.


问:
ASP.NET Membership Web-Based Administration
Does anyone know if there's a way to manage users/roles in the asp.net membership database using a web-based interface you can access remotely?

I need one which doesn't require installation to the Default Website.

Thanks

答:
By the way the ASP.NETAdmin file are located on your machine here:

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ASP.NETWebAdminFiles

enjoy.

OwnerDisplayName: Shahin

LastEditorDisplayName: Shahin

OwnerDisplayName: Jason


问:
Preventing classes from being instantiated on the stack or as data member
I'm starting to use shared pointers in C++ (Visual Studio 2010) and run into the following problem.

I am writing a new module which defines an interface that tells the module how to behave in certain conditions.  It's something like this (artifical example just to illustrate my problem):

```<code>// Interface that should be implemented by user of the module
class RingAlert
   {
   public:
      virtual void ring() = 0;
   };

// Module that does something important
class Module
   {
   public:
      Module (RingAlert &ringAlert) : m_ringAlert(ringAlert) {}
      void dosomething();   // may call RingAlert::ring if something goes wrong.
   private:
      RingAlert &m_ringAlert;
   };
</code>```

To make it easy for the users of the module, and because the RingAlert could be passed to other modules as well, I am now making this a shared pointer, like this:

```<code>typedef std::shared_ptr<RingAlert> RingAlertPtr;

class Module
   {
   public:
      Module (RingAlertPtr ringAlert) : m_ringAlert(ringAlert) {}
      void dosomething();   // may call RingAlert::ring if something goes wrong.
   private:
      RingAlertPtr m_ringAlert;
   };
</code>```

Now users of the module may create a new RingAlert instance and simply pass it to the module, without keeping it somewhere and deleting it at the end of the application.

The problem starts if the application does something like this:

```<code>class MyRingAlert : public RingAlert
   {
   public:
      virtual void ring() {std::cout << "ring ring" << std::endl;}
   };

class Application
   {
   public:
   private:
      MyRingAlert m_myRingAlert;
   };

// later, somewhere in application code
Module m(RingAlertPtr(&m_myRingAlert));
</code>```

In this example, the application takes the address of a data member and puts it in a shared pointer.
Later in the application, the destructor of the Module will delete the shared pointer, which will decrement the reference count, and which will then delete the ring alert, which mustn't be deleted because it is a data member of the Application class.

I found a way of preventing the shared pointer from deleting the instance by doing this (using lambda's but also have a slightly cleaner solution using a function):

```<code>Module m(RingAlertPtr(&m_myRingAlert,[](void *){});
</code>```

Although this solves my problem, I'm not completely happy with it because it will still give a problem if the Application class is destructed before the Module class.

The only good solution seems to be to force the rest of the application to new the instance of RingAlert (or actually the class that implements RingAlert).

Can this be done?
Is there a way to prevent code from instantiating subclasses of a base class on the stack or as datamember?
In other words: can we force subclasses of a base class being newed if they want to be instantiated?

答: What about to create private type-depended overrides operator new and delete for class RingAlert

Body:
I'm starting to use shared pointers in C++ (Visual Studio 2010) and run into the following problem.

I am writing a new module which defines an interface that tells the module how to behave in certain conditions.  It's something like this (artifical example just to illustrate my problem):

// Interface that should be implemented by user of the module
class RingAlert
   {
   public:
      virtual void ring() = 0;
   };

// Module that does something important
class Module
   {
   public:
      Module (RingAlert &ringAlert) : m_ringAlert(ringAlert) {}
      void dosomething();   // may call RingAlert::ring if something goes wrong.
   private:
      RingAlert &m_ringAlert;
   };

To make it easy for the users of the module, and because the RingAlert could be passed to other modules as well, I am now making this a shared pointer, like this:

typedef std::shared_ptr<RingAlert> RingAlertPtr;

class Module
   {
   public:
      Module (RingAlertPtr ringAlert) : m_ringAlert(ringAlert) {}
      void dosomething();   // may call RingAlert::ring if something goes wrong.
   private:
      RingAlertPtr m_ringAlert;
   };

Now users of the module may create a new RingAlert instance and simply pass it to the module, without keeping it somewhere and deleting it at the end of the application.

The problem starts if the application does something like this:

class MyRingAlert : public RingAlert
   {
   public:
      virtual void ring() {std::cout << "ring ring" << std::endl;}
   };

class Application
   {
   public:
   private:
      MyRingAlert m_myRingAlert;
   };

// later, somewhere in application code
Module m(RingAlertPtr(&m_myRingAlert));

In this example, the application takes the address of a data member and puts it in a shared pointer.
Later in the application, the destructor of the Module will delete the shared pointer, which will decrement the reference count, and which will then delete the ring alert, which mustn't be deleted because it is a data member of the Application class.

I found a way of preventing the shared pointer from deleting the instance by doing this (using lambda's but also have a slightly cleaner solution using a function):

Module m(RingAlertPtr(&m_myRingAlert,[](void *){});

Although this solves my problem, I'm not completely happy with it because it will still give a problem if the Application class is destructed before the Module class.

The only good solution seems to be to force the rest of the application to new the instance of RingAlert (or actually the class that implements RingAlert).

Can this be done?
Is there a way to prevent code from instantiating subclasses of a base class on the stack or as datamember?
In other words: can we force subclasses of a base class being newed if they want to be instantiated?


问:
Wrapping the script line in travis.yml
I have this .travis.yml file:

```<code>language: node_js
node_js:
  - '9'
  - '8'
  - '7'
  - '6'
env:
  - CXX=g++-4.8
addons:
  apt:
    sources:
      - ubuntu-toolchain-r-test
    packages:
      - g++-4.8

before_install: 'if [[ `npm -v` != 4* ]]; then npm i -g npm@4; fi'

install:
  - npm install --silent --no-optional > /dev/null 2>&1

script: 'rm -rf node_modules && npm cache clean && npm install istanbul --silent > /dev/null 2>&1 && \
npm link -f --silent > /dev/null 2>&1 && npm link suman -f --silent  > /dev/null 2>&1 && \
suman test/src/dev/node/injection.test.js'
</code>```

I am guessing that the script line is improperly formatted. I get this error on Travis:

```<code>The command "rm -rf node_modules && npm cache clean && npm install istanbul --silent > /dev/null 2>&1 && \ npm link -f --silent > /dev/null 2>&1 && npm link suman -f --silent  > /dev/null 2>&1 && \ suman test/src/dev/node/injection.test.js" exited with 127.
</code>```

Does anyone know that script command is formatted properly? I cannot figured it out.

答:
Looks like the .travis.yml file in the OP was wrong ( I don't know exactly why), because when I changed it to:

```<code>language: node_js
node_js:
  - '9'
  - '8'
  - '7'
  - '6'
env:
  - CXX=g++-4.8
addons:
  apt:
    sources:
      - ubuntu-toolchain-r-test
    packages:
      - g++-4.8

before_install: 'if [[ `npm -v` != 4* ]]; then npm i -g npm@4; fi'
install:
  - 'npm install --silent --no-optional > /dev/null 2>&1'
script: 'rm -rf node_modules && npm cache clean && npm install istanbul --silent > /dev/null 2>&1 && npm link -f --silent > /dev/null 2>&1 && npm link suman -f --silent  > /dev/null 2>&1 && suman test/src/dev/node/injection.test.js'
after_script: 'npm install -g coveralls && cat coverage/lcov.info | coveralls'
notifications:
  email: false
</code>```

Now it's working again.

Title: Wrapping the script line in travis.yml

Body:
I have this .travis.yml file:

language: node_js
node_js:
  - '9'
  - '8'
  - '7'
  - '6'
env:
  - CXX=g++-4.8
addons:
  apt:
    sources:
      - ubuntu-toolchain-r-test
    packages:
      - g++-4.8

before_install: 'if [[ `npm -v` != 4* ]]; then npm i -g npm@4; fi'

install:
  - npm install --silent --no-optional > /dev/null 2>&1

script: 'rm -rf node_modules && npm cache clean && npm install istanbul --silent > /dev/null 2>&1 && \
npm link -f --silent > /dev/null 2>&1 && npm link suman -f --silent  > /dev/null 2>&1 && \
suman test/src/dev/node/injection.test.js'

I am guessing that the script line is improperly formatted. I get this error on Travis:

The command "rm -rf node_modules && npm cache clean && npm install istanbul --silent > /dev/null 2>&1 && \ npm link -f --silent > /dev/null 2>&1 && npm link suman -f --silent  > /dev/null 2>&1 && \ suman test/src/dev/node/injection.test.js" exited with 127.

Does anyone know that script command is formatted properly? I cannot figured it out.

Body:
Looks like the .travis.yml file in the OP was wrong ( I don't know exactly why), because when I changed it to:

language: node_js
node_js:
  - '9'
  - '8'
  - '7'
  - '6'
env:
  - CXX=g++-4.8
addons:
  apt:
    sources:
      - ubuntu-toolchain-r-test
    packages:
      - g++-4.8

before_install: 'if [[ `npm -v` != 4* ]]; then npm i -g npm@4; fi'
install:
  - 'npm install --silent --no-optional > /dev/null 2>&1'
script: 'rm -rf node_modules && npm cache clean && npm install istanbul --silent > /dev/null 2>&1 && npm link -f --silent > /dev/null 2>&1 && npm link suman -f --silent  > /dev/null 2>&1 && suman test/src/dev/node/injection.test.js'
after_script: 'npm install -g coveralls && cat coverage/lcov.info | coveralls'
notifications:
  email: false

Now it's working again.


问:
How to remove index.php from the URL in PHP CodeIgniter App hosted on Azure
I'm trying to run a PHP codeigniter website on Azure.

But when I set

```<code>$config['index_page'] = '';
</code>```

of my config.php it shows me an error saying "The resource you are looking for has been removed, had its name changed, or is temporarily unavailable"

So once I set that to

```<code>$config['index_page'] = 'index.php';
</code>```

I could load my website.

Now in my urls look like this

```<code>http://mysamplesite.azurewebsites.net/helloworld/index.php/Demo
</code>```

But I want that to be like this,

```<code>http://mysamplesite.azurewebsites.net/helloworld/Demo
</code>```

But every time when I remove that index.php part I got the above mentioned error.

I tried to change my htaccess file, but keep getting the error, this is my htaccess file,

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</code>```

Also I had to use site_url() instead of base_url.

So how can I drop index.php from the url?

答:
put this in your .htaccess file. it should works </p>

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
#CI_FOLDER is the Location of your CI files.

#Removes access to the system folder by users.
#Additionally this will allow you to create a System.php controller,
#previously this would not have been possible.
#'system' can be replaced if you have renamed your system folder.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]

#When your application folder isn't in the system folder
#This snippet prevents user access to the application folder
#Submitted by: Fabdrol
#Rename 'application' to your applications folder name.
RewriteCond %{REQUEST_URI} ^application.*
RewriteRule ^(.*)$ /index.php?/$1 [L]

#Checks to see if the user is attempting to access a valid file,
#such as an image or css document, if this isn't true it sends the
#request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

</IfModule>

<IfModule !mod_rewrite.c>
# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
# Submitted by: ElliotHaughin

ErrorDocument 404 /index.php
</IfModule>
</code>```

Body:
I'm trying to run a PHP codeigniter website on Azure.

But when I set

$config['index_page'] = '';

of my config.php it shows me an error saying "The resource you are looking for has been removed, had its name changed, or is temporarily unavailable"

So once I set that to

$config['index_page'] = 'index.php';

I could load my website.

Now in my urls look like this

http://mysamplesite.azurewebsites.net/helloworld/index.php/Demo

But I want that to be like this,

http://mysamplesite.azurewebsites.net/helloworld/Demo

But every time when I remove that index.php part I got the above mentioned error.

I tried to change my htaccess file, but keep getting the error, this is my htaccess file,

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

Also I had to use site_url() instead of base_url.

So how can I drop index.php from the url?

Body:
put this in your .htaccess file. it should works

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
#CI_FOLDER is the Location of your CI files.

#Removes access to the system folder by users.
#Additionally this will allow you to create a System.php controller,
#previously this would not have been possible.
#'system' can be replaced if you have renamed your system folder.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]

#When your application folder isn't in the system folder
#This snippet prevents user access to the application folder
#Submitted by: Fabdrol
#Rename 'application' to your applications folder name.
RewriteCond %{REQUEST_URI} ^application.*
RewriteRule ^(.*)$ /index.php?/$1 [L]

#Checks to see if the user is attempting to access a valid file,
#such as an image or css document, if this isn't true it sends the
#request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

</IfModule>

<IfModule !mod_rewrite.c>
# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
# Submitted by: ElliotHaughin

ErrorDocument 404 /index.php
</IfModule>


问:
Sorting multiple lists using position of data from first list
I have a dynamically-populated list that when it's built, the data is passed into creating a stacked bar chart. With the data in the list sorted, so also the chart.

```<code>list: [
    ['Completion Date', 'New', 'NW-New', 'NW-Info', 'NW-Dec', 'NS-Modify', 'SN-Mod', 'VW-NwClter', 'NW-Del', 'VW-ModClter'],
    ['10/15/2017', 1,   0, 0,   0, 0, 0, 0,  0, 0],
    ['10/16/2017', 5,   8, 3,   2, 1, 0, 0,  0, 0],
    ['10/17/2017', 1,   9, 0,  29, 3, 3, 0,  0, 0],
    ['10/18/2017', 4,  44, 0,  11, 1, 0, 2,  0, 0],
    ['10/19/2017', 4,  39, 0,   0, 1, 0, 0,  1, 0],
    ['10/20/2017', 3,   2, 0,   0, 0, 1, 0,  0, 6],
    ['10/21/2017', 0,   0, 0,   0, 0, 0, 2,  0, 0],
    ['10/22/2017', 0,   0, 0,   0, 0, 0, 0,  0, 0],
    ['10/23/2017', 1,  67, 0,  85, 3, 2, 0,  1, 0],
    ['10/24/2017', 2,  25, 1,   4, 5, 0, 0,  1, 1],
    ['10/25/2017', 4,  65, 0,  11, 5, 0, 0, 11, 1],
    ['10/26/2017', 7,  40, 0,   0, 6, 0, 0,  2, 0],
    ['10/27/2017', 2,  37, 0, 115, 2, 0, 0,  0, 0],
    ['10/28/2017', 2,   0, 0,   0, 0, 0, 0,  0, 0],
    ['10/29/2017', 0,   0, 0,   0, 0, 0, 0,  0, 0],
    ['10/30/2017', 5,  53, 0,   0, 3, 0, 0,  1, 0],
    ['10/31/2017', 1,  30, 0,  19, 3, 0, 0,  0, 0],
    ['11/01/2017', 6, 106, 0,   2, 1, 0, 0,  1, 1],
    ['11/02/2017', 5,  74, 0,  10, 0, 0, 0,  9, 0]
]
</code>```

The data in the first list matches that in the other lists, completion date goes with the date and the strings in the first list goes with the other data respectively.

I wanted a situation where if the string on the first list is sorted alphabetically, then the data matching its index position on the other list changes to the new position of the sorted string. Note the first data string completion date and the respective dates remain same.

I did some research and saw some examples but they were relative to two lists. Like an example of sorting using zip. Any ideas will be welcomed.

Body:
I have a dynamically-populated list that when it's built, the data is passed into creating a stacked bar chart. With the data in the list sorted, so also the chart.

list: [
    ['Completion Date', 'New', 'NW-New', 'NW-Info', 'NW-Dec', 'NS-Modify', 'SN-Mod', 'VW-NwClter', 'NW-Del', 'VW-ModClter'],
    ['10/15/2017', 1,   0, 0,   0, 0, 0, 0,  0, 0],
    ['10/16/2017', 5,   8, 3,   2, 1, 0, 0,  0, 0],
    ['10/17/2017', 1,   9, 0,  29, 3, 3, 0,  0, 0],
    ['10/18/2017', 4,  44, 0,  11, 1, 0, 2,  0, 0],
    ['10/19/2017', 4,  39, 0,   0, 1, 0, 0,  1, 0],
    ['10/20/2017', 3,   2, 0,   0, 0, 1, 0,  0, 6],
    ['10/21/2017', 0,   0, 0,   0, 0, 0, 2,  0, 0],
    ['10/22/2017', 0,   0, 0,   0, 0, 0, 0,  0, 0],
    ['10/23/2017', 1,  67, 0,  85, 3, 2, 0,  1, 0],
    ['10/24/2017', 2,  25, 1,   4, 5, 0, 0,  1, 1],
    ['10/25/2017', 4,  65, 0,  11, 5, 0, 0, 11, 1],
    ['10/26/2017', 7,  40, 0,   0, 6, 0, 0,  2, 0],
    ['10/27/2017', 2,  37, 0, 115, 2, 0, 0,  0, 0],
    ['10/28/2017', 2,   0, 0,   0, 0, 0, 0,  0, 0],
    ['10/29/2017', 0,   0, 0,   0, 0, 0, 0,  0, 0],
    ['10/30/2017', 5,  53, 0,   0, 3, 0, 0,  1, 0],
    ['10/31/2017', 1,  30, 0,  19, 3, 0, 0,  0, 0],
    ['11/01/2017', 6, 106, 0,   2, 1, 0, 0,  1, 1],
    ['11/02/2017', 5,  74, 0,  10, 0, 0, 0,  9, 0]
]

The data in the first list matches that in the other lists, completion date goes with the date and the strings in the first list goes with the other data respectively.

I wanted a situation where if the string on the first list is sorted alphabetically, then the data matching its index position on the other list changes to the new position of the sorted string. Note the first data string completion date and the respective dates remain same.

I did some research and saw some examples but they were relative to two lists. Like an example of sorting using zip. Any ideas will be welcomed.

Body:
As you asked:

if the string on the first list is sorted alphabetically, then the
  data matching its index position on the other list changes to the new
  position of the sorted string.

You can take help and hint from this solution and modify it according to your need:

list1=[
    ['Completion Date', 'New', 'NW-New', 'NW-Info', 'NW-Dec', 'NS-Modify', 'SN-Mod', 'VW-NwClter', 'NW-Del', 'VW-ModClter'],
    ['10/15/2017', 'second', 'third', 'forth',   'fifth', 'sixth', 'seven', 'eight',  'nine', 'ten'],
    ['10/16/2017', 5,   8, 3,   2, 1, 0, 0,  0, 0],
    ['10/17/2017', 1,   9, 0,  29, 3, 3, 0,  0, 0],
    ['10/18/2017', 4,  44, 0,  11, 1, 0, 2,  0, 0],
    ['10/19/2017', 4,  39, 0,   0, 1, 0, 0,  1, 0],
    ['10/20/2017', 3,   2, 0,   0, 0, 1, 0,  0, 6],
    ['10/21/2017', 0,   0, 0,   0, 0, 0, 2,  0, 0],
    ['10/22/2017', 0,   0, 0,   0, 0, 0, 0,  0, 0],
    ['10/23/2017', 1,  67, 0,  85, 3, 2, 0,  1, 0],
    ['10/24/2017', 2,  25, 1,   4, 5, 0, 0,  1, 1],
    ['10/25/2017', 4,  65, 0,  11, 5, 0, 0, 11, 1],
    ['10/26/2017', 7,  40, 0,   0, 6, 0, 0,  2, 0],
    ['10/27/2017', 2,  37, 0, 115, 2, 0, 0,  0, 0],
    ['10/28/2017', 2,   0, 0,   0, 0, 0, 0,  0, 0],
    ['10/29/2017', 0,   0, 0,   0, 0, 0, 0,  0, 0],
    ['10/30/2017', 5,  53, 0,   0, 3, 0, 0,  1, 0],
    ['10/31/2017', 1,  30, 0,  19, 3, 0, 0,  0, 0],
    ['11/01/2017', 6, 106, 0,   2, 1, 0, 0,  1, 1],
    ['11/02/2017', 5,  74, 0,  10, 0, 0, 0,  9, 0]
]

track={index:value for index,value in enumerate(list1[0])}  #create a dict for keep tracking of old index

sorted_list=sorted(list1[0])  #sorting the first sub_list which have headers

for item in list1[1:]:
    right = [0] * len(item)
    for index,value in enumerate(item):
        if index in track:
            index_no=sorted_list.index(track.get(index))     #sorting other than first sub_list according to sorted first sub_list
            right[index_no]=value

    print(right)

output:

['10/15/2017', 'sixth', 'fifth', 'nine', 'forth', 'third', 'second', 'seven', 'ten', 'eight']
['10/16/2017', 1, 2, 0, 3, 8, 5, 0, 0, 0]
['10/17/2017', 3, 29, 0, 0, 9, 1, 3, 0, 0]
['10/18/2017', 1, 11, 0, 0, 44, 4, 0, 0, 2]
['10/19/2017', 1, 0, 1, 0, 39, 4, 0, 0, 0]
['10/20/2017', 0, 0, 0, 0, 2, 3, 1, 6, 0]
['10/21/2017', 0, 0, 0, 0, 0, 0, 0, 0, 2]
['10/22/2017', 0, 0, 0, 0, 0, 0, 0, 0, 0]
['10/23/2017', 3, 85, 1, 0, 67, 1, 2, 0, 0]
['10/24/2017', 5, 4, 1, 1, 25, 2, 0, 1, 0]
['10/25/2017', 5, 11, 11, 0, 65, 4, 0, 1, 0]
['10/26/2017', 6, 0, 2, 0, 40, 7, 0, 0, 0]
['10/27/2017', 2, 115, 0, 0, 37, 2, 0, 0, 0]
['10/28/2017', 0, 0, 0, 0, 0, 2, 0, 0, 0]
['10/29/2017', 0, 0, 0, 0, 0, 0, 0, 0, 0]
['10/30/2017', 3, 0, 1, 0, 53, 5, 0, 0, 0]
['10/31/2017', 3, 19, 0, 0, 30, 1, 0, 0, 0]
['11/01/2017', 1, 2, 1, 0, 106, 6, 0, 1, 0]
['11/02/2017', 0, 10, 9, 0, 74, 5, 0, 0, 0]


问:
Merging JVM and the code into a single file
I would like to merge Java Virtual Machine and my .java code (or compiled .class files) into a single executable binary. How can I do this?</p>

答: I really doubt you are allowed to do that from the licensing prospective. You are going to let end user use software without passing them through accepting JVM license.</p>