问:
dynamic batch size with tf.data or tf.contrib.datta
I can use a placeholder as the batch_size with tf.train.batch_join() (Which is queue based,) so I can dynamically change the batch size in the training loop.

But when I use placeholder (or a nontrainable variable) as the batch_size for tf.data.Dataset.batch(), I got this error,

```<code>ValueError: Cannot capture a placeholder (name:Placeholder, type:Placeholder) by value.
</code>```

The whole error stack trace is very long. I traced the error to v1.4 tensorflow/python/data/ops/dataset_ops.py:108 in make_one_shot_iterator()

```<code>@function.Defun(capture_by_value=True)
</code>```

Full stack trace attached. I was trying the official tf resnet model.

Thanks!!

```<code>Traceback (most recent call last):
  File "imagenet_main.py", line 281, in <module>
    tf.app.run(argv=[sys.argv[0]] + unparsed)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/platform/app.py", line 48, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "imagenet_main.py", line 270, in main
    hooks=[logging_hook])
  File "/usr/lib/python2.7/site-packages/tensorflow/python/estimator/estimator.py", line 302, in train
    loss = self._train_model(input_fn, hooks, saving_listeners)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/estimator/estimator.py", line 708, in _train_model
    input_fn, model_fn_lib.ModeKeys.TRAIN)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/estimator/estimator.py", line 577, in _get_features_and_labels_from_input_fn
    result = self._call_input_fn(input_fn, mode)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/estimator/estimator.py", line 663, in _call_input_fn
    return input_fn(**kwargs)
  File "imagenet_main.py", line 269, in <lambda>
    True, FLAGS.data_dir, worker_batch_size, FLAGS.epochs_per_eval),
  File "imagenet_main.py", line 157, in input_fn
    iterator = dataset.make_one_shot_iterator()
  File "/usr/lib/python2.7/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 113, in make_one_shot_iterator
    _make_dataset.add_to_graph(ops.get_default_graph())
  File "/usr/lib/python2.7/site-packages/tensorflow/python/framework/function.py", line 486, in add_to_graph
    self._create_definition_if_needed()
  File "/usr/lib/python2.7/site-packages/tensorflow/python/framework/function.py", line 321, in _create_definition_if_needed
    self._create_definition_if_needed_impl()
  File "/usr/lib/python2.7/site-packages/tensorflow/python/framework/function.py", line 338, in _create_definition_if_needed_impl
    outputs = self._func(*inputs)

  File "/usr/lib/python2.7/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 111, in _make_dataset
    return self._as_variant_tensor()  # pylint: disable=protected-access
  File "/usr/lib/python2.7/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 1225, in _as_variant_tensor
    self._input_dataset._as_variant_tensor(),  # pylint: disable=protected-access
  File "/usr/lib/python2.7/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 1036, in _as_variant_tensor
    self._input_dataset._as_variant_tensor(),  # pylint: disable=protected-access
  File "/usr/lib/python2.7/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 1147, in _as_variant_tensor
    self._input_dataset._as_variant_tensor(),  # pylint: disable=protected-access
  File "/usr/lib/python2.7/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 1598, in _as_variant_tensor
    output_types=nest.flatten(self.output_types))
  File "/usr/lib/python2.7/site-packages/tensorflow/python/ops/gen_dataset_ops.py", line 1062, in prefetch_dataset
    output_shapes=output_shapes, name=name)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 787, in _apply_op_helper
    op_def=op_def)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/framework/function.py", line 691, in create_op
    inputs[i] = self._add_tensor_and_parents(x)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/framework/function.py", line 706, in _add_tensor_and_parents
    op = self._add_op_and_parents(tensor.op)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/framework/function.py", line 718, in _add_op_and_parents
    "by value." % (op.name, op.type))
ValueError: Cannot capture a placeholder (name:Placeholder, type:Placeholder) by value.
</code>```

答: seems like you have to use initializable iterator, not one_shot</p>

Body:
I can use a placeholder as the batch_size with tf.train.batch_join() (Which is queue based,) so I can dynamically change the batch size in the training loop.

But when I use placeholder (or a nontrainable variable) as the batch_size for tf.data.Dataset.batch(), I got this error,

ValueError: Cannot capture a placeholder (name:Placeholder, type:Placeholder) by value.

The whole error stack trace is very long. I traced the error to v1.4 tensorflow/python/data/ops/dataset_ops.py:108 in make_one_shot_iterator()

@function.Defun(capture_by_value=True)

Full stack trace attached. I was trying the official tf resnet model.

Thanks!!

Traceback (most recent call last):
  File "imagenet_main.py", line 281, in <module>
    tf.app.run(argv=[sys.argv[0]] + unparsed)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/platform/app.py", line 48, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "imagenet_main.py", line 270, in main
    hooks=[logging_hook])
  File "/usr/lib/python2.7/site-packages/tensorflow/python/estimator/estimator.py", line 302, in train
    loss = self._train_model(input_fn, hooks, saving_listeners)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/estimator/estimator.py", line 708, in _train_model
    input_fn, model_fn_lib.ModeKeys.TRAIN)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/estimator/estimator.py", line 577, in _get_features_and_labels_from_input_fn
    result = self._call_input_fn(input_fn, mode)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/estimator/estimator.py", line 663, in _call_input_fn
    return input_fn(**kwargs)
  File "imagenet_main.py", line 269, in <lambda>
    True, FLAGS.data_dir, worker_batch_size, FLAGS.epochs_per_eval),
  File "imagenet_main.py", line 157, in input_fn
    iterator = dataset.make_one_shot_iterator()
  File "/usr/lib/python2.7/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 113, in make_one_shot_iterator
    _make_dataset.add_to_graph(ops.get_default_graph())
  File "/usr/lib/python2.7/site-packages/tensorflow/python/framework/function.py", line 486, in add_to_graph
    self._create_definition_if_needed()
  File "/usr/lib/python2.7/site-packages/tensorflow/python/framework/function.py", line 321, in _create_definition_if_needed
    self._create_definition_if_needed_impl()
  File "/usr/lib/python2.7/site-packages/tensorflow/python/framework/function.py", line 338, in _create_definition_if_needed_impl
    outputs = self._func(*inputs)

  File "/usr/lib/python2.7/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 111, in _make_dataset
    return self._as_variant_tensor()  # pylint: disable=protected-access
  File "/usr/lib/python2.7/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 1225, in _as_variant_tensor
    self._input_dataset._as_variant_tensor(),  # pylint: disable=protected-access
  File "/usr/lib/python2.7/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 1036, in _as_variant_tensor
    self._input_dataset._as_variant_tensor(),  # pylint: disable=protected-access
  File "/usr/lib/python2.7/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 1147, in _as_variant_tensor
    self._input_dataset._as_variant_tensor(),  # pylint: disable=protected-access
  File "/usr/lib/python2.7/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 1598, in _as_variant_tensor
    output_types=nest.flatten(self.output_types))
  File "/usr/lib/python2.7/site-packages/tensorflow/python/ops/gen_dataset_ops.py", line 1062, in prefetch_dataset
    output_shapes=output_shapes, name=name)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 787, in _apply_op_helper
    op_def=op_def)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/framework/function.py", line 691, in create_op
    inputs[i] = self._add_tensor_and_parents(x)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/framework/function.py", line 706, in _add_tensor_and_parents
    op = self._add_op_and_parents(tensor.op)
  File "/usr/lib/python2.7/site-packages/tensorflow/python/framework/function.py", line 718, in _add_op_and_parents
    "by value." % (op.name, op.type))
ValueError: Cannot capture a placeholder (name:Placeholder, type:Placeholder) by value.


来源: stackexchange

问:
Matplotlib/Pandas to generate specific graph from Python dict/JSON
I'm looking to make a specific graph layout from a specific format of Python data, but where the data may be text, string, or another Python object.

I can do this with XlsxWriter (see below), but the data overloads it (14 million lines...no joke. DNA data). Is it possible/how can I do this with Matplotlib or PAndas (or more stable with large data)?

DETAILS:
It has to be able to do it on the fly, and make visual formatting decisions based on whether the data is "the same" (regardless of numerically, text or another Python object).

The coloring in the cells is based on whether the items within {1:"A", 2:"A"}are equivalent (not the same object). Green for True, red for False. For example: "A" == "A" (as in the preceding sentences), or (10/5) == (20/10), or ["A", 1, <test object at 0x1052c9b70>] == ["A", 1, <test object at 0x1052c9b70>] would all be green.

The text that appears in the cells is just the __str__ representation of the object.

EXAMPLE ...

```<code>{
    1000:{
          "Sample1":{1:"A", 2:"A"},
          "Sample2":{1:"A", 2:"A"},
          "Sample3":{1:"A", 2:"A"},
          },

    1001:{
          "Sample1":{1:"A", 2:"A"},
          "Sample2":{1:"A", 2:"A"},
          "Sample3":{1:"A", 2:"A"}
          },

    1002:{
          "Sample1":{1:"C", 2:"A"},
          "Sample2":{1:"A", 2:"A"},
          "Sample3":{1:"A", 2:"A"}
          },

    (...)

    9999:{
          "Sample1":{1:"A", 2:"T"},
          "Sample2":{1:"A", 2:"A"},
          "Sample3":{1:"A", 2:"G"}
          },
}
</code>```

答:
Using pandas and styled tables in a Jupyter notebook:

