问:
PHP DOM in WordPress - add attribute in output buffer HTML
I want to make all input tags on product and cart page with class qty have type="number" and readonly="readonly" attributes through modifying DOM with PHP.

When I limit it to cart and product page, it "only" makes lazy load plugin and Autoptimize plugin stop working for these 2 pages, while other pages are fine. I can't spot any console errors, on admin pages as well.

When I allow it to run for every page, the following happens:

There are no errors in console on product and cart page.

Ajax request for Ajax add to cart plugin breaks.

I get multiple console errors which break layout of many admin pages, moving and hiding portions of content.

These output buffer modifications feel like hacking with resulting errors / incompatibilities. Could it be because of libxml_use_internal_errors(true); which hides warnings and doesn't actually fix anything?

Dom loadHTML doesn't work properly on a server

This is what I have in my functions.php:

```<code>add_action( 'template_redirect', 'acau_activate_buffer', 99999 );
function acau_activate_buffer() {
    // cart and product page only, WooCommerce required for below line to work, remove to reproduce issues without WooCommerce
    if ( ! is_cart() && ! is_product() ) return;
    ob_start();
}

add_action('shutdown', function() {
    // cart and product page only, WooCommerce required for below line to work, remove to reproduce issues without WooCommerce
    if ( ! is_cart() && ! is_product() ) return;
    $final = '';

    // Collect output from all previous buffers.
    $levels = ob_get_level();

    for ($i = 0; $i < $levels; $i++) {
        $final .= ob_get_clean();
    }

    echo apply_filters('acau_output', $final);

}, -99999);

// Filter final output.
add_filter('acau_output', function($output) {

    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    $dom->loadHTML(mb_convert_encoding($output, 'HTML-ENTITIES', 'UTF-8'));

    foreach ($dom->getElementsByTagName('input') as $node) {
        $classes = explode (' ', $node->getAttribute('class') );
        if ( in_array ( 'qty', $classes ) ) {
            $node->setAttribute('type', 'number');
            $node->setAttribute('readonly', 'readonly');
        }
    }
    $newHtml = $dom->saveHtml();
    return $newHtml;

});
</code>```

答:
I've found a solution to my issue, based on what Roland from nextendweb posted on WordPress support forums. He filed a bug report:

https://bugs.php.net/bug.php?id=76563

What he suggests would be in my case:

```<code>$final .= ob_get_contents();
ob_clean();
</code>```

instead of:

```<code>$final .= ob_get_clean();
</code>```

because it isn't working the same as it should.

Body:
I want to make all input tags on product and cart page with class qty have type="number" and readonly="readonly" attributes through modifying DOM with PHP.

When I limit it to cart and product page, it "only" makes lazy load plugin and Autoptimize plugin stop working for these 2 pages, while other pages are fine. I can't spot any console errors, on admin pages as well.

When I allow it to run for every page, the following happens:

There are no errors in console on product and cart page.

Ajax request for Ajax add to cart plugin breaks.

I get multiple console errors which break layout of many admin pages, moving and hiding portions of content.

These output buffer modifications feel like hacking with resulting errors / incompatibilities. Could it be because of libxml_use_internal_errors(true); which hides warnings and doesn't actually fix anything?

Dom loadHTML doesn't work properly on a server

This is what I have in my functions.php:

add_action( 'template_redirect', 'acau_activate_buffer', 99999 );
function acau_activate_buffer() {
    // cart and product page only, WooCommerce required for below line to work, remove to reproduce issues without WooCommerce
    if ( ! is_cart() && ! is_product() ) return;
    ob_start();
}

add_action('shutdown', function() {
    // cart and product page only, WooCommerce required for below line to work, remove to reproduce issues without WooCommerce
    if ( ! is_cart() && ! is_product() ) return;
    $final = '';

    // Collect output from all previous buffers.
    $levels = ob_get_level();

    for ($i = 0; $i < $levels; $i++) {
        $final .= ob_get_clean();
    }

    echo apply_filters('acau_output', $final);

}, -99999);

// Filter final output.
add_filter('acau_output', function($output) {

    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    $dom->loadHTML(mb_convert_encoding($output, 'HTML-ENTITIES', 'UTF-8'));

    foreach ($dom->getElementsByTagName('input') as $node) {
        $classes = explode (' ', $node->getAttribute('class') );
        if ( in_array ( 'qty', $classes ) ) {
            $node->setAttribute('type', 'number');
            $node->setAttribute('readonly', 'readonly');
        }
    }
    $newHtml = $dom->saveHtml();
    return $newHtml;

});

Body:
I've found a solution to my issue, based on what Roland from nextendweb posted on WordPress support forums. He filed a bug report:

https://bugs.php.net/bug.php?id=76563

What he suggests would be in my case:

$final .= ob_get_contents();
ob_clean();

instead of:

$final .= ob_get_clean();

because it isn't working the same as it should.


来源: stackexchange

问:
how to revert back to older vs of symfony?
I have a project directory:

~/traffic_2/phoenix$ the symfony version here is 1.4.11 because I tried to install symfony in ANOTHER project directory using the command:

```<code>~/traffic_2/elemental/webroot$ sudo pear install symfony/symfony
</code>```

so it updated to version 1.4.11 in directory ~/traffic_2/phoenix!

I want to revert back to my previous version of symfony 1.4.2 please in above dir???

please how do I do this??
~/traffic_2/phoenix$sudo pear install symfony/symfony-1.4.2 ?????
thank you

答: After uninstalling the previous package, it should be ok. Look here : How to install an older version of PHPUnit through PEAR?</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a project directory:

~/traffic_2/phoenix$ the symfony version here is 1.4.11 because I tried to install symfony in ANOTHER project directory using the command:

~/traffic_2/elemental/webroot$ sudo pear install symfony/symfony

so it updated to version 1.4.11 in directory ~/traffic_2/phoenix!

I want to revert back to my previous version of symfony 1.4.2 please in above dir???

please how do I do this??
~/traffic_2/phoenix$sudo pear install symfony/symfony-1.4.2 ?????
thank you


问:
Scala function assignment equivalent in C++
There's a special syntax in Scala that allows some sort of function "assignment" or return in 1 line. I was wondering if there's something equivalent in C++.

Scala example: def abs(x: Int) = if (x >= 0) x else -x

答:
You can use the ternary operator:

```<code>int xyz(int x) { return x >= 0 ? x : -x; }
</code>```

For further information please see here.

ContentLicense: CC BY-SA 4.0

Body:
You can use the ternary operator:

int xyz(int x) { return x >= 0 ? x : -x; }

For further information please see here.


问:
Is it possible to modify a range variable?
I need to solve a model in which I have an array with a size of 1..118 but I only want to solve it for some values (e.g. 1..9,11..60,62..115 and 117..118). The numbers that I excluded are the ones that I don't want to solve the problem for, because they will return a solution with no value and therefore are not of interest to me.

It's not possible for me to change the original array since I'll be using it to solve the relaxed version of the problem with the positions not taken before.

Is there any possible way of doing this?

答:
let me give you an example on how to set a range through flow control in OPL:

You have a first model sub.mod

```<code>int minOfx = ...;
int maxOfx = ...;
range r=minOfx..maxOfx;
dvar float x1 in r;
dvar float x2 in r;

maximize x2-x1;
subject to {

}

execute
{
writeln("x2-x1= ",x2-x1);
}
</code>```

and then you have your main model

```<code>main {
  var source = new IloOplModelSource("sub.mod");
  var cplex = new IloCplex();
  var def = new IloOplModelDefinition(source);

  for(var k=1;k<=10;k++)
  {
  var opl = new IloOplModel(def,cplex);

  var data2= new IloOplDataElements();
  data2.minOfx=(k-1)*(k-1);
  data2.maxOfx=k*k;
  opl.addDataSource(data2);
  opl.generate();

  if (cplex.solve()) {
     opl.postProcess();

  } else {
     writeln("No solution");
  }
 opl.end();
}

}
</code>```

When you run your main model you'll get

```<code>x2-x1= 1
x2-x1= 3
x2-x1= 5
x2-x1= 7
x2-x1= 9
x2-x1= 11
x2-x1= 13
x2-x1= 15
x2-x1= 17
x2-x1= 19
</code>```

Using flow control you can change some data in a model and that can change a range.

Body:
let me give you an example on how to set a range through flow control in OPL:

You have a first model sub.mod

int minOfx = ...;
int maxOfx = ...;
range r=minOfx..maxOfx;
dvar float x1 in r;
dvar float x2 in r;

maximize x2-x1;
subject to {

}

execute
{
writeln("x2-x1= ",x2-x1);
}

and then you have your main model

main {
  var source = new IloOplModelSource("sub.mod");
  var cplex = new IloCplex();
  var def = new IloOplModelDefinition(source);

  for(var k=1;k<=10;k++)
  {
  var opl = new IloOplModel(def,cplex);

  var data2= new IloOplDataElements();
  data2.minOfx=(k-1)*(k-1);
  data2.maxOfx=k*k;
  opl.addDataSource(data2);
  opl.generate();

  if (cplex.solve()) {
     opl.postProcess();

  } else {
     writeln("No solution");
  }
 opl.end();
}

}

When you run your main model you'll get

x2-x1= 1
x2-x1= 3
x2-x1= 5
x2-x1= 7
x2-x1= 9
x2-x1= 11
x2-x1= 13
x2-x1= 15
x2-x1= 17
x2-x1= 19

Using flow control you can change some data in a model and that can change a range.


问:
jQuery - issue with selecting which view to show based on screen size
I have implemented some jQuery in my rails app to change the nav items into a dropdown when the screen size is below 755px. I have it working 90%. I works when resizing and also for refresh. I have a problem when clicking any link, upon which it loads both views.

I found my current code here on StackOverflow. I suspect it has something to do with document.ready, but this is not my area of knowledge.

```<code>$(window).resize(function() {
  if ($(window).width() < 755) {
    $("#web").hide();
    $("#mob").show();
  }
  else{
    $("#web").show();
    $("#mob").hide();
  }
});

$(window).load(function() {
  if ($(window).width() < 755) {
    $("#web").hide();
    $("#mob").show();
  }
  else{
    $("#web").show();
    $("#mob").hide();
  }
});
</code>```

I would like to have it load the proper nav when clicking on any link. Thanks!

答:
Thanks Stephan Schrijver. I solved this with the following.</p>