```<code>json = {
    1000:{
          "Sample1":{1:"A", 2:"A"},
          "Sample2":{1:"A", 2:"A"},
          "Sample3":{1:"A", 2:"A"},
          },
    1001:{
          "Sample1":{1:"A", 2:"A"},
          "Sample2":{1:"A", 2:"A"},
          "Sample3":{1:"A", 2:"A"}
          },
    1002:{
          "Sample1":{1:"C", 2:"A"},
          "Sample2":{1:"A", 2:"A"},
          "Sample3":{1:"A", 2:"A"}
          },
    9999:{
          "Sample1":{1:"A", 2:"T"},
          "Sample2":{1:"A", 2:"A"},
          "Sample3":{1:"A", 2:"G"}
          },
}

import pandas as pd
df = pd.DataFrame(json).transpose()
df0 = df.applymap(lambda x: "{}/{}".format(x[1].__repr__(),x[2].__repr__()))
df0

df1 = df.applymap(lambda x: x[1])
df2 = df.applymap(lambda x: x[2])

booldf = df1 == df2
c = lambda x : 'background-color: {}'.format(x)
formatdf = booldf.applymap(lambda x: c("limegreen") if x else c("crimson"))

df0.style.apply(lambda x: formatdf, axis=None)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm looking to make a specific graph layout from a specific format of Python data, but where the data may be text, string, or another Python object.

I can do this with XlsxWriter (see below), but the data overloads it (14 million lines...no joke. DNA data). Is it possible/how can I do this with Matplotlib or PAndas (or more stable with large data)?

DETAILS:
It has to be able to do it on the fly, and make visual formatting decisions based on whether the data is "the same" (regardless of numerically, text or another Python object).

The coloring in the cells is based on whether the items within {1:"A", 2:"A"}are equivalent (not the same object). Green for True, red for False. For example: "A" == "A" (as in the preceding sentences), or (10/5) == (20/10), or ["A", 1, <test object at 0x1052c9b70>] == ["A", 1, <test object at 0x1052c9b70>] would all be green.

The text that appears in the cells is just the __str__ representation of the object.

EXAMPLE ...

{
    1000:{
          "Sample1":{1:"A", 2:"A"},
          "Sample2":{1:"A", 2:"A"},
          "Sample3":{1:"A", 2:"A"},
          },

    1001:{
          "Sample1":{1:"A", 2:"A"},
          "Sample2":{1:"A", 2:"A"},
          "Sample3":{1:"A", 2:"A"}
          },

    1002:{
          "Sample1":{1:"C", 2:"A"},
          "Sample2":{1:"A", 2:"A"},
          "Sample3":{1:"A", 2:"A"}
          },

    (...)

    9999:{
          "Sample1":{1:"A", 2:"T"},
          "Sample2":{1:"A", 2:"A"},
          "Sample3":{1:"A", 2:"G"}
          },
}

Body:
Using pandas and styled tables in a Jupyter notebook:

json = {
    1000:{
          "Sample1":{1:"A", 2:"A"},
          "Sample2":{1:"A", 2:"A"},
          "Sample3":{1:"A", 2:"A"},
          },
    1001:{
          "Sample1":{1:"A", 2:"A"},
          "Sample2":{1:"A", 2:"A"},
          "Sample3":{1:"A", 2:"A"}
          },
    1002:{
          "Sample1":{1:"C", 2:"A"},
          "Sample2":{1:"A", 2:"A"},
          "Sample3":{1:"A", 2:"A"}
          },
    9999:{
          "Sample1":{1:"A", 2:"T"},
          "Sample2":{1:"A", 2:"A"},
          "Sample3":{1:"A", 2:"G"}
          },
}

import pandas as pd
df = pd.DataFrame(json).transpose()
df0 = df.applymap(lambda x: "{}/{}".format(x[1].__repr__(),x[2].__repr__()))
df0

df1 = df.applymap(lambda x: x[1])
df2 = df.applymap(lambda x: x[2])

booldf = df1 == df2
c = lambda x : 'background-color: {}'.format(x)
formatdf = booldf.applymap(lambda x: c("limegreen") if x else c("crimson"))

df0.style.apply(lambda x: formatdf, axis=None)


问:
how can i create a button in windows form which when clicked asks for two values to be entered

I have to develop an application that counts number of sheep in an image

I have to add a button to a form which when clicked asks for two values to be entered by the user

I have to design a form that loads image from pc and count number of sheep in an image. The coding should be done in C#

答:
You can do this by adding a second form to your project:

from here you can add a button on your main from, in this example Form1.

On this button a click event:

and in this method you can use the below to call your second form:

```<code>    private void CallForm_Click(object sender, EventArgs e)
    {
        Form2 secondForm = new Form2();
        secondForm.ShowDialog();
    }
</code>```

And for what you are wanting you may want to add two text box's to your second from where the user can add the required value.

Body:
You can do this by adding a second form to your project:

from here you can add a button on your main from, in this example Form1.

On this button a click event:

and in this method you can use the below to call your second form:

    private void CallForm_Click(object sender, EventArgs e)
    {
        Form2 secondForm = new Form2();
        secondForm.ShowDialog();
    }

And for what you are wanting you may want to add two text box's to your second from where the user can add the required value.


问:
JavaFX Rectangle stops ComboBox displaying drop-down
I have a requirement to display a Rectangle with an InnerShadow effect as the background of my JavaFX nodes. Each node needs to be resizable. I am implementing this with an abstract base class with a Region which has the Rectangle with an InnerShadow as one of its children and a Region provided by the concrete implementation of this class as its other child.

The problem occurs when I add one or more ComboBoxes to the child region. Clicking on the ComboBoxes has no effect, i.e. they do not display their drop-down list of items.

I have tried making the Rectangle smaller (i.e. 10x10 pixels) so that it does not overlap the ComboBoxes. This makes no difference.

```<code>private void createNodeWithBackground() {
    pane = new Region() {
        @Override
        public void resize(double width, double height) {
            super.resize(width, height);

            backing = new Rectangle(width, height);
            InnerShadow shadeEffect = new InnerShadow();
            shadeEffect.setWidth(w/2);
            shadeEffect.setHeight(h/2);
            shadeEffect.setInput(new ColorAdjust(-0.1, 0.2, -0.1, 0.1));
            backing.setEffect(shadeEffect);

            getChildren().clear();
            getChildren().addAll(backing, getBodyNode());
        }
    };
    getChildren().add(pane);
}

/**
 * The concrete class provides a node to be displayed on top of the
 * Rectangle with the InnerShadow.
 * This might be a VBox containing a ComboBox and other nodes.
 */
protected abstract Region getBodyNode();
</code>```

Removing the Rectangle from the scene results in the ComboBoxes displaying drop-down lists as expected.

答: Using javafx.scene.control.ChoiceBox instead of javafx.scene.control.ComboBox resolves this issue, although I have no idea why.</p>

Body:
I have a requirement to display a Rectangle with an InnerShadow effect as the background of my JavaFX nodes. Each node needs to be resizable. I am implementing this with an abstract base class with a Region which has the Rectangle with an InnerShadow as one of its children and a Region provided by the concrete implementation of this class as its other child.

The problem occurs when I add one or more ComboBoxes to the child region. Clicking on the ComboBoxes has no effect, i.e. they do not display their drop-down list of items.

I have tried making the Rectangle smaller (i.e. 10x10 pixels) so that it does not overlap the ComboBoxes. This makes no difference.

private void createNodeWithBackground() {
    pane = new Region() {
        @Override
        public void resize(double width, double height) {
            super.resize(width, height);

            backing = new Rectangle(width, height);
            InnerShadow shadeEffect = new InnerShadow();
            shadeEffect.setWidth(w/2);
            shadeEffect.setHeight(h/2);
            shadeEffect.setInput(new ColorAdjust(-0.1, 0.2, -0.1, 0.1));
            backing.setEffect(shadeEffect);

            getChildren().clear();
            getChildren().addAll(backing, getBodyNode());
        }
    };
    getChildren().add(pane);
}

/**
 * The concrete class provides a node to be displayed on top of the
 * Rectangle with the InnerShadow.
 * This might be a VBox containing a ComboBox and other nodes.
 */
protected abstract Region getBodyNode();

Removing the Rectangle from the scene results in the ComboBoxes displaying drop-down lists as expected.


问:
Select rows that are not urls using regexp?
I've tried multiple regexp's but still fetching rows that contains urls.</p>

```<code>$fields=array(
":regexp"=>"/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/"
);

$foo=$sql->prepare("SELECT * FROM names WHERE name NOT REGEXP :regexp");
$foo->execute($fields);
</code>```

答:
are you using mysql? if so, the regex syntax is not PCRE (like your regex appears to be). it does not use the / delimiters.

also, if you're only testing for the existence of common urls, why isn't the domain part sufficient?

```<code>'[a-z]+://([a-z0-9]+(-+[a-z0-9]+)*\.)+[a-z]{2,}'
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I've tried multiple regexp's but still fetching rows that contains urls.

$fields=array(
":regexp"=>"/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/"
);

$foo=$sql->prepare("SELECT * FROM names WHERE name NOT REGEXP :regexp");
$foo->execute($fields);

Body:
are you using mysql? if so, the regex syntax is not PCRE (like your regex appears to be). it does not use the / delimiters.

also, if you're only testing for the existence of common urls, why isn't the domain part sufficient?

'[a-z]+://([a-z0-9]+(-+[a-z0-9]+)*\.)+[a-z]{2,}'


问:
mockito-groovy-suppport not working
I am writing my Junit test cases for Groovy using Mockito jar, but it is giving me following exception

```<code>java.lang.NullPointerException
    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:42)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:117)
    at  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
</code>```

So I have added mockito-groovy-support 1.3 version jar. but I am still facing the same issue. below is my code

```<code>package test.service
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import static org.mockito.Mockito.when;

//@RunWith(MockitoJUnitRunner.class)
class SyncImplTest {
@Before
public void init() {
    MockitoAnnotations.initMocks(this);
}
    @InjectMocks
    SyncThreatImpl  fixture;

    @Mock
    RpcConfigurationLoader rpcConfigurationLoader

    @Test
    public void testRpcConfig(){
        RpcApiInfo rpcApiInfo =  new RpcApiInfo();
        when(rpcConfigurationLoader.loadConfiguration()).thenReturn(rpcApiInfo) //here m getting NPE
    }

}
</code>```

this is my ss of the jars am using

答:
Again you are using libraries that are aaaaages old. Do NOT mix different Mockito versions. You now have Mockito 1.10.19 and 2.8.9 both in your classpath. mockito-groovy-support is from 2013 and is written for Mockito 1.x, so most probably will not work with Mockito 2.x and you should really not mix two Mockito versions in your classpath.

I guess Mockito like most mocking frameworks just don't properly support mocking Groovy. The most mocking frameworks (JMockit too e. g.) are written for Java and wont work properly with Groovy as Groovy is too much a dynamic language.

You should maybe instead use the Groovy-built-in mocking as described at https://kahdev.wordpress.com/2013/02/14/mocking-java-classes-in-groovy-vs-mockito/

Or you could consider using Spock framework instead for writing tests and mocking. It is written in Groovy and works perfectly fine for Groovy, also with mocking and stubbing. It's syntax and how you write tests might look a bit alien at first, but if you get used to it, it is really an amazing test framework and it is built upon JUnit, so can be run and evaluated by any tool that supports JUnit tests.

Title: mockito-groovy-suppport not working

Body:
I am writing my Junit test cases for Groovy using Mockito jar, but it is giving me following exception

java.lang.NullPointerException
    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:42)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:117)
    at  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

So I have added mockito-groovy-support 1.3 version jar. but I am still facing the same issue. below is my code

package test.service
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import static org.mockito.Mockito.when;

//@RunWith(MockitoJUnitRunner.class)
class SyncImplTest {
@Before
public void init() {
    MockitoAnnotations.initMocks(this);
}
    @InjectMocks
    SyncThreatImpl  fixture;

    @Mock
    RpcConfigurationLoader rpcConfigurationLoader

    @Test
    public void testRpcConfig(){
        RpcApiInfo rpcApiInfo =  new RpcApiInfo();
        when(rpcConfigurationLoader.loadConfiguration()).thenReturn(rpcApiInfo) //here m getting NPE
    }

}

this is my ss of the jars am using


问:
How to dynamically find the IP address of a specific device in a small network?
I am developing a small-scale hobby project which involves an Android app and an ESP8266. The basic idea is, the ESP8266 will control an RGB led and the app will let me do this control remotely.

In my architecture, the ESP8266 will be connected to my home network and when my smartphone is connected to the same network, when I open the app the phone and the ESP8266 will pair and I will do the control over wifi. But the IP address of the ESP will change dynamically. My question is, how can I find out the IP address of the ESP8266 if it's not static?

答: This is what multicast was designed to do. Have your device listen on a particular multicast group, and your phone can send a message to the multicast group, then the device will respond via unicast to your phone. You phone will then have the unicast address of the device. In general, you want to use a multicast group in the Organization-Local Scope (239.0.0.0/8) range.


问:
SQL Many-To-Many multiple items per column
Sorry about the title, as I'm new to SQL and I don't know how to explain the problem appropriately...

I have 5 tables.

Delivery

```<code>ID | Time      |
---------------|
1  | 1999-01-01|
2  | 1999-01-01|
3  | 1999-01-01|
</code>```

Delivery_Items

```<code>Delivery_ID | Order_ID|
----------------------|
1           | 1       |
2           | 2       |
3           | 3       |
</code>```

Food

```<code>ID | Name | Price  |
-------------------|
1  |Eggs  | 3.00   |
2  |Bacon | 1.50   |
3  |Ham   | 4.00   |
</code>```

Ordered_Items

```<code>Order_ID | Item_ID  |
--------------------|
1        |  1       |
1        |  1       |
1        |  2       |
1        |  3       |
2        |  2       |
2        |  1       |
3        |  3       |
</code>```

Orders

```<code>ID | Total_Price  |
------------------|
1  | 11.50        |
</code>```

I would like to Join them together for an expected result of something like this

```<code>Delivery_ID    | Food.Name            | Total Price |
----------------------------------------------------|
1              |Eggs, Eggs, Bacon, Ham| 11.50       |
2              |Bacon, Eggs           | 4.50        |
3              |Ham                   | 4.00        |
</code>```

So far I've tried:

```<code>SELECT
    O.Id,
    GROUP_CONCAT(F.Name
        SEPARATOR ','),
    O.Total
FROM
    Food F
        LEFT OUTER JOIN
    Ordered_Items OI ON OI.Item_ID = F.Id
        LEFT OUTER JOIN
    Orders O ON O.Id = OI.order_Id
GROUP BY O.Id;
</code>```

Which results in

```<code>Delivery_ID    | Food.Name                     | Total Price |
-------------------------------------------------------------|
NULL           |Eggs, Bacon, Ham(trash values) | NULL        |
1              |Eggs, Eggs, Bacon, Ham         | 11.50       |
2              |Bacon, Eggs                    | 4.50        |
3              |Ham                            | 4.00        |
</code>```

How do I get rid of that first NULL line?
And by trash values I mean their IDs don't appear in any Ordered_Items row.

答:
As i understood, you need to know the total price per order.

You can try this:

```<code>SELECT o.Order_ID, SUM(f.Price)
  FROM Ordered_Items oi INNER JOIN Food f
  ON oi.Item_ID = f.ID
  GROUP BY o.Order_ID;
</code>```

As for the items, I think you cannot do it, since you cannot aggregate a field of type VARCHAR.

You can try the below:

```<code>SELECT o.Order_ID, f. Name
  FROM Ordered_Items oi INNER JOIN Food f
  ON oi.Item_ID = f.ID
  ORDER BY o.Order_ID;
</code>```

The result will be somthing like the below:

```<code>Order_ID | Name
--------------------
1        |  Eggs
1        |  Eggs
1        |  Bacon
1        |  Ham
2        |  Bacon
2        |  Eggs
3        |  Ham
</code>```

Hope this helps!

Body:
Sorry about the title, as I'm new to SQL and I don't know how to explain the problem appropriately...

I have 5 tables.

Delivery

ID | Time      |
---------------|
1  | 1999-01-01|
2  | 1999-01-01|
3  | 1999-01-01|

Delivery_Items

Delivery_ID | Order_ID|
----------------------|
1           | 1       |
2           | 2       |
3           | 3       |

Food

ID | Name | Price  |
-------------------|
1  |Eggs  | 3.00   |
2  |Bacon | 1.50   |
3  |Ham   | 4.00   |

Ordered_Items

Order_ID | Item_ID  |
--------------------|
1        |  1       |
1        |  1       |
1        |  2       |
1        |  3       |
2        |  2       |
2        |  1       |
3        |  3       |

Orders

ID | Total_Price  |
------------------|
1  | 11.50        |

I would like to Join them together for an expected result of something like this

Delivery_ID    | Food.Name            | Total Price |
----------------------------------------------------|
1              |Eggs, Eggs, Bacon, Ham| 11.50       |
2              |Bacon, Eggs           | 4.50        |
3              |Ham                   | 4.00        |

So far I've tried:

SELECT
    O.Id,
    GROUP_CONCAT(F.Name
        SEPARATOR ','),
    O.Total
FROM
    Food F
        LEFT OUTER JOIN
    Ordered_Items OI ON OI.Item_ID = F.Id
        LEFT OUTER JOIN
    Orders O ON O.Id = OI.order_Id
GROUP BY O.Id;

Which results in

Delivery_ID    | Food.Name                     | Total Price |
-------------------------------------------------------------|
NULL           |Eggs, Bacon, Ham(trash values) | NULL        |
1              |Eggs, Eggs, Bacon, Ham         | 11.50       |
2              |Bacon, Eggs                    | 4.50        |
3              |Ham                            | 4.00        |

How do I get rid of that first NULL line?
And by trash values I mean their IDs don't appear in any Ordered_Items row.

Body:
As i understood, you need to know the total price per order.

You can try this:

SELECT o.Order_ID, SUM(f.Price)
  FROM Ordered_Items oi INNER JOIN Food f
  ON oi.Item_ID = f.ID
  GROUP BY o.Order_ID;

As for the items, I think you cannot do it, since you cannot aggregate a field of type VARCHAR.

You can try the below:

SELECT o.Order_ID, f. Name
  FROM Ordered_Items oi INNER JOIN Food f
  ON oi.Item_ID = f.ID
  ORDER BY o.Order_ID;

The result will be somthing like the below:

Order_ID | Name
--------------------
1        |  Eggs
1        |  Eggs
1        |  Bacon
1        |  Ham
2        |  Bacon
2        |  Eggs
3        |  Ham

Hope this helps!


问:
Selenium WD / Java | Cannot create 'if' & 'else if' statement
I have a web page that have an indicator if a specific stock is opened/closed.
For that I want to set a if & else if statement. For some reason I get an error in eclipse.

*Note: Don't know if it helps, but if I copy/paste the code to a new empty class that is a 'Main' one, it works without any errors - so the structure of the code is Ok I guess.

```<code>import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class TestClock {

public static void chromeMethod(WebDriver driver) {
    System.setProperty("webdriver.chrome.driver", "C:\\automation\\drivers\\chromedriver.exe");
}

public static void runTestClock(WebDriver driver)
{

    WebElement Status = null;
    if( Status == driver.findElement(By.cssSelector(".redClockBigIcon")));
    {
        System.out.println("Stock is closed");
        driver.navigate().back();
    }

    else if (Status == driver.findElement(By.cssSelector(".greenClockBigIcon")) );
    {
        System.out.println("Stock is open");

        driver.navigate().back();
    }

}
}
</code>```

I get a syntax error under 'else' :

Syntax error on token "else", delete this token

答: Please remove the ; (semi-colon) at the end of if and else if statements.</p>

Body:
I have a web page that have an indicator if a specific stock is opened/closed.
For that I want to set a if & else if statement. For some reason I get an error in eclipse.

*Note: Don't know if it helps, but if I copy/paste the code to a new empty class that is a 'Main' one, it works without any errors - so the structure of the code is Ok I guess.

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

public class TestClock {

public static void chromeMethod(WebDriver driver) {
    System.setProperty("webdriver.chrome.driver", "C:\\automation\\drivers\\chromedriver.exe");
}

public static void runTestClock(WebDriver driver)
{

    WebElement Status = null;
    if( Status == driver.findElement(By.cssSelector(".redClockBigIcon")));
    {
        System.out.println("Stock is closed");
        driver.navigate().back();
    }

    else if (Status == driver.findElement(By.cssSelector(".greenClockBigIcon")) );
    {
        System.out.println("Stock is open");

        driver.navigate().back();
    }

}
}

I get a syntax error under 'else' :

Syntax error on token "else", delete this token


问:
How to emit events in tkinter?
I have simple app written in python3 and tkinter module. I want to write my custom widget and need to send my custom event.

Why this sample code below does not work?

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

from tkinter import *

class MyWidget(Listbox):
    def __init__(self, master, *args, **kwargs):
        super().__init__(master, *args, **kwargs)

        # ===================
        # error:  _tkinter.TclError: only one event specification allowed
        self.bind('<<ListboxSelect>>', lambda e: self.event_generate('MyEvent'))
        # ===================

class App(Tk):
    def __init__(self):
        super().__init__()
        w = MyWidget(self)
        w.bind('MyEvent', lambda e: print('It\'s working'))
        w.pack()

        w.insert(END, 'ddddddd')

if __name__ == '__main__':
    app = App()
    app.mainloop()
</code>```

答: Virtual events need to be surrounded by << and >>. Just replace 'MyEvent' by '<<MyEvent>>' and your custom event should work.

Title: How to emit events in tkinter?

Body:
I have simple app written in python3 and tkinter module. I want to write my custom widget and need to send my custom event.

Why this sample code below does not work?

#!/usr/bin/env python3

from tkinter import *

class MyWidget(Listbox):
    def __init__(self, master, *args, **kwargs):
        super().__init__(master, *args, **kwargs)

        # ===================
        # error:  _tkinter.TclError: only one event specification allowed
        self.bind('<<ListboxSelect>>', lambda e: self.event_generate('MyEvent'))
        # ===================

class App(Tk):
    def __init__(self):
        super().__init__()
        w = MyWidget(self)
        w.bind('MyEvent', lambda e: print('It\'s working'))
        w.pack()

        w.insert(END, 'ddddddd')

if __name__ == '__main__':
    app = App()
    app.mainloop()


问:
Accessing Google Inbox reminders using API
Is there any way to access Google Inbox reminders via Gmail API or another way? I know that Google Inbox can show reminders from Google Keep, but can't find any information about how this communication is done.</p>

答:
There is a Google Tasks API that is available which has some reminder functionality built into GMail.

Comparrison of Google Keep, Google Inbox Reminders and Google Tasks as well as info found at The Google Tasks Guide: How to Get the Most Out of the Simplest To-Do App


问:
Loop to 100 then change change row x times
I am trying to create a vba loop that loops to 100 then continues value 101 at row 1 on the next column.

Column A data would have 1-100, B = 101-200, C = 201-300 etc.,

This is some code I got online and I am trying to modify it.

```<code>Sub exa()
    Dim CB          As CommandBar
    Dim ctl         As CommandBarButton
    Dim strCBName   As String
    Dim wbTemp      As Workbook
    Dim wks         As Worksheet
    Dim rngInput    As Range
    Dim i           As Long

    Set CB = CommandBars.Add(Position:=msoBarPopup, MenuBar:=False, Temporary:=True)
    Set ctl = CB.Controls.Add(Type:=msoControlButton, Temporary:=True)
    strCBName = CB.Name

    'Set wbTemp = Workbooks.Add(xlWBATWorksheet)
    'Set wks = wbTemp.Worksheets(1)
    Set wks = ThisWorkbook.Worksheets(1)
    Set rngInput = wks.Range("A:A")

    rngInput.Offset(, -1).ColumnWidth = 6.5
    rngInput.ColumnWidth = 6.5
    rngInput.HorizontalAlignment = xlRight

    For i = 1 To 100
        ctl.FaceId = i
        ctl.CopyFace
        rngInput.Cells(i).PasteSpecial
        rngInput.Cells(i).Value = i
    Next

    rngInput.Cells(1).Select

    On Error Resume Next
    Set CB = CommandBars(strCBName)
    On Error GoTo 0

    If Not CB Is Nothing Then
        CB.Delete
    Else
        MsgBox "no toolbar!", 0, vbNullString
    End If
End Sub
</code>```

Thanks for any help

答:
You have the worksheet, so you don't have to use a range and set the cells that way.  Just set the cells of the worksheet directly</p>

```<code>Dim Row As long
Dim Col As long

Set wks = ThisWorkbook.Worksheets(1)