```<code>@media only screen and (max-width: 754px) {
  .mob-nav {
    display: inline;
  }
  .web-nav {
    display: none;
  }
}

@media only screen and (min-width: 755px) {
  .mob-nav {
    display: none;
  }
  .web-nav {
    display: inline;
  }
}
</code>```

Body:
I have implemented some jQuery in my rails app to change the nav items into a dropdown when the screen size is below 755px. I have it working 90%. I works when resizing and also for refresh. I have a problem when clicking any link, upon which it loads both views.

I found my current code here on StackOverflow. I suspect it has something to do with document.ready, but this is not my area of knowledge.

$(window).resize(function() {
  if ($(window).width() < 755) {
    $("#web").hide();
    $("#mob").show();
  }
  else{
    $("#web").show();
    $("#mob").hide();
  }
});

$(window).load(function() {
  if ($(window).width() < 755) {
    $("#web").hide();
    $("#mob").show();
  }
  else{
    $("#web").show();
    $("#mob").hide();
  }
});

I would like to have it load the proper nav when clicking on any link. Thanks!

Body:
Thanks Stephan Schrijver. I solved this with the following.

@media only screen and (max-width: 754px) {
  .mob-nav {
    display: inline;
  }
  .web-nav {
    display: none;
  }
}

@media only screen and (min-width: 755px) {
  .mob-nav {
    display: none;
  }
  .web-nav {
    display: inline;
  }
}


问:
Problem building Tensorflow 13.1 from Source on OS X 10.11.6
I am trying to build tensorflow 13.1 from source on my Mac - OS X 10.11.6
I have tried with bazel 0.21 (macports), bazel 18.1 and bazel 15.2.

```<code>bazel-0.18.1-installer-darwin-x86_64.sh
bazel-0.15.2-installer-darwin-x86_64.sh
</code>```

The build of Tensorflow 13.1 with bazel 0.21 from macports built successfully.
Next I build a .whl file and installed it with pip 19.1 into my Anaconda 3.6 virtual environment.  The files for tensorflow in:
/Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages/tensorflow
are missing.  There are only include files.

When I try to import tensorflow into a python 3.6 shell, the command finishes instantly (without loading).
Clearly, something is wrong with the build, the installation or both
AttributeError: module 'tensorflow' has no attribute 'version'

```<code>$ port list bazel
bazel                          @0.21.0         devel/bazel

$ bazel version
WARNING: failed to raise resource limit 8 to 524288: Invalid argument
Starting local Bazel server and connecting to it...
INFO: Invocation ID: 0fad439c-f23b-48e3-81e5-5e56b1e6cf24
Build label: 0.21.0- (@non-git)
Build target: bazel-out/darwin-opt/bin/src/main/java/com/google/devtools/build/lib/bazel/BazelServer_deploy.jar
Build time: Wed Feb 27 15:35:45 2019 (1551281745)
Build timestamp: 1551281745
Build timestamp as int: 1551281745

$ pip --version
pip 19.1.1 from /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages/pip (python 3.6)

$ bazel build //tensorflow/tools/pip_package:build_pip_package

$ ./bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg

$sudo -H pip  install  /tmp/tensorflow_pkg/tensorflow-1.13.1-cp36-cp36m-macosx_10_7_x86_64.whl

$ source activate ai
(ai) MacBook-Pro:~ davidlaxer$ python
Python 3.6.7 |Anaconda, Inc.| (default, Oct 23 2018, 14:01:38)
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow
>>> print(tensorflow.__version__)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'tensorflow' has no attribute '__version__'
>>> quit()
(ai) MacBook-Pro:~ davidlaxer$ conda list tensorflow
# packages in environment at /Users/davidlaxer/anaconda/envs/ai:
#
# Name                    Version                   Build  Channel
tensorflow                1.13.1                    <pip>
tensorflow-estimator      1.13.0                    <pip>

(ai) MacBook-Pro:tensorflow davidlaxer$ which pip
/Users/davidlaxer/anaconda/envs/ai/bin/pip
(ai) MacBook-Pro:tensorflow davidlaxer$ sudo which pip
/Users/davidlaxer/anaconda/envs/ai/bin/pip
(ai) MacBook-Pro:tensorflow davidlaxer$  pip install /tmp/tensorflow_pkg/tensorflow-1.13.1-cp36-cp36m-macosx_10_7_x86_64.whl
Requirement already satisfied: tensorflow==1.13.1 from file:///tmp/tensorflow_pkg/tensorflow-1.13.1-cp36-cp36m-macosx_10_7_x86_64.whl in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (1.13.1)
Requirement already satisfied: six>=1.10.0 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorflow==1.13.1) (1.12.0)
Requirement already satisfied: grpcio>=1.8.6 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorflow==1.13.1) (1.12.1)
Requirement already satisfied: wheel>=0.26 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorflow==1.13.1) (0.33.2)
Requirement already satisfied: absl-py>=0.1.6 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorflow==1.13.1) (0.2.2)
Requirement already satisfied: protobuf>=3.6.1 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorflow==1.13.1) (3.6.1)
Requirement already satisfied: keras-applications>=1.0.6 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorflow==1.13.1) (1.0.6)
Requirement already satisfied: termcolor>=1.1.0 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorflow==1.13.1) (1.1.0)
Requirement already satisfied: gast>=0.2.0 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorflow==1.13.1) (0.2.0)
Requirement already satisfied: numpy>=1.13.3 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorflow==1.13.1) (1.16.3)
Requirement already satisfied: keras-preprocessing>=1.0.5 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorflow==1.13.1) (1.0.9)
Requirement already satisfied: tensorboard<1.14.0,>=1.13.0 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorflow==1.13.1) (1.13.1)
Requirement already satisfied: tensorflow-estimator<1.14.0rc0,>=1.13.0 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorflow==1.13.1) (1.13.0)
Requirement already satisfied: astor>=0.6.0 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorflow==1.13.1) (0.6.2)
Requirement already satisfied: setuptools in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from protobuf>=3.6.1->tensorflow==1.13.1) (41.0.1)
Requirement already satisfied: h5py in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from keras-applications>=1.0.6->tensorflow==1.13.1) (2.8.0)
Requirement already satisfied: werkzeug>=0.11.15 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorboard<1.14.0,>=1.13.0->tensorflow==1.13.1) (0.14.1)
Requirement already satisfied: markdown>=2.6.8 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorboard<1.14.0,>=1.13.0->tensorflow==1.13.1) (2.6.11)
Requirement already satisfied: mock>=2.0.0 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorflow-estimator<1.14.0rc0,>=1.13.0->tensorflow==1.13.1) (3.0.5)

</code>```

The directory for my virtual environment where my tensorfiles should live only has an include directory!

```<code>
(ai) MacBook-Pro:tensorflow davidlaxer$ ls -l
total 0
drwxr-xr-x  8 root  staff  272 May 10 02:07 include
</code>```

On Ubuntu, all the files are there!

```<code>
ubuntu@ip-10-0-1-233:~/anaconda/envs/ai/lib/python3.6/site-packages/tensorflow$ ls -l
total 16976
drwxrwxr-x  4 ubuntu ubuntu     4096 Jan 15 16:37 _api
drwxrwxr-x  2 ubuntu ubuntu     4096 Jan 15 16:37 aux-bin
drwxrwxr-x  5 ubuntu ubuntu     4096 Jan 15 16:37 compiler
drwxrwxr-x 98 ubuntu ubuntu     4096 Jan 15 16:37 contrib
drwxrwxr-x 12 ubuntu ubuntu     4096 Jan 15 16:37 core
drwxrwxr-x  4 ubuntu ubuntu     4096 Jan 15 16:37 examples
drwxrwxr-x  9 ubuntu ubuntu     4096 Jan 15 16:37 include
-rw-rw-r--  2 ubuntu ubuntu    29128 Nov 13 22:59 __init__.py
-rwxrwxr-x  2 ubuntu ubuntu 17307888 Nov 13 23:01 libtensorflow_framework.so
drwxrwxr-x  2 ubuntu ubuntu     4096 Jan 15 16:37 __pycache__
drwxrwxr-x 26 ubuntu ubuntu     4096 Jan 15 16:37 python
drwxrwxr-x  7 ubuntu ubuntu     4096 Jan 15 16:37 tools

</code>```

答:
It seems that Tensorflow 13.1 now requires macOS 10.12.6 (Sierra) or later (64=bit).
Tensorflow 12.0 does still work on OS X 10.11.

https://github.com/tensorflow/tensorflow/issues/28839

E.g. Here's what happens building tensorflow 13.1 on OS X 10.11.6 after correcting the Subgraph::Indentity initializer

```<code>ERROR: /Users/davidlaxer/tensorflow/tensorflow/contrib/ignite/BUILD:148:1: Executing genrule //tensorflow/contrib/ignite:gen_igfs_ops_pygenrule failed (Trace/breakpoint trap): bash failed: error executing command /bin/bash -c ... (remaining 1 argument(s) skipped)
dyld: lazy symbol binding failed: Symbol not found: _clock_gettime
  Referenced from: /private/var/tmp/_bazel_davidlaxer/f9fe21ec5c09226e5ca0dce9376abe82/execroot/org_tensorflow/bazel-out/host/bin/tensorflow/contrib/ignite/../../../_solib_darwin_x86_64/_U_S_Stensorflow_Scontrib_Signite_Cgen_Ugen_Uigfs_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so (which was built for Mac OS X 10.12)
  Expected in: /usr/lib/libSystem.B.dylib

dyld: Symbol not found: _clock_gettime
  Referenced from: /private/var/tmp/_bazel_davidlaxer/f9fe21ec5c09226e5ca0dce9376abe82/execroot/org_tensorflow/bazel-out/host/bin/tensorflow/contrib/ignite/../../../_solib_darwin_x86_64/_U_S_Stensorflow_Scontrib_Signite_Cgen_Ugen_Uigfs_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so (which was built for Mac OS X 10.12)
  Expected in: /usr/lib/libSystem.B.dylib
</code>```

/bin/bash: line 1: 53224 Trace/BPT trap: 5       baze

https://github.com/tensorflow/tensorflow/issues/28839-out/host/bin/tensorflow/contrib/ignite/gen_gen_igfs_ops_py_wrappers_cc , '' 0 0 > bazel-out/darwin-opt/genfiles/tensorflow/contrib/ignite/python/ops/gen_igfs_ops.py
Target //tensorflow/tools/pip_package:build_pip_package failed to build
Use --verbose_failures to see the command lines of failed build steps.
INFO: Elapsed time: 3007.455s, Critical Path: 200.07s
INFO: 2483 processes: 2483 local.
FAILED: Build did NOT complete successfully

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

Body:
I am trying to build tensorflow 13.1 from source on my Mac - OS X 10.11.6
I have tried with bazel 0.21 (macports), bazel 18.1 and bazel 15.2.

bazel-0.18.1-installer-darwin-x86_64.sh
bazel-0.15.2-installer-darwin-x86_64.sh

The build of Tensorflow 13.1 with bazel 0.21 from macports built successfully.
Next I build a .whl file and installed it with pip 19.1 into my Anaconda 3.6 virtual environment.  The files for tensorflow in:
/Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages/tensorflow
are missing.  There are only include files.

When I try to import tensorflow into a python 3.6 shell, the command finishes instantly (without loading).
Clearly, something is wrong with the build, the installation or both
AttributeError: module 'tensorflow' has no attribute 'version'

$ port list bazel
bazel                          @0.21.0         devel/bazel

$ bazel version
WARNING: failed to raise resource limit 8 to 524288: Invalid argument
Starting local Bazel server and connecting to it...
INFO: Invocation ID: 0fad439c-f23b-48e3-81e5-5e56b1e6cf24
Build label: 0.21.0- (@non-git)
Build target: bazel-out/darwin-opt/bin/src/main/java/com/google/devtools/build/lib/bazel/BazelServer_deploy.jar
Build time: Wed Feb 27 15:35:45 2019 (1551281745)
Build timestamp: 1551281745
Build timestamp as int: 1551281745

$ pip --version
pip 19.1.1 from /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages/pip (python 3.6)

$ bazel build //tensorflow/tools/pip_package:build_pip_package

$ ./bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg

$sudo -H pip  install  /tmp/tensorflow_pkg/tensorflow-1.13.1-cp36-cp36m-macosx_10_7_x86_64.whl

$ source activate ai
(ai) MacBook-Pro:~ davidlaxer$ python
Python 3.6.7 |Anaconda, Inc.| (default, Oct 23 2018, 14:01:38)
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow
>>> print(tensorflow.__version__)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'tensorflow' has no attribute '__version__'
>>> quit()
(ai) MacBook-Pro:~ davidlaxer$ conda list tensorflow
# packages in environment at /Users/davidlaxer/anaconda/envs/ai:
#
# Name                    Version                   Build  Channel
tensorflow                1.13.1                    <pip>
tensorflow-estimator      1.13.0                    <pip>

(ai) MacBook-Pro:tensorflow davidlaxer$ which pip
/Users/davidlaxer/anaconda/envs/ai/bin/pip
(ai) MacBook-Pro:tensorflow davidlaxer$ sudo which pip
/Users/davidlaxer/anaconda/envs/ai/bin/pip
(ai) MacBook-Pro:tensorflow davidlaxer$  pip install /tmp/tensorflow_pkg/tensorflow-1.13.1-cp36-cp36m-macosx_10_7_x86_64.whl
Requirement already satisfied: tensorflow==1.13.1 from file:///tmp/tensorflow_pkg/tensorflow-1.13.1-cp36-cp36m-macosx_10_7_x86_64.whl in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (1.13.1)
Requirement already satisfied: six>=1.10.0 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorflow==1.13.1) (1.12.0)
Requirement already satisfied: grpcio>=1.8.6 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorflow==1.13.1) (1.12.1)
Requirement already satisfied: wheel>=0.26 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorflow==1.13.1) (0.33.2)
Requirement already satisfied: absl-py>=0.1.6 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorflow==1.13.1) (0.2.2)
Requirement already satisfied: protobuf>=3.6.1 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorflow==1.13.1) (3.6.1)
Requirement already satisfied: keras-applications>=1.0.6 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorflow==1.13.1) (1.0.6)
Requirement already satisfied: termcolor>=1.1.0 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorflow==1.13.1) (1.1.0)
Requirement already satisfied: gast>=0.2.0 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorflow==1.13.1) (0.2.0)
Requirement already satisfied: numpy>=1.13.3 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorflow==1.13.1) (1.16.3)
Requirement already satisfied: keras-preprocessing>=1.0.5 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorflow==1.13.1) (1.0.9)
Requirement already satisfied: tensorboard<1.14.0,>=1.13.0 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorflow==1.13.1) (1.13.1)
Requirement already satisfied: tensorflow-estimator<1.14.0rc0,>=1.13.0 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorflow==1.13.1) (1.13.0)
Requirement already satisfied: astor>=0.6.0 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorflow==1.13.1) (0.6.2)
Requirement already satisfied: setuptools in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from protobuf>=3.6.1->tensorflow==1.13.1) (41.0.1)
Requirement already satisfied: h5py in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from keras-applications>=1.0.6->tensorflow==1.13.1) (2.8.0)
Requirement already satisfied: werkzeug>=0.11.15 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorboard<1.14.0,>=1.13.0->tensorflow==1.13.1) (0.14.1)
Requirement already satisfied: markdown>=2.6.8 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorboard<1.14.0,>=1.13.0->tensorflow==1.13.1) (2.6.11)
Requirement already satisfied: mock>=2.0.0 in /Users/davidlaxer/anaconda/envs/ai/lib/python3.6/site-packages (from tensorflow-estimator<1.14.0rc0,>=1.13.0->tensorflow==1.13.1) (3.0.5)

The directory for my virtual environment where my tensorfiles should live only has an include directory!

(ai) MacBook-Pro:tensorflow davidlaxer$ ls -l
total 0
drwxr-xr-x  8 root  staff  272 May 10 02:07 include

On Ubuntu, all the files are there!

ubuntu@ip-10-0-1-233:~/anaconda/envs/ai/lib/python3.6/site-packages/tensorflow$ ls -l
total 16976
drwxrwxr-x  4 ubuntu ubuntu     4096 Jan 15 16:37 _api
drwxrwxr-x  2 ubuntu ubuntu     4096 Jan 15 16:37 aux-bin
drwxrwxr-x  5 ubuntu ubuntu     4096 Jan 15 16:37 compiler
drwxrwxr-x 98 ubuntu ubuntu     4096 Jan 15 16:37 contrib
drwxrwxr-x 12 ubuntu ubuntu     4096 Jan 15 16:37 core
drwxrwxr-x  4 ubuntu ubuntu     4096 Jan 15 16:37 examples
drwxrwxr-x  9 ubuntu ubuntu     4096 Jan 15 16:37 include
-rw-rw-r--  2 ubuntu ubuntu    29128 Nov 13 22:59 __init__.py
-rwxrwxr-x  2 ubuntu ubuntu 17307888 Nov 13 23:01 libtensorflow_framework.so
drwxrwxr-x  2 ubuntu ubuntu     4096 Jan 15 16:37 __pycache__
drwxrwxr-x 26 ubuntu ubuntu     4096 Jan 15 16:37 python
drwxrwxr-x  7 ubuntu ubuntu     4096 Jan 15 16:37 tools

Body:
It seems that Tensorflow 13.1 now requires macOS 10.12.6 (Sierra) or later (64=bit).
Tensorflow 12.0 does still work on OS X 10.11.

https://github.com/tensorflow/tensorflow/issues/28839

E.g. Here's what happens building tensorflow 13.1 on OS X 10.11.6 after correcting the Subgraph::Indentity initializer

ERROR: /Users/davidlaxer/tensorflow/tensorflow/contrib/ignite/BUILD:148:1: Executing genrule //tensorflow/contrib/ignite:gen_igfs_ops_pygenrule failed (Trace/breakpoint trap): bash failed: error executing command /bin/bash -c ... (remaining 1 argument(s) skipped)
dyld: lazy symbol binding failed: Symbol not found: _clock_gettime
  Referenced from: /private/var/tmp/_bazel_davidlaxer/f9fe21ec5c09226e5ca0dce9376abe82/execroot/org_tensorflow/bazel-out/host/bin/tensorflow/contrib/ignite/../../../_solib_darwin_x86_64/_U_S_Stensorflow_Scontrib_Signite_Cgen_Ugen_Uigfs_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so (which was built for Mac OS X 10.12)
  Expected in: /usr/lib/libSystem.B.dylib

dyld: Symbol not found: _clock_gettime
  Referenced from: /private/var/tmp/_bazel_davidlaxer/f9fe21ec5c09226e5ca0dce9376abe82/execroot/org_tensorflow/bazel-out/host/bin/tensorflow/contrib/ignite/../../../_solib_darwin_x86_64/_U_S_Stensorflow_Scontrib_Signite_Cgen_Ugen_Uigfs_Uops_Upy_Uwrappers_Ucc___Utensorflow/libtensorflow_framework.so (which was built for Mac OS X 10.12)
  Expected in: /usr/lib/libSystem.B.dylib

/bin/bash: line 1: 53224 Trace/BPT trap: 5       baze

https://github.com/tensorflow/tensorflow/issues/28839-out/host/bin/tensorflow/contrib/ignite/gen_gen_igfs_ops_py_wrappers_cc , '' 0 0 > bazel-out/darwin-opt/genfiles/tensorflow/contrib/ignite/python/ops/gen_igfs_ops.py
Target //tensorflow/tools/pip_package:build_pip_package failed to build
Use --verbose_failures to see the command lines of failed build steps.
INFO: Elapsed time: 3007.455s, Critical Path: 200.07s
INFO: 2483 processes: 2483 local.
FAILED: Build did NOT complete successfully


问:
Find duplicates in Laravel Eloquent
The following code I have on the controller is below.