For Col = 1 to 10
    For Row = 1 To 100
        wks.Cells(Row, Col).Value = (Col - 1) * 100 + Row
    Next
Next
</code>```

Body:
I am trying to create a vba loop that loops to 100 then continues value 101 at row 1 on the next column.

Column A data would have 1-100, B = 101-200, C = 201-300 etc.,

This is some code I got online and I am trying to modify it.

Sub exa()
    Dim CB          As CommandBar
    Dim ctl         As CommandBarButton
    Dim strCBName   As String
    Dim wbTemp      As Workbook
    Dim wks         As Worksheet
    Dim rngInput    As Range
    Dim i           As Long

    Set CB = CommandBars.Add(Position:=msoBarPopup, MenuBar:=False, Temporary:=True)
    Set ctl = CB.Controls.Add(Type:=msoControlButton, Temporary:=True)
    strCBName = CB.Name

    'Set wbTemp = Workbooks.Add(xlWBATWorksheet)
    'Set wks = wbTemp.Worksheets(1)
    Set wks = ThisWorkbook.Worksheets(1)
    Set rngInput = wks.Range("A:A")

    rngInput.Offset(, -1).ColumnWidth = 6.5
    rngInput.ColumnWidth = 6.5
    rngInput.HorizontalAlignment = xlRight

    For i = 1 To 100
        ctl.FaceId = i
        ctl.CopyFace
        rngInput.Cells(i).PasteSpecial
        rngInput.Cells(i).Value = i
    Next

    rngInput.Cells(1).Select

    On Error Resume Next
    Set CB = CommandBars(strCBName)
    On Error GoTo 0

    If Not CB Is Nothing Then
        CB.Delete
    Else
        MsgBox "no toolbar!", 0, vbNullString
    End If
End Sub

Thanks for any help

Body:
You have the worksheet, so you don't have to use a range and set the cells that way.  Just set the cells of the worksheet directly

Dim Row As long
Dim Col As long

Set wks = ThisWorkbook.Worksheets(1)

For Col = 1 to 10
    For Row = 1 To 100
        wks.Cells(Row, Col).Value = (Col - 1) * 100 + Row
    Next
Next


问:
Print 2 ArrayLists with specific format
I am trying to format the output of my program, so it looks easily readable by the user. I am not that good at formatting text and I would really welcome your help.

I am trying to print/display(in my JTextArea). I already have a method to display there:

```<code>public void display(String... lines){
     for(String line:lines){
          System.out.println(line);
     }
}
</code>```

Now, I have the 2 ArrayLists that contain some data which was added to them through the use of the program.

```<code>itemOrders = new ArrayList<CafeOrders>();
customers = new ArrayList<CafeCustomer>();
</code>```

The constructors, respectively:

```<code>public CafeOrders(String orderID, String itemName, double price){
    super();
    this.orderID = orderID;
    this.itemName = itemName;
    this.price = price;

}
</code>```

and

```<code>public CafeCustomer(int customerID, String customerName){
    super();
    this.customerID = customerID;
    this.customerName = customerName;
    this.orderNo = UUID.randomUUID().toString();

}
</code>```

I made it in such a way, that orderNo = orderID.

First the customer name is asked, then when he selects from a list of items, each item is added to the CafeOrders ArrayList along with the customer's ID.

I want to create a method that prints those 2 ArrayLists in the specific format, or something similar:

```<code>customerName "with id" orderID "has purchased" itemName1
                                               itemName2
                                               itemName3
                                               etc...
</code>```

Any help would be appreciated!

答:
modify the code like this :

for(CafeCustomer customer : customers ){

```<code> System.out.println(customer.getCustomerName() +"with Id " +
            customer.getCustomerId()+ "has purchased ::");

   for(CafeOrders order: itemOrders ){
       if(customer.getOrderNo.equals(order.getOrderId()) ){
           System.out.println("\t\t\t\t\t\t\t"+ order.getItemName());
       }
   }
</code>```

}

Title: Print 2 ArrayLists with specific format

Body:
I am trying to format the output of my program, so it looks easily readable by the user. I am not that good at formatting text and I would really welcome your help.

I am trying to print/display(in my JTextArea). I already have a method to display there:

public void display(String... lines){
     for(String line:lines){
          System.out.println(line);
     }
}

Now, I have the 2 ArrayLists that contain some data which was added to them through the use of the program.

itemOrders = new ArrayList<CafeOrders>();
customers = new ArrayList<CafeCustomer>();

The constructors, respectively:

public CafeOrders(String orderID, String itemName, double price){
    super();
    this.orderID = orderID;
    this.itemName = itemName;
    this.price = price;

}

and

public CafeCustomer(int customerID, String customerName){
    super();
    this.customerID = customerID;
    this.customerName = customerName;
    this.orderNo = UUID.randomUUID().toString();

}

I made it in such a way, that orderNo = orderID.

First the customer name is asked, then when he selects from a list of items, each item is added to the CafeOrders ArrayList along with the customer's ID.

I want to create a method that prints those 2 ArrayLists in the specific format, or something similar:

customerName "with id" orderID "has purchased" itemName1
                                               itemName2
                                               itemName3
                                               etc...

Any help would be appreciated!

Body:
modify the code like this :

for(CafeCustomer customer : customers ){

 System.out.println(customer.getCustomerName() +"with Id " +
            customer.getCustomerId()+ "has purchased ::");

   for(CafeOrders order: itemOrders ){
       if(customer.getOrderNo.equals(order.getOrderId()) ){
           System.out.println("\t\t\t\t\t\t\t"+ order.getItemName());
       }
   }

}


问:
How to create a ColorSlider by picking start and end color in hexdec in android
I want to create a seekbar in Android which the startcolor is going to be for example "00AA10" and endcolor "0FFF99" and then I can change the color by incrementing this hex decimal value and get the new color by calculating the distance of the 2 given colors.</p>

答:
```<code>String hexStringStart= "00AA10";
int a=Integer.parseInt(hexStringStart, 16);

String hexStringEnd= "0FFF99";
int b=Integer.parseInt(hexStringEnd, 16);
int discrete=0;
int start_pos=0;
int start_position=0;
int start=0;
int end=100;
SeekBar seek= new SeekBar(getContext());
start=a;      // need to give starting value of SeekBar
end=b;         // need to give end value of SeekBar
start_pos=a;    // need to give starting position value of SeekBar

    start_position=(int) (((start_pos-start)/(end-start))*100);
    discrete=start_pos;
     seek.setProgress(start_position);
    seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            String colorString = String.format("%06X", (0xFFFFFF & discrete));
            // TODO Auto-generated method stub
            Toast.makeText(getContext(), "Color = "+colorString, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
            // TODO Auto-generated method stub
            // To convert it as discrete value
            float temp=progress;
            float dis=end-start;
            discrete = (int) (start+((temp/100)*dis));

        }
    });

}
</code>```


问:
How to use same object at different places in a class?
I have written small java code, and want to use same object which I have created in main method in other methods as well in a class. Is there any way ? I dont want to create every time new object in Checklength method just to call digitSum. I want use same o object created in main method.

Note: Without changing method properties

```<code>public class UserMainCode {

    public int digitSum(int input1) {
        int num = input1;
        int sum = 0;
        int output = 0;
        int length = 0;
        while (num > 0) {
            sum = sum + num % 10;
            num = num / 10;
        }
        output = sum;
        length = Integer.valueOf(Integer.toString(output).length());
        Checklength(length, output);
        return length;
    }

    public static void Checklength(int length, int sum) {
        if (length > 1) {
            UserMainCode b = new UserMainCode();
            b.digitSum(sum);
        }
        else {
            System.out.println(sum);
        }
    }

    public static void main(String[] args) {
        UserMainCode o = new UserMainCode();
        o.digitSum(976592);
    }
}
</code>```

Any ideas ?

答:
The thing to do in this situation is to remove static from the checklength method. static means that the method belongs at the class-level rather than the instance level. If you remove that, checklength will be back on the instance-level and will be able to call digitSum on the same instance (which can be explicitly accessed via the keyword this).

```<code>public class UserMainCode {

    public int digitSum(int input1) {
        int num = input1;
        int sum = 0;
        int output = 0;
        int length = 0;
        while (num > 0) {
            sum = sum + num % 10;
            num = num / 10;
        }
        output = sum;
        length = Integer.valueOf(Integer.toString(output).length());
        Checklength(length, output);
        return length;
    }

    public void checklength(int length, int sum) {
        if (length > 1) {
            // deleted instance b - we don't need it
            digitSum(sum);  // implicitly means  this.digitSum(sum);
        }
        else {
            System.out.println(sum);
        }
    }
}
</code>```

All of these operations now happen on the instance created in your main method.

Body:
I have written small java code, and want to use same object which I have created in main method in other methods as well in a class. Is there any way ? I dont want to create every time new object in Checklength method just to call digitSum. I want use same o object created in main method.

Note: Without changing method properties

public class UserMainCode {

    public int digitSum(int input1) {
        int num = input1;
        int sum = 0;
        int output = 0;
        int length = 0;
        while (num > 0) {
            sum = sum + num % 10;
            num = num / 10;
        }
        output = sum;
        length = Integer.valueOf(Integer.toString(output).length());
        Checklength(length, output);
        return length;
    }

    public static void Checklength(int length, int sum) {
        if (length > 1) {
            UserMainCode b = new UserMainCode();
            b.digitSum(sum);
        }
        else {
            System.out.println(sum);
        }
    }

    public static void main(String[] args) {
        UserMainCode o = new UserMainCode();
        o.digitSum(976592);
    }
}

Any ideas ?

Body:
The thing to do in this situation is to remove static from the checklength method. static means that the method belongs at the class-level rather than the instance level. If you remove that, checklength will be back on the instance-level and will be able to call digitSum on the same instance (which can be explicitly accessed via the keyword this).

public class UserMainCode {

    public int digitSum(int input1) {
        int num = input1;
        int sum = 0;
        int output = 0;
        int length = 0;
        while (num > 0) {
            sum = sum + num % 10;
            num = num / 10;
        }
        output = sum;
        length = Integer.valueOf(Integer.toString(output).length());
        Checklength(length, output);
        return length;
    }

    public void checklength(int length, int sum) {
        if (length > 1) {
            // deleted instance b - we don't need it
            digitSum(sum);  // implicitly means  this.digitSum(sum);
        }
        else {
            System.out.println(sum);
        }
    }
}

All of these operations now happen on the instance created in your main method.


问:
VSCode Debug C++: Why does the flow not stop at breakpoint?

VSCode Version:1.3.1

OS Version:Ubuntu 14.04

I debug a C++ project on Ubuntu 14.04. I run cmake to produce an executable file and setting VSCode config file. When I press F5 to debug, the program runs well, but it doesn't stop at breakpoint!

my source code is in ${workspaceRoot}/InfiniTAM

executable file is in ${workspaceRoot}/build

My config file:

```<code>tasjs.json

    {
"version": "0.1.0",
"command": "echo",
"isShellCommand": true,
"args": ["InfiniTAM!"],
"showOutput": "always"
}

launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "C++ Launch (GDB)",
            "type": "cppdbg",
            "request": "launch",
            "launchOptionType": "Local",
            "targetArchitecture": "x64",
            "program": "${workspaceRoot}/build/InfiniTAM",
            "args": ["Teddy/calib.txt", "Teddy/Frames/%04i.ppm","Teddy/Frames/%04i.pgm"],
            "stopAtEntry": false,
            "cwd": "${workspaceRoot}/build",
            "environment": [],
            "externalConsole": true
        }
    ]
}
</code>```

答:
I have had this same problem for a while and am now able to write a working configuration which works universally for all C and CPP programs and you don't need to change anything during execution.

Install Code-Runner Extention.

Paste the configuration given below into your settings.json file.

```<code> {
   "code-runner.executorMap": {

    "javascript": "nodejs",
    "java": "cd $dir && javac $fileName && java $fileNameWithoutExt",
    "c": "cd $dir && gcc -g \"$fileName\" -o \"$fileNameWithoutExt\" && $dir\"$fileNameWithoutExt\"",
    "cpp": "cd $dir && g++ -g \"$fileName\" -o \"$fileNameWithoutExt\" && $dir\"$fileNameWithoutExt\"",
    "objective-c": "cd $dir && gcc -framework Cocoa $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
    "php": "php",
    "python": "python3",
    "perl": "perl",
    "ruby": "ruby",
    "go": "go run",
    "lua": "lua",
    "groovy": "groovy",
    "powershell": "powershell -ExecutionPolicy ByPass -File",
    "bat": "cmd /c",
    "shellscript": "bash",
    "fsharp": "fsi",
    "csharp": "scriptcs",
    "vbscript": "cscript //Nologo",
    "typescript": "ts-node",
    "coffeescript": "coffee",
    "scala": "scala",
    "swift": "swift",
    "julia": "julia",
    "crystal": "crystal",
    "ocaml": "ocaml",
    "r": "Rscript",
    "applescript": "osascript",
    "clojure": "lein exec",
    "haxe": "haxe --cwd $dirWithoutTrailingSlash --run $fileNameWithoutExt",
    "rust": "cd $dir && rustc $fileName && $dir$fileNameWithoutExt",
    "racket": "racket",
    "ahk": "autohotkey",
    "autoit": "autoit3",
    "kotlin": "cd $dir && kotlinc $fileName -include-runtime -d $fileNameWithoutExt.jar && java -jar $fileNameWithoutExt.jar",
    "dart": "dart",
    "pascal": "cd $dir && fpc $fileName && $dir$fileNameWithoutExt",
    "d": "cd $dir && dmd $fileName && $dir$fileNameWithoutExt",
    "haskell": "runhaskell",
    "nim": "nim compile --verbosity:0 --hints:off --run"
}
}
</code>```

Paste the below code in launch.json by clicking the settings symbol in the debugging panel (present at top left).

```<code>{
"version": "0.2.0",
"configurations": [
    {
        "name": "(gdb) Launch",
        "type": "cppdbg",
        "request": "launch",
        "program": "${fileDirname}/${fileBasenameNoExtension}",
        "args": [],
        "stopAtEntry": false,
        "cwd": "${workspaceFolder}",
        "environment": [],
        "externalConsole": true,
        "MIMode": "gdb",
        "setupCommands": [
            {
                "description": "Enable pretty-printing for gdb",
                "text": "-enable-pretty-printing",
                "ignoreFailures": true
            }
        ]
    }
  ]
}
</code>```

After this When ever you press ctrl+Alt+N it compiles and executes and you can see the output in the output panel.

When You Press F5 after selecting the right Task ( choose (gdb)Launch ). It will start the debugging with working break points and stuff.

ContentLicense: CC BY-SA 4.0

Body:
VSCode Version:1.3.1

OS Version:Ubuntu 14.04

I debug a C++ project on Ubuntu 14.04. I run cmake to produce an executable file and setting VSCode config file. When I press F5 to debug, the program runs well, but it doesn't stop at breakpoint!

my source code is in ${workspaceRoot}/InfiniTAM

executable file is in ${workspaceRoot}/build

My config file:

tasjs.json

    {
"version": "0.1.0",
"command": "echo",
"isShellCommand": true,
"args": ["InfiniTAM!"],
"showOutput": "always"
}

launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "C++ Launch (GDB)",
            "type": "cppdbg",
            "request": "launch",
            "launchOptionType": "Local",
            "targetArchitecture": "x64",
            "program": "${workspaceRoot}/build/InfiniTAM",
            "args": ["Teddy/calib.txt", "Teddy/Frames/%04i.ppm","Teddy/Frames/%04i.pgm"],
            "stopAtEntry": false,
            "cwd": "${workspaceRoot}/build",
            "environment": [],
            "externalConsole": true
        }
    ]
}

Body:
I have had this same problem for a while and am now able to write a working configuration which works universally for all C and CPP programs and you don't need to change anything during execution.

Install Code-Runner Extention.

Paste the configuration given below into your settings.json file.

 {
   "code-runner.executorMap": {

    "javascript": "nodejs",
    "java": "cd $dir && javac $fileName && java $fileNameWithoutExt",
    "c": "cd $dir && gcc -g \"$fileName\" -o \"$fileNameWithoutExt\" && $dir\"$fileNameWithoutExt\"",
    "cpp": "cd $dir && g++ -g \"$fileName\" -o \"$fileNameWithoutExt\" && $dir\"$fileNameWithoutExt\"",
    "objective-c": "cd $dir && gcc -framework Cocoa $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",
    "php": "php",
    "python": "python3",
    "perl": "perl",
    "ruby": "ruby",
    "go": "go run",
    "lua": "lua",
    "groovy": "groovy",
    "powershell": "powershell -ExecutionPolicy ByPass -File",
    "bat": "cmd /c",
    "shellscript": "bash",
    "fsharp": "fsi",
    "csharp": "scriptcs",
    "vbscript": "cscript //Nologo",
    "typescript": "ts-node",
    "coffeescript": "coffee",
    "scala": "scala",
    "swift": "swift",
    "julia": "julia",
    "crystal": "crystal",
    "ocaml": "ocaml",
    "r": "Rscript",
    "applescript": "osascript",
    "clojure": "lein exec",
    "haxe": "haxe --cwd $dirWithoutTrailingSlash --run $fileNameWithoutExt",
    "rust": "cd $dir && rustc $fileName && $dir$fileNameWithoutExt",
    "racket": "racket",
    "ahk": "autohotkey",
    "autoit": "autoit3",
    "kotlin": "cd $dir && kotlinc $fileName -include-runtime -d $fileNameWithoutExt.jar && java -jar $fileNameWithoutExt.jar",
    "dart": "dart",
    "pascal": "cd $dir && fpc $fileName && $dir$fileNameWithoutExt",
    "d": "cd $dir && dmd $fileName && $dir$fileNameWithoutExt",
    "haskell": "runhaskell",
    "nim": "nim compile --verbosity:0 --hints:off --run"
}
}

Paste the below code in launch.json by clicking the settings symbol in the debugging panel (present at top left).

{
"version": "0.2.0",
"configurations": [
    {
        "name": "(gdb) Launch",
        "type": "cppdbg",
        "request": "launch",
        "program": "${fileDirname}/${fileBasenameNoExtension}",
        "args": [],
        "stopAtEntry": false,
        "cwd": "${workspaceFolder}",
        "environment": [],
        "externalConsole": true,
        "MIMode": "gdb",
        "setupCommands": [
            {
                "description": "Enable pretty-printing for gdb",
                "text": "-enable-pretty-printing",
                "ignoreFailures": true
            }
        ]
    }
  ]
}

After this When ever you press ctrl+Alt+N it compiles and executes and you can see the output in the output panel.

When You Press F5 after selecting the right Task ( choose (gdb)Launch ). It will start the debugging with working break points and stuff.


问:
DB-API SQLite INSERT statement throws InterfaceError in Python 2.7
Given a SQLite table I've created, with the field in question being type TEXT, the following fails:

hsh = hashlib.sha1("".join(some_list)).hexdigest()

db_setup(hsh)

I receive the error:

InterfaceError: Error binding parameter 2 - probably unsupported type.

```<code>def db_setup(my_hash, oavals)
    to_insert = (my_hash,)
    ('INSERT INTO position VALUES \
    (null, ?, ?, null, ?, ?, ?, ?, ?)',(0, 0, to_insert,
    oavals["a"], oavals["b"],
    oavals["c"], oavals["d"]))
</code>```

If I substitute a manual int or string (e.g. 57, or "hello" for to_insert in the db_setup def, it works fine, which leads me to believe that it's tripping over the hash, for some reason. I feel as if I'm missing something obvious here.

Table schema:

    'CREATE TABLE position \

    (id INTEGER PRIMARY KEY, position INTEGER, displayline INTEGER, \

    header TEXT, digest TEXT, conkey TEXT, consecret TEXT, \

    acckey TEXT, accsecret TEXT)'

答:
It is failing because to_insert is a tuple, not the value you wish to insert.

Try changing that first line to:

```<code>to_insert = my_hash
</code>```

Or better yet, just put my_hash into your parameter list.

Here's an example:

```<code>>>> hsh = '49cb6536afc7e4a4b3a94eb493aae4d52b8f6a60'
>>> conn = sqlite3.connect(':memory:')
>>> c = conn.cursor()
>>> c.execute("CREATE TABLE t (i TEXT);")
>>> c.execute("INSERT INTO t VALUES (?)", (hsh,)) # tuple works
<sqlite3.Cursor object at 0x011A35E0>
>>> c.execute("INSERT INTO t VALUES (?)", ((123,),)) # tuple within tuple doesn't
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.
</code>```

Body:
Given a SQLite table I've created, with the field in question being type TEXT, the following fails:

hsh = hashlib.sha1("".join(some_list)).hexdigest()

db_setup(hsh)

I receive the error:

InterfaceError: Error binding parameter 2 - probably unsupported type.

def db_setup(my_hash, oavals)
    to_insert = (my_hash,)
    ('INSERT INTO position VALUES \
    (null, ?, ?, null, ?, ?, ?, ?, ?)',(0, 0, to_insert,
    oavals["a"], oavals["b"],
    oavals["c"], oavals["d"]))

If I substitute a manual int or string (e.g. 57, or "hello" for to_insert in the db_setup def, it works fine, which leads me to believe that it's tripping over the hash, for some reason. I feel as if I'm missing something obvious here.

Table schema:

    'CREATE TABLE position \

    (id INTEGER PRIMARY KEY, position INTEGER, displayline INTEGER, \

    header TEXT, digest TEXT, conkey TEXT, consecret TEXT, \

    acckey TEXT, accsecret TEXT)'

Body:
It is failing because to_insert is a tuple, not the value you wish to insert.

Try changing that first line to:

to_insert = my_hash

Or better yet, just put my_hash into your parameter list.

Here's an example:

>>> hsh = '49cb6536afc7e4a4b3a94eb493aae4d52b8f6a60'
>>> conn = sqlite3.connect(':memory:')
>>> c = conn.cursor()
>>> c.execute("CREATE TABLE t (i TEXT);")
>>> c.execute("INSERT INTO t VALUES (?)", (hsh,)) # tuple works
<sqlite3.Cursor object at 0x011A35E0>
>>> c.execute("INSERT INTO t VALUES (?)", ((123,),)) # tuple within tuple doesn't
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.


问:
SQL querying two sources
I have a View and Table as example below

Table1

```<code>+---------+------+
| Country | City |
+---------+------+
| UK      | LDN  |
| US      | NEY  |
| US      | LAX  |
+---------+------+
</code>```

View1

```<code>+---------+---------+-------+
| Column1 | Column2 | Site  |
+---------+---------+-------+
| Test    | Test2   | UKLDN |
| Test    | Test2   | USNEY |
| Test    | Test2   | USLAX |
| Test    | Test2   | PELMA |
+---------+---------+-------+
</code>```

The result i'm trying to achieve is show all rows from View1, that have a View1.Site column matching Table1.Country and Table1.City. My confusion is how do to it as i'm not an sql person but more C# etc.

The resulting data I want to create is below. I don't know if I can do this solely from View1 or what functions to use.

Result

```<code>+---------+---------+-------+---------------+
| Column1 | Column2 | Site  | ExistInTable1 |
+---------+---------+-------+---------------+
| Test    | Test2   | UKLDN | Y             |
| Test    | Test2   | USNEY | Y             |
| Test    | Test2   | USLAX | Y             |
| Test    | Test2   | PELMA | N             |
+---------+---------+-------+---------------+
</code>```

Thanks

答:
You need to do a LEFT JOIN with your table and then check if it matches or not with the info from the view, like this:

```<code>SELECT
    VW.Column1
    ,VW.Column2
    ,VW.Site
    ,CASE WHEN ISNULL(T.country, T.city) IS NULL THEN 'N' ELSE 'Y' END AS ExistInTable1