public function add(Request $request)
{
    $request->validate([
        'userSelected' => 'required',
        'projectSelected' => 'required',
    ]);

    $researcherToProject = new ProjectResearchers();
    $researcherToProject->user_id = $request->userSelected;
    $researcherToProject->project_id = $request->projectSelected;
    $researcherToProject->created_at = Carbon::now();
    $researcherToProject->updated_at = Carbon::now();
    $researcherToProject->save();

    return new ProjectsResearchersResource($researcherToProject);
}
```

Should I make another validation or create a function?

Ex: I create a user id "5" with project id "13" and user id "2" with project id "17". If I try creating again a user id "5" with project id "13" it allows me, so I get two times the same data in the database. How do I avoid duplicate entries?

答:
Additionaly to @nakov answer:

firstOrCreate() can combine 2 ways and looks cleaner:

```<code>public function add(Request $request){
    $request->validate([
        'userSelected' => 'required',
        'projectSelected' => 'required',
    ]);

    $researcherToProject = ProjectResearchers::firstOrCreate([
        'user_id' => $request->userSelected,
        'project_id' => $request->projectSelected
    ]);

    $researcherToProject->created_at = Carbon::now();
    $researcherToProject->updated_at = Carbon::now();
    $researcherToProject->save();

    return new ProjectsResearchersResource($researcherToProject);
}
</code>```

Or if you don't want to update:

```<code>public function add(Request $request){
    $request->validate([
        'userSelected' => 'required',
        'projectSelected' => 'required',
    ]);

    $researcherToProject = ProjectResearchers::firstOrCreate([
        'user_id' => $request->userSelected,
        'project_id' => $request->projectSelected
    ]);

    if(!$researcherToProject->id){
        $researcherToProject->created_at = Carbon::now();
        $researcherToProject->updated_at = Carbon::now();
        $researcherToProject->save();
    }

    return new ProjectsResearchersResource($researcherToProject);
}
</code>```

Title: Find duplicates in Laravel Eloquent

Body:
The following code I have on the controller is below.

public function add(Request $request)
{
    $request->validate([
        'userSelected' => 'required',
        'projectSelected' => 'required',
    ]);

    $researcherToProject = new ProjectResearchers();
    $researcherToProject->user_id = $request->userSelected;
    $researcherToProject->project_id = $request->projectSelected;
    $researcherToProject->created_at = Carbon::now();
    $researcherToProject->updated_at = Carbon::now();
    $researcherToProject->save();

    return new ProjectsResearchersResource($researcherToProject);
}

Should I make another validation or create a function?

Ex: I create a user id "5" with project id "13" and user id "2" with project id "17". If I try creating again a user id "5" with project id "13" it allows me, so I get two times the same data in the database. How do I avoid duplicate entries?

Body:
Additionaly to @nakov answer:

firstOrCreate() can combine 2 ways and looks cleaner:

public function add(Request $request){
    $request->validate([
        'userSelected' => 'required',
        'projectSelected' => 'required',
    ]);

    $researcherToProject = ProjectResearchers::firstOrCreate([
        'user_id' => $request->userSelected,
        'project_id' => $request->projectSelected
    ]);

    $researcherToProject->created_at = Carbon::now();
    $researcherToProject->updated_at = Carbon::now();
    $researcherToProject->save();

    return new ProjectsResearchersResource($researcherToProject);
}

Or if you don't want to update:

public function add(Request $request){
    $request->validate([
        'userSelected' => 'required',
        'projectSelected' => 'required',
    ]);

    $researcherToProject = ProjectResearchers::firstOrCreate([
        'user_id' => $request->userSelected,
        'project_id' => $request->projectSelected
    ]);

    if(!$researcherToProject->id){
        $researcherToProject->created_at = Carbon::now();
        $researcherToProject->updated_at = Carbon::now();
        $researcherToProject->save();
    }

    return new ProjectsResearchersResource($researcherToProject);
}


问:
Issue about Schema.xml uniqueKey field

Possible Duplicate:

  Solr: QueryElevationComponent requires StrField uniqueKeyField error

I hava configured the schema.xml with different field like

```<code><fields>
    <field name="id" type="int" indexed="true" stored="true" required="true" />
</fields>
<uniqueKey>id</uniqueKey>
</code>```

when I run solr service it gives me the error like uniquekey field must be string then after I change the field type int to string it's working fine

```<code><fields>
    <field name="id" type="string" indexed="true" stored="true" required="true" />
</fields>
<uniqueKey>id</uniqueKey>
</code>```

but i want to uniquekey in int type.

HTTP Status 500 - Severe errors in solr configuration. Check your log
  files for more detailed information on what may be wrong. If you want
  solr to continue after configuration errors, change:
  false in null
  ------------------------------------------------------------- org.apache.solr.common.SolrException: QueryElevationComponent requires
  the schema to have a uniqueKeyField implemented using StrField at
  org.apache.solr.handler.component.QueryElevationComponent.inform(QueryElevationComponent.java:157)
  at
  org.apache.solr.core.SolrResourceLoader.inform(SolrResourceLoader.java:508)
  at org.apache.solr.core.SolrCore.(SolrCore.java:588) at
  org.apache.solr.core.CoreContainer$Initializer.initialize(CoreContainer.java:137)
  at
  org.apache.solr.servlet.SolrDispatchFilter.init(SolrDispatchFilter.java:83)
  at
  org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:295)
  at
  org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:422)
  at
  org.apache.catalina.core.ApplicationFilterConfig.(ApplicationFilterConfig.java:115)
  at
  org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4071)
  at
  org.apache.catalina.core.StandardContext.start(StandardContext.java:4725)
  at
  org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:799)
  at
  org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:779)
  at
  org.apache.catalina.core.StandardHost.addChild(StandardHost.java:601)
  at
  org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:943)
  at
  org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:778)
  at
  org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:504)
  at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1315)
  at
  org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:324)
  at
  org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:142)
  at
  org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1061)
  at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
  at
  org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
  at
  org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
  at
  org.apache.catalina.core.StandardService.start(StandardService.java:525)
  at
  org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
  at org.apache.catalina.startup.Catalina.start(Catalina.java:595) at
  sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
  sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
  java.lang.reflect.Method.invoke(Unknown Source) at
  org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289) at
  org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)

答: Just as the error says, the QueryElevationComponent needs a unique key of type string. This is documented.</p>

Title: Issue about Schema.xml uniqueKey field

Body:
Possible Duplicate:

  Solr: QueryElevationComponent requires StrField uniqueKeyField error

I hava configured the schema.xml with different field like

<fields>
    <field name="id" type="int" indexed="true" stored="true" required="true" />
</fields>
<uniqueKey>id</uniqueKey>

when I run solr service it gives me the error like uniquekey field must be string then after I change the field type int to string it's working fine

<fields>
    <field name="id" type="string" indexed="true" stored="true" required="true" />
</fields>
<uniqueKey>id</uniqueKey>

but i want to uniquekey in int type.

HTTP Status 500 - Severe errors in solr configuration. Check your log
  files for more detailed information on what may be wrong. If you want
  solr to continue after configuration errors, change:
  false in null
  ------------------------------------------------------------- org.apache.solr.common.SolrException: QueryElevationComponent requires
  the schema to have a uniqueKeyField implemented using StrField at
  org.apache.solr.handler.component.QueryElevationComponent.inform(QueryElevationComponent.java:157)
  at
  org.apache.solr.core.SolrResourceLoader.inform(SolrResourceLoader.java:508)
  at org.apache.solr.core.SolrCore.(SolrCore.java:588) at
  org.apache.solr.core.CoreContainer$Initializer.initialize(CoreContainer.java:137)
  at
  org.apache.solr.servlet.SolrDispatchFilter.init(SolrDispatchFilter.java:83)
  at
  org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:295)
  at
  org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:422)
  at
  org.apache.catalina.core.ApplicationFilterConfig.(ApplicationFilterConfig.java:115)
  at
  org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4071)
  at
  org.apache.catalina.core.StandardContext.start(StandardContext.java:4725)
  at
  org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:799)
  at
  org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:779)
  at
  org.apache.catalina.core.StandardHost.addChild(StandardHost.java:601)
  at
  org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:943)
  at
  org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:778)
  at
  org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:504)
  at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1315)
  at
  org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:324)
  at
  org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:142)
  at
  org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1061)
  at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
  at
  org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
  at
  org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
  at
  org.apache.catalina.core.StandardService.start(StandardService.java:525)
  at
  org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
  at org.apache.catalina.startup.Catalina.start(Catalina.java:595) at
  sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
  sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
  java.lang.reflect.Method.invoke(Unknown Source) at
  org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289) at
  org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)


问:
Delphi Calculate age of person from TDateEdit component
I have a very simple form with a TDateEdit, TButton and TLabel component.

What is the best way to get the age of someone if the date given is their birthdate? How would someone do this in Delphi from the TDateEdit component and then display the age within the label?

Is there maybe a built in function or something I can use to get the age of someone from their date of birth in the component? I'm looking for the simplest, easiest and best way to do this.

答:
I prefer Ian Boyd's answer, but for those that insist that YearsBetween is the way to go, here's an alternative.

If Y is the result from YearsBetween, then the proper result is either Y or Y+1.  This routine calls YearsBetween and returns Y+1.  Then it uses IncYear to see if the answer is too big.  If it is, it returns Y.

This might seem like it's simpler, but behind the scenes there is a lot more work going on.  Ian Boyd's answer is the one you should use.

```<code>function AgeInCompleteYears ( const nBirthDate   : tDateTime;
                              const nCurrentDate : tDateTime  ) : integer;
begin
  Result := 1 + DateUtils.YearsBetween ( nCurrentDate, nBirthDate );
  if DateUtils.IncYear ( nBirthDate, Result ) > nCurrentDate then
    dec ( Result );
end;
</code>```

Body:
I prefer Ian Boyd's answer, but for those that insist that YearsBetween is the way to go, here's an alternative.

If Y is the result from YearsBetween, then the proper result is either Y or Y+1.  This routine calls YearsBetween and returns Y+1.  Then it uses IncYear to see if the answer is too big.  If it is, it returns Y.

This might seem like it's simpler, but behind the scenes there is a lot more work going on.  Ian Boyd's answer is the one you should use.

function AgeInCompleteYears ( const nBirthDate   : tDateTime;
                              const nCurrentDate : tDateTime  ) : integer;
begin
  Result := 1 + DateUtils.YearsBetween ( nCurrentDate, nBirthDate );
  if DateUtils.IncYear ( nBirthDate, Result ) > nCurrentDate then
    dec ( Result );
end;


问:
RegEx for extracting placeholder matches
I have this string

template = "Hello my name is <name>, I'm <age>."
```

<p>And I want to test if my strings match that template and anything can be in place of the placeholders. The placeholders start and end with brackets like this <code><place holder here></code>. E.g this string would match</p>

<pre class="lang-py prettyprint-override"><code>string = "Hello my name is John Doe, I'm 30 years old."
</code>```

I also want to extract parts of the string that substitute the placeholders. For the example above, I want to get the list:

['John Doe', '30 years old']
```

I'm able to extract the placeholders of the template using the pattern <(.*?)> for regex, but I'm currently stuck on how to extract the actual substitutions from the string. I need a generic approach and I don't want to hardcode the pattern to match the full template because I have many templates to check. Is there a clever way to do this?

答:
If the desired outputs are followed by exact punctuation mentioned in the question, we can simply use an expression similar to:

```<code>is\s(.+?),|([0-9].+)\.
</code>```

DEMO

Test

```<code># coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"is\s(.+?),|([0-9].+)\."

test_str = "Hello my name is John Doe, I'm 30 years old."

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
</code>```

Body:
I have this string

template = "Hello my name is <name>, I'm <age>."

And I want to test if my strings match that template and anything can be in place of the placeholders. The placeholders start and end with brackets like this <place holder here>. E.g this string would match

string = "Hello my name is John Doe, I'm 30 years old."

I also want to extract parts of the string that substitute the placeholders. For the example above, I want to get the list:

['John Doe', '30 years old']

I'm able to extract the placeholders of the template using the pattern <(.*?)> for regex, but I'm currently stuck on how to extract the actual substitutions from the string. I need a generic approach and I don't want to hardcode the pattern to match the full template because I have many templates to check. Is there a clever way to do this?

Body:
If the desired outputs are followed by exact punctuation mentioned in the question, we can simply use an expression similar to:

is\s(.+?),|([0-9].+)\.

DEMO

Test

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"is\s(.+?),|([0-9].+)\."

test_str = "Hello my name is John Doe, I'm 30 years old."

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.