FROM View1 VW
LEFT JOIN Table1 T
    ON VW.site = CONCAT(T.country, T.City)
</code>```

The LEFT JOIN keyword returns all records from the left table (View1), and the matched records from the right table (Table1). The result is NULL from the right side, if there is no match.(check done with the CASE statement)

You can test it Here as well.

Title: SQL querying two sources

Body:
I have a View and Table as example below

Table1

+---------+------+
| Country | City |
+---------+------+
| UK      | LDN  |
| US      | NEY  |
| US      | LAX  |
+---------+------+

View1

+---------+---------+-------+
| Column1 | Column2 | Site  |
+---------+---------+-------+
| Test    | Test2   | UKLDN |
| Test    | Test2   | USNEY |
| Test    | Test2   | USLAX |
| Test    | Test2   | PELMA |
+---------+---------+-------+

The result i'm trying to achieve is show all rows from View1, that have a View1.Site column matching Table1.Country and Table1.City. My confusion is how do to it as i'm not an sql person but more C# etc.

The resulting data I want to create is below. I don't know if I can do this solely from View1 or what functions to use.

Result

+---------+---------+-------+---------------+
| Column1 | Column2 | Site  | ExistInTable1 |
+---------+---------+-------+---------------+
| Test    | Test2   | UKLDN | Y             |
| Test    | Test2   | USNEY | Y             |
| Test    | Test2   | USLAX | Y             |
| Test    | Test2   | PELMA | N             |
+---------+---------+-------+---------------+

Thanks

Body:
You need to do a LEFT JOIN with your table and then check if it matches or not with the info from the view, like this:

SELECT
    VW.Column1
    ,VW.Column2
    ,VW.Site
    ,CASE WHEN ISNULL(T.country, T.city) IS NULL THEN 'N' ELSE 'Y' END AS ExistInTable1
FROM View1 VW
LEFT JOIN Table1 T
    ON VW.site = CONCAT(T.country, T.City)

The LEFT JOIN keyword returns all records from the left table (View1), and the matched records from the right table (Table1). The result is NULL from the right side, if there is no match.(check done with the CASE statement)

You can test it Here as well.


问:
How to populate lookup tables in Rails tests
I am using Cucumber, RSpec, and Factory Girl for the testing of my Rails application. But I have several lookup tables that contain mostly static data. So I'm trying to figure out the best way to populate these when testing. Doing them individually in FactoryGirl seems tedious and I'd like to stay away from fixtures. For development and production, I populate them in my seeds.rb file.

Thanks!

答:
Use Factory Girl .sequence, Populator and Faker and you'll never run out of lab rats!

```<code>Factory.define(:model) do |m|
  m.sequence(:title)  { |n| "model-#{n}" }
  m.author            Faker::Name.name
  m.short             Populator.words(5)
  m.long              Populator.paragraphs(1..3)
end
</code>```

Then maybe in a before :each block

```<code>@models = []
15.times { @models << Factory.create(:model) }
</code>```

Or you can use only Populator to fill your database before tests.

Body:
Use Factory Girl .sequence, Populator and Faker and you'll never run out of lab rats!

Factory.define(:model) do |m|
  m.sequence(:title)  { |n| "model-#{n}" }
  m.author            Faker::Name.name
  m.short             Populator.words(5)
  m.long              Populator.paragraphs(1..3)
end

Then maybe in a before :each block

@models = []
15.times { @models << Factory.create(:model) }

Or you can use only Populator to fill your database before tests.


问:
Extracting values stored in a 2D array of dictionaries with Python
I have written a piece of code to determine the probability of getting a value Y when X dice are thrown. The equation I use contains a sum over range 0 up-to-and-including Y.

I want to plot the values on a grid (number of dice - sum of values) and have created a grid.

```<code>import scipy.special
from matplotlib import pyplot as plt
from matplotlib import cm as cm
import numpy as np
from numpy import exp,arange

def probability_of_sum(sum, dice, faces):
    # Give different names.
    X = sum
    Y = dice
    Z = faces

    # Calculations, calculations, calculations.
    # Dummy values.
    wanted_possibilities = 1
    total_possibilities = 2
    probability = wanted_possibilities/total_possibilities

    return {'wanted_possibilities':wanted_possibilities, 'total_possibilities':total_possibilities, 'probability':probability}

# Main part of the function.
# Consider 1 to 8 dice
# Get probabilities for lowest possible sum (8) to highest possible sum (48)

dice_range = np.linspace(1, 8, num=8)
value_range = np.linspace(1, 8*6, num=8*6)
X,Y = np.meshgrid( dice_range, value_range)

# Calculate value for each grid point separately using VECTORIZE.
value_prob = np.vectorize(probability_of_sum)( Y, X, 6)
</code>```

The output of my function is now a 2D array of dictionaries (below are dummy values):

```<code>[[{'Wanted_possibilities': 0, 'total_possibilities':1, 'probability':0}
{'Wanted_possibilities': 1, 'total_possibilities':1, 'probability':1}]
 [{'Wanted_possibilities': 0, 'total_possibilities':2, 'probability':0}
{'Wanted_possibilities': 1, 'total_possibilities':2, 'probability':0.5}]
 [{'Wanted_possibilities': 0, 'total_possibilities':3, 'probability':0}
{'Wanted_possibilities': 1, 'total_possibilities':3, 'probability':0.33}]
 [{'Wanted_possibilities': 0, 'total_possibilities':4, 'probability':0}
{'Wanted_possibilities': 1, 'total_possibilities':4, 'probability':0.25}] ]
</code>```

How do I continue from here to plot the output ('probability') as a 2D function of X and Y?

```<code>value_prob['probability']
</code>```

gives me the error

IndexError: only integers, slices(:), ellipsis (...), numpy.newaxis(None) and integer or boolean arrays are valid indices.

I can access individual elements by using

```<code>(value_prob[1,1])['probability']
</code>```

but then I would need a loop to plot the function. Is there a more general/powerful/cleaner way of accessing this?

EDIT: I would like to plot 'probability' against (dice, value).

答:
You can try this:

```<code>import matplotlib.pyplot as plt
import itertools
import numpy as np
s = [[{'Wanted_possibilities': 0, 'total_possibilities':1, 'probability':0},
{'Wanted_possibilities': 1, 'total_possibilities':1, 'probability':1}],
 [{'Wanted_possibilities': 0, 'total_possibilities':2, 'probability':0},
{'Wanted_possibilities': 1, 'total_possibilities':2, 'probability':0.5}],
 [{'Wanted_possibilities': 0, 'total_possibilities':3, 'probability':0},
{'Wanted_possibilities': 1, 'total_possibilities':3, 'probability':0.33}],
 [{'Wanted_possibilities': 0, 'total_possibilities':4, 'probability':0},
{'Wanted_possibilities': 1, 'total_possibilities':4, 'probability':0.25}] ]
final_data = list(itertools.chain(*[[[i['Wanted_possibilities'], i['total_possibilities'], i['probability']] for i in b] for b in s]))
plt.bar(np.arange(len([i[-1] for i in final_data])), [i[0] for i in final_data], 0.60, yerr = [i[1] for i in final_data])
plt.ylabel('Probabilities')
plt.xticks(np.arange(len([i[-1] for i in final_data])), tuple(map(str, [i[-1] for i in final_data])))
plt.show()
</code>```

Body:
I have written a piece of code to determine the probability of getting a value Y when X dice are thrown. The equation I use contains a sum over range 0 up-to-and-including Y.

I want to plot the values on a grid (number of dice - sum of values) and have created a grid.

import scipy.special
from matplotlib import pyplot as plt
from matplotlib import cm as cm
import numpy as np
from numpy import exp,arange

def probability_of_sum(sum, dice, faces):
    # Give different names.
    X = sum
    Y = dice
    Z = faces

    # Calculations, calculations, calculations.
    # Dummy values.
    wanted_possibilities = 1
    total_possibilities = 2
    probability = wanted_possibilities/total_possibilities

    return {'wanted_possibilities':wanted_possibilities, 'total_possibilities':total_possibilities, 'probability':probability}

# Main part of the function.
# Consider 1 to 8 dice
# Get probabilities for lowest possible sum (8) to highest possible sum (48)

dice_range = np.linspace(1, 8, num=8)
value_range = np.linspace(1, 8*6, num=8*6)
X,Y = np.meshgrid( dice_range, value_range)

# Calculate value for each grid point separately using VECTORIZE.
value_prob = np.vectorize(probability_of_sum)( Y, X, 6)

The output of my function is now a 2D array of dictionaries (below are dummy values):

[[{'Wanted_possibilities': 0, 'total_possibilities':1, 'probability':0}
{'Wanted_possibilities': 1, 'total_possibilities':1, 'probability':1}]
 [{'Wanted_possibilities': 0, 'total_possibilities':2, 'probability':0}
{'Wanted_possibilities': 1, 'total_possibilities':2, 'probability':0.5}]
 [{'Wanted_possibilities': 0, 'total_possibilities':3, 'probability':0}
{'Wanted_possibilities': 1, 'total_possibilities':3, 'probability':0.33}]
 [{'Wanted_possibilities': 0, 'total_possibilities':4, 'probability':0}
{'Wanted_possibilities': 1, 'total_possibilities':4, 'probability':0.25}] ]

How do I continue from here to plot the output ('probability') as a 2D function of X and Y?

value_prob['probability']

gives me the error

IndexError: only integers, slices(:), ellipsis (...), numpy.newaxis(None) and integer or boolean arrays are valid indices.

I can access individual elements by using

(value_prob[1,1])['probability']

but then I would need a loop to plot the function. Is there a more general/powerful/cleaner way of accessing this?

EDIT: I would like to plot 'probability' against (dice, value).

Body:
You can try this:

import matplotlib.pyplot as plt
import itertools
import numpy as np
s = [[{'Wanted_possibilities': 0, 'total_possibilities':1, 'probability':0},
{'Wanted_possibilities': 1, 'total_possibilities':1, 'probability':1}],
 [{'Wanted_possibilities': 0, 'total_possibilities':2, 'probability':0},
{'Wanted_possibilities': 1, 'total_possibilities':2, 'probability':0.5}],
 [{'Wanted_possibilities': 0, 'total_possibilities':3, 'probability':0},
{'Wanted_possibilities': 1, 'total_possibilities':3, 'probability':0.33}],
 [{'Wanted_possibilities': 0, 'total_possibilities':4, 'probability':0},
{'Wanted_possibilities': 1, 'total_possibilities':4, 'probability':0.25}] ]
final_data = list(itertools.chain(*[[[i['Wanted_possibilities'], i['total_possibilities'], i['probability']] for i in b] for b in s]))
plt.bar(np.arange(len([i[-1] for i in final_data])), [i[0] for i in final_data], 0.60, yerr = [i[1] for i in final_data])
plt.ylabel('Probabilities')
plt.xticks(np.arange(len([i[-1] for i in final_data])), tuple(map(str, [i[-1] for i in final_data])))
plt.show()


问:
Array objects values remove unwanted string
I have the following originaldata  which I would like to remove the div tags from the each objects inside it, leaving it with the content within the tags as the final result, see modifieddata.

What would be the best approach using javascript? filter and map? or something else.

```<code>originaldata = [{
        "name": "john",
        "content": "<div class="ExternalClass06EE5E42165840F48DFA193ACAD4F87A">aa</div>"
    },
    {
        "name": "mary",
        "content": "<div class="ExternalClass3D5F8061F3DE49C4BC55A9CE0ADD6F9A">asd</div>"
    }
]