问:
Azure Functions (C#): get time zone ids (NodaTime)
I have an Azure Function that is time triggered. The Azure Function starts at every occasion when it is somewhere 00:00 am (local time). What I would like to achieve is to find the time zone strings (e.g. Europe/London) for the time zones where it is currently 00:00 am when the Azure Function is running.

I.e., I provide an UTC value and it provides me all time zone ids where it is currently 00:00 am local time.

How can I achieve that using NodaTime?

答:
A slightly simpler version than yours, if you always want to check for midnight:

```<code>static List<string> GetTimeZonesAtMidnight(Instant instant) =>
    // Extension method in NodaTime.Extensions.DateTimeZoneProviderExtensions
    DateTimeZoneProviders.Tzdb.GetAllZones()
        .Where(zone => instant.InZone(zone).TimeOfDay == LocalTime.Midnight)
        .Select(zone => zone.Id)
        .ToList();
</code>```

If you need to check for non-midnight values, pass in a LocalTime:

```<code>static List<string> GetTimeZonesAtMidnight(Instant instant, LocalTime timeOfDay) =>
    // Extension method in NodaTime.Extensions.DateTimeZoneProviderExtensions
    DateTimeZoneProviders.Tzdb.GetAllZones()
        .Where(zone => instant.InZone(zone).TimeOfDay == timeOfDay)
        .Select(zone => zone.Id)
        .ToList();
</code>```

Body:
A slightly simpler version than yours, if you always want to check for midnight:

static List<string> GetTimeZonesAtMidnight(Instant instant) =>
    // Extension method in NodaTime.Extensions.DateTimeZoneProviderExtensions
    DateTimeZoneProviders.Tzdb.GetAllZones()
        .Where(zone => instant.InZone(zone).TimeOfDay == LocalTime.Midnight)
        .Select(zone => zone.Id)
        .ToList();

If you need to check for non-midnight values, pass in a LocalTime:

static List<string> GetTimeZonesAtMidnight(Instant instant, LocalTime timeOfDay) =>
    // Extension method in NodaTime.Extensions.DateTimeZoneProviderExtensions
    DateTimeZoneProviders.Tzdb.GetAllZones()
        .Where(zone => instant.InZone(zone).TimeOfDay == timeOfDay)
        .Select(zone => zone.Id)
        .ToList();


问:
resource for practical javascript exercise
I am beginner to webprogramming &  Javascript. I have went through few tutorials and learned the basics. Could someone suggest me the best resource with practical exercise with solutions.

I found "pagetutor.com" which has practical javascript exercises, but it's paid! Please
suggest any paid sites too which is really worth for practical learning.

答:
Eloquent JavaScript is an "interactive tutorial" that embeds an editor directly into its pages, enabling you to test and experiment with its many examples.

Learning Advanced JavaScript provides a series of examples intended to enable the learner to understand Prototype.js's .bind method.  Examples can be edited to allow the reader to experiment with them.

Admittedly, neither of these options actually provide an answer to the question, as they are not really "exercises" so much as interactive tutorials.  But they may be of some value nonetheless.


问:
How do I create multiple shapes relative to each other in kivy?
I want to be able to create multiple shapes on my canvas and have them evenly spaced out from each other. I would also like to have the shapes start a new line once they reach the end of the screen.

Heres the code I have now:

```<code>def draw_streak(self, obj):
        name = obj.text
        can = self.root.get_screen("three")

        with open("streak.json", "r") as file:
            read = json.load(file)

        for key in read.keys():
            if key == name:
                with open("streak.json", "r+") as f:
                    data = json.load(f)

                get_score = data.get(key, {}).get('score')

                for x in range(get_score):
                    with can.ids.my_box.canvas:
                        Color(0, 1, 0, .75, mode='rgba')
                        Rectangle(pos=can.pos, size=(30,30))
</code>```

if get_score was 10, then I would like 10 rectangles to be drawn. Right now when I run the program only one rectangle is drawn. I believe multiple are being drawn but they just overlap eachother.

EDIT

This is the kv code:

```<code><ScreenThree>
    id: screen_three
    name: "three"
    on_leave: my_box.canvas.clear()
    on_leave: selected_streak.canvas.clear()
    ...
        BoxLayout:
            id: my_box
            orientation: "vertical"
</code>```

my_box is just the id for the BoxLayout

答:
pos[0], pos[1], size[0], size[1]

what does the 0 and 1 in rect.size and new_pos do?

Kivy Widget » pos

```<code>pos
</code>```

Position of the widget.

pos is a ReferenceListProperty of (x, y)
  properties.

The pos contains the x and y coordinates of a widget's position. pos[0] refers to the x coordinate, and pos[1] refers to the y coordinate.

Kivy Widget » size

```<code>size
</code>```

Size of the widget.

size is a ReferenceListProperty of (width, height)
  properties.

The size contains the width and height of a widget. size[0] refers to the width and size[1] refers to the height.

Create multiple shapes

To prevent the rectangles from overlapping, save the starting position and increment it after drawing each rectangle.

Snippets

The following snippets add rectangles diagonally.

```<code>    new_pos = can.pos
    for x in range(get_score):
        with can.ids.my_box.canvas:
            Color(0, 1, 0, .75, mode='rgba')
            rect = Rectangle(pos=new_pos, size=(30, 30))
        new_pos[0] += rect.size[0]
        new_pos[1] += rect.size[1]
</code>```

Output

Body:
I want to be able to create multiple shapes on my canvas and have them evenly spaced out from each other. I would also like to have the shapes start a new line once they reach the end of the screen.

Heres the code I have now:

def draw_streak(self, obj):
        name = obj.text
        can = self.root.get_screen("three")

        with open("streak.json", "r") as file:
            read = json.load(file)

        for key in read.keys():
            if key == name:
                with open("streak.json", "r+") as f:
                    data = json.load(f)

                get_score = data.get(key, {}).get('score')

                for x in range(get_score):
                    with can.ids.my_box.canvas:
                        Color(0, 1, 0, .75, mode='rgba')
                        Rectangle(pos=can.pos, size=(30,30))

if get_score was 10, then I would like 10 rectangles to be drawn. Right now when I run the program only one rectangle is drawn. I believe multiple are being drawn but they just overlap eachother.

EDIT

This is the kv code:

<ScreenThree>
    id: screen_three
    name: "three"
    on_leave: my_box.canvas.clear()
    on_leave: selected_streak.canvas.clear()
    ...
        BoxLayout:
            id: my_box
            orientation: "vertical"

my_box is just the id for the BoxLayout

Body:
pos[0], pos[1], size[0], size[1]

what does the 0 and 1 in rect.size and new_pos do?

Kivy Widget » pos

pos

Position of the widget.

pos is a ReferenceListProperty of (x, y)
  properties.

The pos contains the x and y coordinates of a widget's position. pos[0] refers to the x coordinate, and pos[1] refers to the y coordinate.

Kivy Widget » size

size

Size of the widget.

size is a ReferenceListProperty of (width, height)
  properties.

The size contains the width and height of a widget. size[0] refers to the width and size[1] refers to the height.

Create multiple shapes

To prevent the rectangles from overlapping, save the starting position and increment it after drawing each rectangle.

Snippets

The following snippets add rectangles diagonally.

    new_pos = can.pos
    for x in range(get_score):
        with can.ids.my_box.canvas:
            Color(0, 1, 0, .75, mode='rgba')
            rect = Rectangle(pos=new_pos, size=(30, 30))
        new_pos[0] += rect.size[0]
        new_pos[1] += rect.size[1]

Output


问:
Login even after wrong creditionals flutter firebase
i get navigate to the home page even i entered the wrong credentials. i get the error that 'no user fond' but how to stop it.</p>

```<code>signIn() async {
    if (formkey.currentState.validate()) {
        formkey.currentState.save();
        try {
            _auth.signInWithEmailAndPassword(email: email, password: password);
            Navigator.push(context, MaterialPageRoute(builder: (context)=> Home()));
        } catch (e) {
            print(e.message);
        }
    }
}
</code>```

答:
When I run this code:

```<code>try {
  await FirebaseAuth.instance.signInWithEmailAndPassword(email: "nope@stackhack.com", password: "secret");
  print("Signed in");
}
catch (e) {
  print(e);
}
</code>```

I get the error printed, and not the "Signed in" message. The error contains a code property, which has a value "ERROR_USER_NOT_FOUND". So to respond to this specific error, I could do something like:

```<code>if (e.code == "ERROR_USER_NOT_FOUND") {
  print("User not found");
}
</code>```

Body:
i get navigate to the home page even i entered the wrong credentials. i get the error that 'no user fond' but how to stop it.

signIn() async {
    if (formkey.currentState.validate()) {
        formkey.currentState.save();
        try {
            _auth.signInWithEmailAndPassword(email: email, password: password);
            Navigator.push(context, MaterialPageRoute(builder: (context)=> Home()));
        } catch (e) {
            print(e.message);
        }
    }
}

Body:
When I run this code:

try {
  await FirebaseAuth.instance.signInWithEmailAndPassword(email: "nope@stackhack.com", password: "secret");
  print("Signed in");
}
catch (e) {
  print(e);
}

I get the error printed, and not the "Signed in" message. The error contains a code property, which has a value "ERROR_USER_NOT_FOUND". So to respond to this specific error, I could do something like:

if (e.code == "ERROR_USER_NOT_FOUND") {
  print("User not found");
}


答:
It looks like you're not awaiting for any response from auth.signInWithEmailAndPassword which is what you'd need to do in order to check and see if they're actually authenticated.

So:

```<code>await _auth.signInWithEmailAndPassword(email: email, password: password);
</code>```

Title: Login even after wrong creditionals flutter firebase

Body:
It looks like you're not awaiting for any response from auth.signInWithEmailAndPassword which is what you'd need to do in order to check and see if they're actually authenticated.

So:

await _auth.signInWithEmailAndPassword(email: email, password: password);


问:
Is it possible to send a function from server to a client?
By my yet little understanding on how NodeJS/Javascript works, I believe it should be possible. Is it?

I would like to be able to send a function to a client based on http request, something like this (pseudo short code):

```<code>// Server
server.get("/function",()=>{
   return function () => {
     console.log('test)
}

// client
request ("server/function",(res)=>{
     func = res.body
     func()
// # result
// test
</code>```

I have tried to convert to string to send the function from the server and convert back to an object on the client, but it return errors that I couldn't understand why as if I send a simple key value json object it works.

```<code>// server
const http = require('http');
const port = 3000;
const hostname = '127.0.0.1';

const server = http.createServer((req, res) => {
    if (req.url === '/function') {
        res.statusCode = 200;
        function func () {
            console.log('test')
        }
        res.end(func.toString())
    }
});

server.listen(3000)
</code>```

```<code>// client
const http = require('http');

const httpGet = url => {
    return new Promise((resolve, reject) => {
        http.get(url, res => {
            res.setEncoding('utf8');
            let body = '';
            res.on('data', chunk => body += chunk);
            res.on('end', () => resolve(body));
        }).on('error', reject);
    });
};

const call = async () => {
    const body = await httpGet('http://localhost:3000/function')
    console.log(`${body}`)
    func = JSON.parse(body) // try to redefine function based on the response
}

const func = () => {
    console.log('before')
}
func() // run the func defined here

call()

func() // run the function got from the request?

</code>```

The idea is to have a client that will be able to execute almoust any code without the need of updating the client itself.

答:
I'm not sure why you want to do this, it is really unsafe and you shouldn't have web applications that do this. But here goes:

Let's say you have a function:

```<code>function test() {
  console.log("test")
}
</code>```

And as string:

```<code>const funcString = test.toString()
// ^ is now "function test() {\n  console.log(\"test\")\n }"
</code>```

You need to first get the function body:

```<code>const funcBody = funcString.replace(/^[^{]+{/, '').replace(/}[^}]*$/, '')
// ^ is now "console.log(\"test\")"
</code>```

Then create a function from it:

```<code>const newTest = Function(funcBody)
</code>```

Now if you call newTest() you will see test printed in your console.

Note that the regular expression I have used to get the function body will not work on all functions. For example, for const test = () => 1 you will need a different regular expression.

Body:
By my yet little understanding on how NodeJS/Javascript works, I believe it should be possible. Is it?

I would like to be able to send a function to a client based on http request, something like this (pseudo short code):

// Server
server.get("/function",()=>{
   return function () => {
     console.log('test)
}

// client
request ("server/function",(res)=>{
     func = res.body
     func()
// # result
// test

I have tried to convert to string to send the function from the server and convert back to an object on the client, but it return errors that I couldn't understand why as if I send a simple key value json object it works.

// server
const http = require('http');
const port = 3000;
const hostname = '127.0.0.1';

const server = http.createServer((req, res) => {
    if (req.url === '/function') {
        res.statusCode = 200;
        function func () {
            console.log('test')
        }
        res.end(func.toString())
    }
});

server.listen(3000)

// client
const http = require('http');

const httpGet = url => {
    return new Promise((resolve, reject) => {
        http.get(url, res => {
            res.setEncoding('utf8');
            let body = '';
            res.on('data', chunk => body += chunk);
            res.on('end', () => resolve(body));
        }).on('error', reject);
    });
};

const call = async () => {
    const body = await httpGet('http://localhost:3000/function')
    console.log(`${body}`)
    func = JSON.parse(body) // try to redefine function based on the response
}

const func = () => {
    console.log('before')
}
func() // run the func defined here

call()

func() // run the function got from the request?

The idea is to have a client that will be able to execute almoust any code without the need of updating the client itself.

Body:
I'm not sure why you want to do this, it is really unsafe and you shouldn't have web applications that do this. But here goes:

Let's say you have a function:

function test() {
  console.log("test")
}

And as string:

const funcString = test.toString()
// ^ is now "function test() {\n  console.log(\"test\")\n }"

You need to first get the function body:

const funcBody = funcString.replace(/^[^{]+{/, '').replace(/}[^}]*$/, '')
// ^ is now "console.log(\"test\")"

Then create a function from it:

const newTest = Function(funcBody)

Now if you call newTest() you will see test printed in your console.

Note that the regular expression I have used to get the function body will not work on all functions. For example, for const test = () => 1 you will need a different regular expression.


问:
Is it possible to return custom errors in python gRPC server?
I have a .proto file:

```<code>// Protocol Buffers Language version
syntax = "proto3";

package my_package;

// -----------------Cart service-----------------

service CartService {
    rpc AddItem(AddItemRequest) returns (AddItemResponse) {}
}

message CartItem {
    string product_id = 1;
    int32  quantity = 2;
}

message AddItemRequest {
    string user_id = 1;
    CartItem item = 2;
}

message AddItemResponse {
    string user_id = 1;
}
</code>```

In my AddItem method I want to return a custom error like cart_not_found:

```<code>class CartService(my_package_pb2_grpc.CartServiceServicer):
    def AddItem(self, request, context):
         context.set_code(StatusCode.CART_NOT_FOUND)
         context.set_details('Cart Not Found!')
         return context
</code>```

The above code does not work as gRPC status codes are limited to some basic list. How can I return custom errors in gRPC?

EDIT-1:

I've seen examples that set machine readable code in details like below:

```<code>context.set_code(grpc.StatusCode.INTERNAL)
context.set_details('cart_not_found')
return context
</code>```

But this has its own limitation and I cannot set description for the error or any other custom key.

The other method is to return error in every message you have like below:

```<code>message AddItemResponse {
    string user_id = 1;
    Error error = 2;
}

message Error {
    string code = 1;
    string message = 2;
}
</code>```

This implementation has one drawback that services need to check for error existence and then handle the error otherwise process the response.

答: There is an example for returning custom error at https://github.com/grpc/grpc/tree/master/examples/python/errors.</p>

Body:
I have a .proto file:

// Protocol Buffers Language version
syntax = "proto3";

package my_package;

// -----------------Cart service-----------------

service CartService {
    rpc AddItem(AddItemRequest) returns (AddItemResponse) {}
}

message CartItem {
    string product_id = 1;
    int32  quantity = 2;
}

message AddItemRequest {
    string user_id = 1;
    CartItem item = 2;
}

message AddItemResponse {
    string user_id = 1;
}

In my AddItem method I want to return a custom error like cart_not_found:

class CartService(my_package_pb2_grpc.CartServiceServicer):
    def AddItem(self, request, context):
         context.set_code(StatusCode.CART_NOT_FOUND)
         context.set_details('Cart Not Found!')
         return context

The above code does not work as gRPC status codes are limited to some basic list. How can I return custom errors in gRPC?

EDIT-1:

I've seen examples that set machine readable code in details like below:

context.set_code(grpc.StatusCode.INTERNAL)
context.set_details('cart_not_found')
return context

But this has its own limitation and I cannot set description for the error or any other custom key.

The other method is to return error in every message you have like below:

message AddItemResponse {
    string user_id = 1;
    Error error = 2;
}

message Error {
    string code = 1;
    string message = 2;
}

This implementation has one drawback that services need to check for error existence and then handle the error otherwise process the response.


问:
Anyone with experience of targeting Silverlight & WPF?
Is it possible to develop against Silverlight and WPF using the same source code? Maybe using some #define blocks where it is necessary.</p>

答:
You can use Visual Studio file linking to include classes from WPF projects in Silverlight - but only if they don't do any UI or XAML based stuff (as this is where you will usually find inconsistencies between the two)...

So keep it to business logic etc.

OwnerDisplayName: Phil Wright

ContentLicense: CC BY-SA 2.5


问:
Change iFrame src on ajax complete
using jQuery's $.ajax() I want to retrieve some information from the server, and then, based on that info, change the src attribute of an iframe.

Something like:

```<code>$.ajax(
                {
                    url: "someUrl.aspx/getInfo",
                    dataType: "json",
                    data: "{'data':{'data1':'data1'}}",
                    type: "post",
                    contentType: "application/json; charset=utf-8",
                    complete: function(data, stat) {
                        if (stat == "success" )
                        {
                           var src = JSON.parse(jsondata.responseText).d.src
                           $('#myframe').attr("src",src);
                        }

                    }
                }
                );
</code>```

The page I am trying to load is returning a PDF file, so the goal is to show the user the dialog to choose between downloading or opening that file. On IE7 and 8 the browser is showing the info bar with this message : "To help protect your security, Internet Explorer blocked this site from downloading files to your computer. Click here for options."

Changing the iframe's src attribute OUTSIDE the ajax call works fine and the dialog to choose between opening or saving the PDF is shown.

Any workarounds to avoid the info bar showing?
Thanks in advance.

答:
You could try this if you don't want to use jQuery

document.getElementById("myframe").src=src;

try this wit jQuery

```<code>var iframe = $('#myframe');

 $(iframe).attr('src', src)
</code>```

In order to open a PDF try this

```<code>window.open(src);
</code>```

will open the pdf in a new window...but the info bar cannot be avoided....

Title: Change iFrame src on ajax complete

Body:
using jQuery's $.ajax() I want to retrieve some information from the server, and then, based on that info, change the src attribute of an iframe.

Something like:

$.ajax(
                {
                    url: "someUrl.aspx/getInfo",
                    dataType: "json",
                    data: "{'data':{'data1':'data1'}}",
                    type: "post",
                    contentType: "application/json; charset=utf-8",
                    complete: function(data, stat) {
                        if (stat == "success" )
                        {
                           var src = JSON.parse(jsondata.responseText).d.src
                           $('#myframe').attr("src",src);
                        }

                    }
                }
                );

The page I am trying to load is returning a PDF file, so the goal is to show the user the dialog to choose between downloading or opening that file. On IE7 and 8 the browser is showing the info bar with this message : "To help protect your security, Internet Explorer blocked this site from downloading files to your computer. Click here for options."

Changing the iframe's src attribute OUTSIDE the ajax call works fine and the dialog to choose between opening or saving the PDF is shown.

Any workarounds to avoid the info bar showing?
Thanks in advance.

Body:
You could try this if you don't want to use jQuery

document.getElementById("myframe").src=src;

try this wit jQuery

var iframe = $('#myframe');

 $(iframe).attr('src', src)

In order to open a PDF try this

window.open(src);

will open the pdf in a new window...but the info bar cannot be avoided....


问:
How do you set the text of an EditText menu item?
I am trying to set the text of an item in a toolbar menu with the EditText property. The textbox shows up on the app, but always empty. I'm trying to get "Hello World!" to show up in the textbox using 3 different ways, but it still is empty. Below is the XML:</p>

```<code>    <item android:id="@+id/DisplayPath"
    android:title="Hello World!"
    android:text="Hello World!"
    android:hint="Hello WOrld"
    app:showAsAction="always"
    app:actionViewClass="android.widget.EditText" />
</code>```

答:
just override onCreateOptionsMenu() like this in your MainPage.java

```<code>@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }
</code>```

Edit

you have to access editText widget to set text on it

Body:
I am trying to set the text of an item in a toolbar menu with the EditText property. The textbox shows up on the app, but always empty. I'm trying to get "Hello World!" to show up in the textbox using 3 different ways, but it still is empty. Below is the XML:

    <item android:id="@+id/DisplayPath"
    android:title="Hello World!"
    android:text="Hello World!"
    android:hint="Hello WOrld"
    app:showAsAction="always"
    app:actionViewClass="android.widget.EditText" />

Body:
just override onCreateOptionsMenu() like this in your MainPage.java

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

Edit

you have to access editText widget to set text on it


问:
Error Gradle Build C:\Program Files\Java\jdk1.7.0_79\bin\java.exe'' finished with non-zero exit value 1

Error:Execution failed for task ':app:transformClassesWithDexForDebug'.
  com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.7.0_79\bin\java.exe'' finished with non-zero exit value 1

Here is my gradle build file:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "br.com.gerenciarsc.nfce"
        minSdkVersion 12
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile('org.simpleframework:simple-xml:2.7.1') {
        exclude group: 'xpp3', module: 'xpp3'
        exclude group: 'stax', module: 'stax-api'
        exclude group: 'stax', module: 'stax'
    }
    compile 'com.google.code.gson:gson:2.5'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.j256.ormlite:ormlite-core:4.48'
    compile 'com.j256.ormlite:ormlite-android:4.48'
    compile 'com.beardedhen:androidbootstrap:2.0.0'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.journeyapps:zxing-android-embedded:3.0.2@aar'
    compile 'com.google.zxing:core:3.2.0'
    compile 'br.com.uol.ps:library:0.8'
    compile 'com.android.support:support-v4:23.1.1'
    compile 'javax.xml.crypto:jsr105-api:1.0.1'
    compile ('commons-io:commons-io:2.4'){
        exclude group: 'org.apache.commons.collections', module: 'org.apache.commons.collections'
    }
}
</code>```

答:
I've got this error:

Execution failed for task
  ':vvm:transformClassesWithDesugarForRelease'.
  com.android.build.api.transform.TransformException:
  org.gradle.process.internal.ExecException: A problem occurred starting
  process 'command 'E:\Java\jdk1.8.0_181\bin\java.exe''

I've solved it by updating gradle from 4.4 to 5.4

Body:
Error:Execution failed for task ':app:transformClassesWithDexForDebug'.
  com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.7.0_79\bin\java.exe'' finished with non-zero exit value 1

Here is my gradle build file:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "br.com.gerenciarsc.nfce"
        minSdkVersion 12
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile('org.simpleframework:simple-xml:2.7.1') {
        exclude group: 'xpp3', module: 'xpp3'
        exclude group: 'stax', module: 'stax-api'
        exclude group: 'stax', module: 'stax'
    }
    compile 'com.google.code.gson:gson:2.5'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.j256.ormlite:ormlite-core:4.48'
    compile 'com.j256.ormlite:ormlite-android:4.48'
    compile 'com.beardedhen:androidbootstrap:2.0.0'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.journeyapps:zxing-android-embedded:3.0.2@aar'
    compile 'com.google.zxing:core:3.2.0'
    compile 'br.com.uol.ps:library:0.8'
    compile 'com.android.support:support-v4:23.1.1'
    compile 'javax.xml.crypto:jsr105-api:1.0.1'
    compile ('commons-io:commons-io:2.4'){
        exclude group: 'org.apache.commons.collections', module: 'org.apache.commons.collections'
    }
}


问:
React: useEffect vs useMemo vs useState
I was trying to find a concise answer to this on the web without luck.

Is the following correct regarding the differences between useEffect, useMemo and useState?

Both useState and useMemo will remember a value across renders. The difference is that:

useMemo does not cause a re-render, while useState does

useMemo only runs when its dependencies (if any) have changed, while setSomeState (second array item returned by useState) does not have such a dependency array

Both useMemo and useEffect only runs when their dependencies change (if any). The difference is that:

useEffect runs after a render happens, while useMemo runs before

Any other key differences I have missed?

答:
Your points are basically correct, some minor clarification:

useState is causing a re-render on the call of the setState method (second element in the array returned). It does not have any dependencies like useMemo or useEffect.

useMemo only recalculates a value if the elements in its dependency array change (if there are no dependencies - i.e. the array is empty, it will recalculate only once). If the array is left out, it will recalculate on every render. Calling the function does not cause a re-render. Also it runs during the render of the component and not before.

useEffect is called after each render, if elements in its dependency array have changed or the array is left out. If the array is empty, it will only be run once on the initial mount (and unmount if you return a cleanup function).

You can always check Hooks API Reference, which is a pretty solid documentation in my opinion

Title: React: useEffect vs useMemo vs useState


问:
C# laziness question
What's the common approach to design applications, which strongly rely on lazy evaluation in C# (LINQ, IEnumerable, IQueryable, ...)?

Right now I usually attempt to make every query as lazy as possible, using yield return and LINQ queries, but in runtime this could usually lead to "too lazy" behavior, when every query gets builts from it's beginning obviously resulting in severe visual performance degradation.

What I usually do means putting ToList() projection operators somewhere to cache the data, but I suspect this approach might be incorrect.

What's the appropriate / common ways to design this sort of applications from the very beginning?

答:
Pretty broad question and unfortunately you're going to hear this a lot: It depends. Lazy-loading is great until it's not.

In general, if you're using the same IEnumerables over and over it might be best to cache them as lists.

But rarely does it make sense for your callers to know this either way. That is, if you're getting IEnumerables from a repository or something, it is best to let the repository do its job. It might cache it as a list internally or it might build it up every time. If your callers try to get too clever they might miss changes in the data, etc.

Title: C# laziness question


问:
How do I change the Hitbox size of a turtle in python turtle graphics?
I dont know how to change the size of a turtle hitbox in python turtle graphics

I haven't tried anything yet because I'm new, and know very little about this. I've tried googling it, though, but nothing popped up.

```<code>from turtle import *
import turtle
from random import randint
import time

screen = turtle.Screen()
screen.setup(1920, 1080)
player = turtle.Turtle()
</code>```

I want to add a button that you have to click to start right here

The game starts right here :

```<code>wn = turtle.Screen()

last_pressed = 'up'

def setup(col, x, y, w, s, shape):

  player.penup()
  player.up()
  player.goto(x,y)
  player.width(w)
  player.turtlesize(s)
  player.color(col)
  player.lt(90)
  player.down()
  wn.onkey(up, "s")
  wn.onkey(left, "d")
  wn.onkey(right, "a")
  wn.onkey(back, "w")
  wn.onkey(quitTurtles, "Escape")
  wn.listen()
  wn.mainloop()
</code>```

答:
```<code>I dont know how to change the size of a turtle hitbox in python turtle graphics
</code>```

What do you mean by "hitbox"?  I'm not sure what you mean by that (and neither does Google, apparently).

Do you mean that you want a rectangular button to click on?  If that's the case, you could use the tkinter module together with the turtle module to create a button to click.  (But be aware that it's not always easy to get the tkinter and turtle modules to work together to do what you want.)

If you want a button to click on, but don't need a Tkinter button, you could just try creating a new turtle in the shape of a rectangle that intercepts mouse clicks with onclick().  You can see an example of this if you run:

```<code> python3 -m turtledemo
</code>```

and select Examples >> colormixer from the main menubar.

Or, if by "hitbox" you mean how to detect when one turtle has intercepted another turtle (as in, one has come close enough to the other to be considered a "hit"), I suggest querying each turtle's location, then using the Pythagorean Theorem to calculate the distance from each other.  If this distance is within a predetermined threshold, consider the hitbox as being "hit."

You can see an example of this by typing:

```<code>python3 -m turtle
</code>```

(Pay attention to the yellow turtle as he tries to catch up to the other turtle.)

I apologize if this answer isn't quite what you're looking for, but I'm just not sure what you mean by "hitbox."  Maybe you could clarify?

Body:
I dont know how to change the size of a turtle hitbox in python turtle graphics

I haven't tried anything yet because I'm new, and know very little about this. I've tried googling it, though, but nothing popped up.

from turtle import *
import turtle
from random import randint
import time

screen = turtle.Screen()
screen.setup(1920, 1080)
player = turtle.Turtle()

I want to add a button that you have to click to start right here

The game starts right here :

wn = turtle.Screen()

last_pressed = 'up'

def setup(col, x, y, w, s, shape):

  player.penup()
  player.up()
  player.goto(x,y)
  player.width(w)
  player.turtlesize(s)
  player.color(col)
  player.lt(90)
  player.down()
  wn.onkey(up, "s")
  wn.onkey(left, "d")
  wn.onkey(right, "a")
  wn.onkey(back, "w")
  wn.onkey(quitTurtles, "Escape")
  wn.listen()
  wn.mainloop()

Body:
I dont know how to change the size of a turtle hitbox in python turtle graphics

What do you mean by "hitbox"?  I'm not sure what you mean by that (and neither does Google, apparently).

Do you mean that you want a rectangular button to click on?  If that's the case, you could use the tkinter module together with the turtle module to create a button to click.  (But be aware that it's not always easy to get the tkinter and turtle modules to work together to do what you want.)

If you want a button to click on, but don't need a Tkinter button, you could just try creating a new turtle in the shape of a rectangle that intercepts mouse clicks with onclick().  You can see an example of this if you run:

 python3 -m turtledemo

and select Examples >> colormixer from the main menubar.

Or, if by "hitbox" you mean how to detect when one turtle has intercepted another turtle (as in, one has come close enough to the other to be considered a "hit"), I suggest querying each turtle's location, then using the Pythagorean Theorem to calculate the distance from each other.  If this distance is within a predetermined threshold, consider the hitbox as being "hit."

You can see an example of this by typing:

python3 -m turtle

(Pay attention to the yellow turtle as he tries to catch up to the other turtle.)

I apologize if this answer isn't quite what you're looking for, but I'm just not sure what you mean by "hitbox."  Maybe you could clarify?


问:
Undefined variable: all_data (View: /var/www/html/resources/views/welcome.blade.php)
I'm trying to post data from controller to view, basically when page loads user sees the form and when it get submits, it returns the data. I'm not sure what I'm doing wrong. I have tried the following to returns the data

Return methods tried:

```<code>return view('welcome',['all_data'=>$all_data]);
return view('welcome')->with('all_data', $all_data);
return view('welcome')->with('data', json_decode($data, true));
return View::make('welcome', array('all_data'=>$all_data));
</code>```

Controller:

```<code>public function getStatus(Request $request){

//SQLQuery which returns $all_data

$all_data = json_encode($data);
return view('welcome', compact('all_data'));
}
</code>```

Route:

```<code>Route::get('/', function () {
    return view('welcome');
});

Route::post('/getstatus', 'GetApplicationStatusController@getStatus');
</code>```

View:

```<code>@foreach ($all_data as $data)
<td id="appid">{{$data->appid}}</td>
<td id="firstname">{{$data->firstname}}</td>
<td id="middlename">{{$data->middlename}}</td>
<td id="lastname">{{$data->lastname}}</td>
<td id="action">{{$data->action}}</td>
@endforeach
</code>```

答:
Pass all_data without json_encode for foreach

```<code>public function getStatus(Request $request){

    //SQLQuery which returns $data
    $all_data = $data;
    return view('welcome', compact('all_data'));
}
</code>```

In view:

```<code>@foreach ($all_data as $data)
   <td id="appid">{{$data['appid']}}</td>
   <td id="firstname">{{$data['firstname']}}</td>
   <td id="middlename">{{$data['middlename']}}</td>
   <td id="lastname">{{$data['lastname']}}</td>
   <td id="action">{{$data['action']}}</td>
@endforeach
</code>```

Body:
I'm trying to post data from controller to view, basically when page loads user sees the form and when it get submits, it returns the data. I'm not sure what I'm doing wrong. I have tried the following to returns the data

Return methods tried:

return view('welcome',['all_data'=>$all_data]);
return view('welcome')->with('all_data', $all_data);
return view('welcome')->with('data', json_decode($data, true));
return View::make('welcome', array('all_data'=>$all_data));

Controller:

public function getStatus(Request $request){

//SQLQuery which returns $all_data

$all_data = json_encode($data);
return view('welcome', compact('all_data'));
}

Route:

Route::get('/', function () {
    return view('welcome');
});

Route::post('/getstatus', 'GetApplicationStatusController@getStatus');

View:

@foreach ($all_data as $data)
{{$data->appid}}
{{$data->firstname}}
{{$data->middlename}}
{{$data->lastname}}
{{$data->action}}
@endforeach

Body:
Pass all_data without json_encode for foreach

public function getStatus(Request $request){

    //SQLQuery which returns $data
    $all_data = $data;
    return view('welcome', compact('all_data'));
}

In view:

@foreach ($all_data as $data)
   <td id="appid">{{$data['appid']}}</td>
   <td id="firstname">{{$data['firstname']}}</td>
   <td id="middlename">{{$data['middlename']}}</td>
   <td id="lastname">{{$data['lastname']}}</td>
   <td id="action">{{$data['action']}}</td>
@endforeach


问:
No database provider .Net Core Angular app
I'm trying to build my database using .NET Core 2.2 and Angular and have run across this error:

```<code>No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.
</code>```

I have a default constructor in my ApplicationDbContext class.

```<code>public class ApplicationDbContext : DbContext
{
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> opts) : base()
        {
        }
}
</code>```

My program cs looks okay to me:

```<code>public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration(SetUpConfiguration)
                .UseStartup<Startup>();

        private static void SetUpConfiguration(WebHostBuilderContext ctx, IConfigurationBuilder builder)
        {
            builder.Sources.Clear();
            builder.AddJsonFile("appsettings.json", false, true)
                    .AddEnvironmentVariables();
        }
    }
</code>```

And my startup registers the db:

```<code>private readonly IConfiguration _config;
        public Startup(IConfiguration config)
        {
            _config = config;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddDbContext<ApplicationDbContext>(cfg => {
                cfg.UseSqlServer(_config.GetConnectionString("LevanaConnectionString"));
            });

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }
</code>```

答:
You're not passing the options into the base constructor:</p>

```<code>public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> opts) : base(opts) // <-- this
    {
    }
}
</code>```

Body:
I'm trying to build my database using .NET Core 2.2 and Angular and have run across this error:

No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.

I have a default constructor in my ApplicationDbContext class.

public class ApplicationDbContext : DbContext
{
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> opts) : base()
        {
        }
}

My program cs looks okay to me:

public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration(SetUpConfiguration)
                .UseStartup<Startup>();

        private static void SetUpConfiguration(WebHostBuilderContext ctx, IConfigurationBuilder builder)
        {
            builder.Sources.Clear();
            builder.AddJsonFile("appsettings.json", false, true)
                    .AddEnvironmentVariables();
        }
    }

And my startup registers the db:

private readonly IConfiguration _config;
        public Startup(IConfiguration config)
        {
            _config = config;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddDbContext<ApplicationDbContext>(cfg => {
                cfg.UseSqlServer(_config.GetConnectionString("LevanaConnectionString"));
            });

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }

Body:
You're not passing the options into the base constructor:

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> opts) : base(opts) // <-- this
    {
    }
}


问:
Use of unresolved identifier 'UIBezierPath'
I am building a project that is using a charting library I originally found when building android apps called MPAndroidCharts. It has been ported over to iOS/Swift and had been working great. I came across a weird problem though. Friday when I left work the project was working perfectly, I test the app at the end of each day and the beginning of each day, not sure why, it's just how I do it. So it was working Friday when I left work, I came in today opened up the project and tried to build it, now I am getting build failure saying "Use of unresolved identifier 'UIBezierPath' did you mean 'NSBezierPath'?" I have not updated anything on my system and nothing has changed in the code base, but now it won't build.

When I try to update it to NSBezierPath I get a bunch of other errors because it doesn't have the same arguments in the constructor and I am not 100% sure how to convert it over to NSBezierPath. My constructor is simple(ish)...

```<code>let bezierPath = UIBezierPath(roundedRect: barRect, byRoundingCorners: UIRectCorner.allCorners, cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))
let roundedPath = bezierPath.cgPath
</code>```

When I update to NSBezierPath I get errors about UIRectCorner needing to be NSRectPointer, which doesn't have the ".allCorners" and then the constructor is all wrong and it doesn't build.

I am trying to make this not too general because I know that is bad, but I don't know how to fix it, or why it just magically became unresolved over the weekend without me updating xCode or my code base, or any associated libraries. Any help would be greatly appreciated. If you need it the link to the charting library is ... https://github.com/danielgindi/Charts

答:
now I am getting build failure saying "Use of unresolved identifier 'UIBezierPath' did you mean 'NSBezierPath'?"

UIBezierPath is a UIKit class, and since UIKit is an iOS framework you can use UIBezierPath in iOS projects but not macOS projects. NSBezierPath is an AppKit class, and AppKit is a macOS framework, so you can use it on macOS but not iOS.

If Xcode is offering NSBezierPath as an alternative, then it sounds like you've somehow switched your target to build for macOS instead of iOS. Check that, and also check that your project links against UIKit.

When I try to update it to NSBezierPath I get a bunch of other errors because it doesn't have the same arguments in the constructor and I am not 100% sure how to convert it over to NSBezierPath.

You shouldn't switch to NSBeziierPath unless you're porting your project to macOS. If that's what you're doing, then yes, you'll need to switch, and you'll need to read the NSBezierPath documentation to figure out how to rewrite your code to use that API. Briefly, it looks like you should be able to use init(roundedRect:,xRadius:,yRadius:) with cornerRadius for the last two parameters.

Body:
I am building a project that is using a charting library I originally found when building android apps called MPAndroidCharts. It has been ported over to iOS/Swift and had been working great. I came across a weird problem though. Friday when I left work the project was working perfectly, I test the app at the end of each day and the beginning of each day, not sure why, it's just how I do it. So it was working Friday when I left work, I came in today opened up the project and tried to build it, now I am getting build failure saying "Use of unresolved identifier 'UIBezierPath' did you mean 'NSBezierPath'?" I have not updated anything on my system and nothing has changed in the code base, but now it won't build.

When I try to update it to NSBezierPath I get a bunch of other errors because it doesn't have the same arguments in the constructor and I am not 100% sure how to convert it over to NSBezierPath. My constructor is simple(ish)...

let bezierPath = UIBezierPath(roundedRect: barRect, byRoundingCorners: UIRectCorner.allCorners, cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))
let roundedPath = bezierPath.cgPath

When I update to NSBezierPath I get errors about UIRectCorner needing to be NSRectPointer, which doesn't have the ".allCorners" and then the constructor is all wrong and it doesn't build.

I am trying to make this not too general because I know that is bad, but I don't know how to fix it, or why it just magically became unresolved over the weekend without me updating xCode or my code base, or any associated libraries. Any help would be greatly appreciated. If you need it the link to the charting library is ... https://github.com/danielgindi/Charts