modifieddata = [{
        "name": "john",
        "content": "aa"
    },
    {
      "name": "mary",
      "content": "asd"
    }
]
</code>```

答:
What would be the best approach using javascript? filter and map? or something else.

If you want to take a functional approach, just map (copying the objects), you're not filtering.

If not, just forEach modifying the existing objects:

Here's the map version:

var originaldata = [{
  "name": "john",
  "content": "
aa
"
},
{
  "name": "mary",
  "content": "
asd
"
}];
var temp = document.createElement("div");
var modifieddata = originaldata.map(entry => {
  temp.innerHTML = entry.content;
  return {
    name: entry.name,
    content: temp.firstChild.firstChild.nodeValue
  };
});
console.log(modifieddata);```
</div>
</div>
</p>

<p>...or using a Stage 3 proposal for object property spread that browser vendors are actively adding (Chrome has it, for instance), we can avoid having to know the names of the other properties:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// Note: I have the "Use BabelJS / ES2015" checkbox ticked
// so this will work even in browsers that don't
// have property spread yet.
const originaldata = [{
  "name": "john",
  "content": "<div class='ExternalClass06EE5E42165840F48DFA193ACAD4F87A'>aa</div>"
},
{
  "name": "mary",
  "content": "<div class='ExternalClass3D5F8061F3DE49C4BC55A9CE0ADD6F9A'>asd</div>"
}];
const temp = document.createElement("div");
const modifieddata = originaldata.map(entry => {
  temp.innerHTML = entry.content;
  return {
    ...entry, // <=== Property spread
    content: temp.firstChild.firstChild.nodeValue
  };
});
console.log(modifieddata);</code>```

Here's the forEach version:

var originaldata = [{
  "name": "john",
  "content": "
aa
"
},
{
  "name": "mary",
  "content": "
asd
"
}];
var temp = document.createElement("div");
originaldata.forEach(entry => {
  temp.innerHTML = entry.content;
  entry.content = temp.firstChild.firstChild.nodeValue;
});
console.log(originaldata);```
</div>
</div>
</p>

<hr>

<p>In a comment you've said:</p>

<blockquote>
  <p>If there is additional HTML tags within the DIV would this also be removed. Ideally I would like to keep all the content within the DIV even if its other tags. Is this also possible?</p>
</blockquote>

<p>In that case, in all of the above, change</p>

```entry.content = temp.firstChild.firstChild.nodeValue;
```

<p>to</p>

```entry.content = temp.firstChild.innerHTML;
```

<p>Here's the <code>forEach</code> with that change:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var originaldata = [{
  "name": "john",
  "content": "<div class='ExternalClass06EE5E42165840F48DFA193ACAD4F87A'>aa<span>stuff in a span</span><br></div>"
},
{
  "name": "mary",
  "content": "<div class='ExternalClass3D5F8061F3DE49C4BC55A9CE0ADD6F9A'>asd</div>"
}];
var temp = document.createElement("div");
originaldata.forEach(entry => {
  temp.innerHTML = entry.content;
  entry.content = temp.firstChild.innerHTML;
});
console.log(originaldata);</code>```

Body:
I have the following originaldata  which I would like to remove the div tags from the each objects inside it, leaving it with the content within the tags as the final result, see modifieddata.

What would be the best approach using javascript? filter and map? or something else.

originaldata = [{
        "name": "john",
        "content": "
aa
"
    },
    {
        "name": "mary",
        "content": "
asd
"
    }
]

modifieddata = [{
        "name": "john",
        "content": "aa"
    },
    {
      "name": "mary",
      "content": "asd"
    }
]

Body:
What would be the best approach using javascript? filter and map? or something else.

If you want to take a functional approach, just map (copying the objects), you're not filtering.

If not, just forEach modifying the existing objects:

Here's the map version:

var originaldata = [{
  "name": "john",
  "content": "<div class='ExternalClass06EE5E42165840F48DFA193ACAD4F87A'>aa</div>"
},
{
  "name": "mary",
  "content": "<div class='ExternalClass3D5F8061F3DE49C4BC55A9CE0ADD6F9A'>asd</div>"
}];
var temp = document.createElement("div");
var modifieddata = originaldata.map(entry => {
  temp.innerHTML = entry.content;
  return {
    name: entry.name,
    content: temp.firstChild.firstChild.nodeValue
  };
});
console.log(modifieddata);

...or using a Stage 3 proposal for object property spread that browser vendors are actively adding (Chrome has it, for instance), we can avoid having to know the names of the other properties:

// Note: I have the "Use BabelJS / ES2015" checkbox ticked
// so this will work even in browsers that don't
// have property spread yet.
const originaldata = [{
  "name": "john",
  "content": "<div class='ExternalClass06EE5E42165840F48DFA193ACAD4F87A'>aa</div>"
},
{
  "name": "mary",
  "content": "<div class='ExternalClass3D5F8061F3DE49C4BC55A9CE0ADD6F9A'>asd</div>"
}];
const temp = document.createElement("div");
const modifieddata = originaldata.map(entry => {
  temp.innerHTML = entry.content;
  return {
    ...entry, // <=== Property spread
    content: temp.firstChild.firstChild.nodeValue
  };
});
console.log(modifieddata);

Here's the forEach version:

var originaldata = [{
  "name": "john",
  "content": "<div class='ExternalClass06EE5E42165840F48DFA193ACAD4F87A'>aa</div>"
},
{
  "name": "mary",
  "content": "<div class='ExternalClass3D5F8061F3DE49C4BC55A9CE0ADD6F9A'>asd</div>"
}];
var temp = document.createElement("div");
originaldata.forEach(entry => {
  temp.innerHTML = entry.content;
  entry.content = temp.firstChild.firstChild.nodeValue;
});
console.log(originaldata);

In a comment you've said:

If there is additional HTML tags within the DIV would this also be removed. Ideally I would like to keep all the content within the DIV even if its other tags. Is this also possible?

In that case, in all of the above, change

entry.content = temp.firstChild.firstChild.nodeValue;

to

entry.content = temp.firstChild.innerHTML;

Here's the forEach with that change:

var originaldata = [{
  "name": "john",
  "content": "<div class='ExternalClass06EE5E42165840F48DFA193ACAD4F87A'>aa<span>stuff in a span</span><br></div>"
},
{
  "name": "mary",
  "content": "<div class='ExternalClass3D5F8061F3DE49C4BC55A9CE0ADD6F9A'>asd</div>"
}];
var temp = document.createElement("div");
originaldata.forEach(entry => {
  temp.innerHTML = entry.content;
  entry.content = temp.firstChild.innerHTML;
});
console.log(originaldata);


问:
How to display when data more than array in c++?
this my program...

```<code>{
    char name[5];
    cout << "NPM : ";
    cin >> name;
    cout << "  name: " << name <<endl;
}
</code>```

make the display name, birth date, with the provisions of each letter can not be more, if more then error. use array function !! how to input data if more array notice error..?

答:
```<code>{
   char name[5];
   cout << "NPM : ";
   cin.getline(name, 5);
   cout << "   name: " << name << endl;
}
</code>```

Would be possible approach if you HAVE to use char arrays.

The maxlenght for the String itself will be 4 characters long, because char[4] will be a Nullbyte ( '\0' )

Body:
this my program...

{
    char name[5];
    cout << "NPM : ";
    cin >> name;
    cout << "  name: " << name <<endl;
}

make the display name, birth date, with the provisions of each letter can not be more, if more then error. use array function !! how to input data if more array notice error..?

Body:
{
   char name[5];
   cout << "NPM : ";
   cin.getline(name, 5);
   cout << "   name: " << name << endl;
}

Would be possible approach if you HAVE to use char arrays.

The maxlenght for the String itself will be 4 characters long, because char[4] will be a Nullbyte ( '\0' )


问:
Why append don't work, pass by reference?
I have writtern the below codes

```<code>a = [1,2,3]
b = a.append(4)
</code>```

Why there is nothing inside b?

答:
Because append doesn't return the modified list - it simply adds the new element, modifying the list in-place and returning None. To get the effect you want, do this instead:

```<code>b = a + [4]
</code>```

Notice that the above creates a new list, whereas using append modifies the same list.

Body:
I have writtern the below codes

a = [1,2,3]
b = a.append(4)

Why there is nothing inside b?

Body:
Because append doesn't return the modified list - it simply adds the new element, modifying the list in-place and returning None. To get the effect you want, do this instead:

b = a + [4]

Notice that the above creates a new list, whereas using append modifies the same list.


问:
Able to malloc more than docker-compose mem_limit
I'm trying to limit my container so that it doesn't take up all the RAM on the host. From the Docker docs I understand that --memory limits the RAM and --memory-swap limits (RAM+swap). From the docker-compose docs it looks like the terms for those are mem_limit and memswap_limit, so I've constructed the following docker-compose file:

```<code>> cat docker-compose.yml
version: "2"

services:
    stress:
        image: progrium/stress
        command: '-m 1 --vm-bytes 15G --vm-hang 0 --timeout 10s'

        mem_limit: 1g
        memswap_limit: 2g
</code>```

The progrium/stress image just runs stress, which in this case spawns a single thread which requests 15GB RAM and holds on to it for 10 seconds.

I'd expect this to crash, since 15>2. (It does crash if I ask for more RAM than the host has.)

The kernel has cgroups enabled, and docker stats shows that the limit is being recognised:

```<code>> docker stats
CONTAINER       CPU %     MEM USAGE / LIMIT     MEM %       NET I/O       BLOCK I/O       PIDS
7624a9605c70    0.00%     1024MiB / 1GiB        99.99%      396B / 0B     172kB / 0B      2
</code>```

So what's going on? How do I actually limit the container?

Update:
Watching free, it looks like the RAM usage is effectively limited (only 1GB of RAM is used) but the swap is not: the container will gradually increase swap usage until it's eaten though all of the swap and stress crashes (it takes about 20secs to get through 5GB of swap on my machine).

Update 2:
Setting mem_swappiness: 0 causes an immediate crash when requesting more memory than mem_limit, regardless of memswap_limit.

答:
Running docker info shows WARNING: No swap limit support

According to https://docs.docker.com/engine/installation/linux/linux-postinstall/#your-kernel-does-not-support-cgroup-swap-limit-capabilities this is disabled by default ("Memory and swap accounting incur an overhead of about 1% of the total available memory and a 10% overall performance degradation.") You can enable it by editing the /etc/default/grub file:

Add or edit the GRUB_CMDLINE_LINUX line to add the following two key-value pairs:
GRUB_CMDLINE_LINUX="cgroup_enable=memory swapaccount=1"
then update GRUB with update-grub and reboot.

Body:
I'm trying to limit my container so that it doesn't take up all the RAM on the host. From the Docker docs I understand that --memory limits the RAM and --memory-swap limits (RAM+swap). From the docker-compose docs it looks like the terms for those are mem_limit and memswap_limit, so I've constructed the following docker-compose file:

> cat docker-compose.yml
version: "2"

services:
    stress:
        image: progrium/stress
        command: '-m 1 --vm-bytes 15G --vm-hang 0 --timeout 10s'

        mem_limit: 1g
        memswap_limit: 2g

The progrium/stress image just runs stress, which in this case spawns a single thread which requests 15GB RAM and holds on to it for 10 seconds.

I'd expect this to crash, since 15>2. (It does crash if I ask for more RAM than the host has.)

The kernel has cgroups enabled, and docker stats shows that the limit is being recognised:

> docker stats
CONTAINER       CPU %     MEM USAGE / LIMIT     MEM %       NET I/O       BLOCK I/O       PIDS
7624a9605c70    0.00%     1024MiB / 1GiB        99.99%      396B / 0B     172kB / 0B      2

So what's going on? How do I actually limit the container?

Update:
Watching free, it looks like the RAM usage is effectively limited (only 1GB of RAM is used) but the swap is not: the container will gradually increase swap usage until it's eaten though all of the swap and stress crashes (it takes about 20secs to get through 5GB of swap on my machine).

Update 2:
Setting mem_swappiness: 0 causes an immediate crash when requesting more memory than mem_limit, regardless of memswap_limit.


问:
How to get e-mail address of current Jenkins user to use in groovy script
I've created a groovy script for the new Jenkins Workflow Plugin, https://github.com/jenkinsci/workflow-plugin. I want it to send a mail to the user who started the job when it needs input for the next step. I've tried to search the API but I can't find anything about getting the users email address.

I would think of something like this.

```<code>import hudson.model.User
def user = User.current()
def mailAddress = user.getMailAddress()
</code>```

Is there a way to get the current Jenkins user' address in groovy?

答:
```<code>import hudson.tasks.Mailer;
import hudson.model.User;
import hudson.model.Cause;
import hudson.model.Cause.UserIdCause;

def cause = build.getCause(hudson.model.Cause$UserIdCause)
def id = cause.getUserId()
User u = User.get(id)
def umail = u.getProperty(Mailer.UserProperty.class)
print umail.getAddress()
</code>```

Body:
I've created a groovy script for the new Jenkins Workflow Plugin, https://github.com/jenkinsci/workflow-plugin. I want it to send a mail to the user who started the job when it needs input for the next step. I've tried to search the API but I can't find anything about getting the users email address.

I would think of something like this.

import hudson.model.User
def user = User.current()
def mailAddress = user.getMailAddress()

Is there a way to get the current Jenkins user' address in groovy?


答:
First of all you must resolve the problem of quotes, you couldn't use the double quotes multiple time in the same string :

```<code>"<div class="ExternalClass06EE5E42165840F48DFA193ACAD4F87A">aa</div>"
^___________^_____________________________________________^_________^
</code>```

Instead use single quotes :

```<code> "<div class='ExternalClass06EE5E42165840F48DFA193ACAD4F87A '>aa</div>"
</code>```

Then loop through the array and chnage the property you want :

```<code>for (var i in originaldata) {
   var temp_div = document.createElement('div'); //Create temporary div
   temp_div.innerHTML = originaldata[i].content; //Append the tag in the content to it

   originaldata[i].content = temp_div.textContent; //Get the text using 'textContent'
}
</code>```

var originaldata = [{
    "name": "john",
    "content": "
aa
"
  },
  {
    "name": "mary",
    "content": "
asd
"
  }
];

for (var i in originaldata) {
  var temp_div = document.createElement('div');
  temp_div.innerHTML = originaldata[i].content;

  originaldata[i].content = temp_div.textContent;
}

console.log(originaldata);```

Title: Array objects values remove unwanted string

Body:
First of all you must resolve the problem of quotes, you couldn't use the double quotes multiple time in the same string :

"<div class="ExternalClass06EE5E42165840F48DFA193ACAD4F87A">aa</div>"
^___________^_____________________________________________^_________^

Instead use single quotes :

 "<div class='ExternalClass06EE5E42165840F48DFA193ACAD4F87A '>aa</div>"

Then loop through the array and chnage the property you want :

for (var i in originaldata) {
   var temp_div = document.createElement('div'); //Create temporary div
   temp_div.innerHTML = originaldata[i].content; //Append the tag in the content to it

   originaldata[i].content = temp_div.textContent; //Get the text using 'textContent'
}

var originaldata = [{
    "name": "john",
    "content": "<div class='ExternalClass06EE5E42165840F48DFA193ACAD4F87A '>aa</div>"
  },
  {
    "name": "mary",
    "content": "<div class='ExternalClass3D5F8061F3DE49C4BC55A9CE0ADD6F9A '>asd</div>"
  }
];

for (var i in originaldata) {
  var temp_div = document.createElement('div');
  temp_div.innerHTML = originaldata[i].content;

  originaldata[i].content = temp_div.textContent;
}

console.log(originaldata);


问:
python 2.7 functools_lru_cache does not import although installed
When I try to import matplotlib I get an error

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/matplotlib/__init__.py", line 128, in <module>
  from matplotlib.rcsetup import defaultParams, validate_backend, cycler
  File "/usr/local/lib/python2.7/dist-packages/matplotlib/rcsetup.py", line 29, in <module>
    from matplotlib.fontconfig_pattern import parse_fontconfig_pattern
  File "/usr/local/lib/python2.7/dist-packages/matplotlib/fontconfig_pattern.py", line 32, in <module>
    from backports.functools_lru_cache import lru_cache
ImportError: No module named functools_lru_cache
</code>```

backports itself imports properly. When I try to install functools manually via

```<code>sudo pip install backports.functools_lru_cache
</code>```

I get info that

```<code>Requirement already satisfied: backports.functools_lru_cache in /usr/local/lib/python2.7/dist-packages
</code>```

Nevertheless when i try to

```<code>import backports.functools_lru_cache
</code>```

I get info that

```<code>ImportError: No module named functools_lru_cache
</code>```

System info
Ubuntu 16
Python 2.7.12
Pip 9.0.1

答:
I had the same problem and my solution was;

Download whl file from https://pypi.python.org/pypi/backports.functools_lru_cache/1.3

pip install

Body:
When I try to import matplotlib I get an error

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/matplotlib/__init__.py", line 128, in <module>
  from matplotlib.rcsetup import defaultParams, validate_backend, cycler
  File "/usr/local/lib/python2.7/dist-packages/matplotlib/rcsetup.py", line 29, in <module>
    from matplotlib.fontconfig_pattern import parse_fontconfig_pattern
  File "/usr/local/lib/python2.7/dist-packages/matplotlib/fontconfig_pattern.py", line 32, in <module>
    from backports.functools_lru_cache import lru_cache
ImportError: No module named functools_lru_cache

backports itself imports properly. When I try to install functools manually via

sudo pip install backports.functools_lru_cache

I get info that

Requirement already satisfied: backports.functools_lru_cache in /usr/local/lib/python2.7/dist-packages

Nevertheless when i try to

import backports.functools_lru_cache

I get info that

ImportError: No module named functools_lru_cache

System info
Ubuntu 16
Python 2.7.12
Pip 9.0.1


问:
Source Code Protection
When you compile a program to publish with Visual Studio 2010, does that have any advanced methods to keep your program being decompiled to source code? Are there any methods you would use to encrypt yoursource code before compiling?</p>

答: No, there's really no way to prevent a managed assembly from being decompiled back into source code. The best you can hope for is obfuscation, which can do quite a good job of making the decompiled code hard to understand.</p>

Title: Source Code Protection


问:
Update tensor with arrays in tensorflow
I have a 3-D tensor in which I want to update some values the same way as in this numpy code:

```<code>x_np = np.zeros((2,3,2))
updates_np = np.ones((2,2))
indices_1 = np.array([0, 1])
indices_2 = np.array([1, 1])

x_np[indices_1, indices_2, :] = updates_np
</code>```

and this is the result:

```<code>>>> x_np

array([[[ 0.,  0.],
        [ 1.,  1.],
        [ 0.,  0.]],

       [[ 0.,  0.],
        [ 1.,  1.],
        [ 0.,  0.]]])
</code>```

as you can I want to update full rows on the last dimension, so to do that I'm trying to use scatter_update (and I also tried with dynamic_stitch). But it seems that scatter_update doesn't accept more than one dimension as the updates indices.

How can I do this in tensorflow?

答:
I came with a solution which to me looks awful, so any improvements are welcome

```<code>sess = tf.InteractiveSession()
x = tf.zeros((2,3,2))
indices_1 = tf.constant([0, 1])
indices_2 = tf.constant([1, 1])
updates_tf = tf.ones((2, 2))

x_temp = tf.Variable(tf.reshape(x, [-1, 2]))

indices_flat = tf.shape(x)[1]*indices_1 + indices_2
sess.run(tf.initialize_all_variables())
print(sess.run(tf.reshape(tf.scatter_update(x_temp, indices_flat,  updates_tf), tf.shape(x))))
</code>```

Result

```<code>[[[ 0.  0.]
  [ 1.  1.]
  [ 0.  0.]]

 [[ 0.  0.]
  [ 1.  1.]
  [ 0.  0.]]]
</code>```

Title: Update tensor with arrays in tensorflow

Body:
I have a 3-D tensor in which I want to update some values the same way as in this numpy code:

x_np = np.zeros((2,3,2))
updates_np = np.ones((2,2))
indices_1 = np.array([0, 1])
indices_2 = np.array([1, 1])

x_np[indices_1, indices_2, :] = updates_np

and this is the result:

>>> x_np

array([[[ 0.,  0.],
        [ 1.,  1.],
        [ 0.,  0.]],

       [[ 0.,  0.],
        [ 1.,  1.],
        [ 0.,  0.]]])

as you can I want to update full rows on the last dimension, so to do that I'm trying to use scatter_update (and I also tried with dynamic_stitch). But it seems that scatter_update doesn't accept more than one dimension as the updates indices.

How can I do this in tensorflow?

Body:
I came with a solution which to me looks awful, so any improvements are welcome

sess = tf.InteractiveSession()
x = tf.zeros((2,3,2))
indices_1 = tf.constant([0, 1])
indices_2 = tf.constant([1, 1])
updates_tf = tf.ones((2, 2))

x_temp = tf.Variable(tf.reshape(x, [-1, 2]))

indices_flat = tf.shape(x)[1]*indices_1 + indices_2
sess.run(tf.initialize_all_variables())
print(sess.run(tf.reshape(tf.scatter_update(x_temp, indices_flat,  updates_tf), tf.shape(x))))

Result

[[[ 0.  0.]
  [ 1.  1.]
  [ 0.  0.]]

 [[ 0.  0.]
  [ 1.  1.]
  [ 0.  0.]]]