问:
React server run error + Redux + Webpack + Babel [TODO LIST]
I am new in React and doing a Todo List but i can't start my server because i am getting error when I try yarn run build

Error

```<code>ERROR in ./src/index.js
Module parse failed: C:\Users\PixyDigital\Desktop\Getto\src\index.js Unexpected token (8:4)
You may need an appropriate loader to handle this file type.
|
| render(
|     <Provider store={store}>
|         <App />
|     </Provider>,
 @ multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-server ./src/index.js
webpack: Failed to compile.
</code>```

index.js

```<code>import React from "react"
import {render} from "react-dom"
import {Provider} from "react-redux"
import store from "./stores/store"
import App from "./components/app.js"

render(
    <Provider store={store}>
        <App />
    </Provider>,

    document.getElementById("app")
)
</code>```

webpack.config.js

```<code>module.exports = {
    entry: __dirname + "/src/index.js",
    output:{
        filename: "bundle.js",
        path: __dirname + "/dist"
    },
    module:{
        loaders:[
            {
                test:/\.css$/,
                loader:"style-loader$css-loader"
            },
            {
                test:/\.jsx$/,
                loader:"babel-loader",
                exclude:/node_modules/
            }
        ]
    },
    resolve:{
        extensions:['*','.js','.jsx','.css']
    },
    devServer:{
        contentBase: __dirname + "/dist"
    }
}
</code>```

package.json

```<code>{
  "name": "todoApp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack-dev-server --inline --hot"
  },
  "devDependencies": {
    "babel-core": "^6.25.0",
    "babel-loader": "^7.1.1",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^0.28.4",
    "style-loader": "^0.18.2",
    "webpack": "^3.1.0",
    "webpack-dev-server": "^2.5.1"
  },
  "dependencies": {
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "react-hot-loader": "^1.3.1",
    "react-redux": "^5.0.5",
    "redux": "^3.7.1"
  }
}
</code>```

So how can I resolve my problem, Do you have any idea?

Thanks.

答:
```<code>        {
            test:/\.jsx?$/,
            loader:"babel-loader",
            exclude:/node_modules/,
            options: {
                presets: ["react"]
            }
        }
</code>```

UPD: This happens because babel doesn't transform JSX out of the box;

Also i'd recommend to configure babel using .baberlc file

Body:
I am new in React and doing a Todo List but i can't start my server because i am getting error when I try yarn run build

Error

ERROR in ./src/index.js
Module parse failed: C:\Users\PixyDigital\Desktop\Getto\src\index.js Unexpected token (8:4)
You may need an appropriate loader to handle this file type.
|
| render(
|     <Provider store={store}>
|         <App />
|     </Provider>,
 @ multi (webpack)-dev-server/client?http://localhost:8080 webpack/hot/dev-server ./src/index.js
webpack: Failed to compile.

index.js

import React from "react"
import {render} from "react-dom"
import {Provider} from "react-redux"
import store from "./stores/store"
import App from "./components/app.js"

render(
    <Provider store={store}>
        <App />
    </Provider>,

    document.getElementById("app")
)

webpack.config.js

module.exports = {
    entry: __dirname + "/src/index.js",
    output:{
        filename: "bundle.js",
        path: __dirname + "/dist"
    },
    module:{
        loaders:[
            {
                test:/\.css$/,
                loader:"style-loader$css-loader"
            },
            {
                test:/\.jsx$/,
                loader:"babel-loader",
                exclude:/node_modules/
            }
        ]
    },
    resolve:{
        extensions:['*','.js','.jsx','.css']
    },
    devServer:{
        contentBase: __dirname + "/dist"
    }
}

package.json

{
  "name": "todoApp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack-dev-server --inline --hot"
  },
  "devDependencies": {
    "babel-core": "^6.25.0",
    "babel-loader": "^7.1.1",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^0.28.4",
    "style-loader": "^0.18.2",
    "webpack": "^3.1.0",
    "webpack-dev-server": "^2.5.1"
  },
  "dependencies": {
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "react-hot-loader": "^1.3.1",
    "react-redux": "^5.0.5",
    "redux": "^3.7.1"
  }
}

So how can I resolve my problem, Do you have any idea?

Thanks.

Body:
        {
            test:/\.jsx?$/,
            loader:"babel-loader",
            exclude:/node_modules/,
            options: {
                presets: ["react"]
            }
        }

UPD: This happens because babel doesn't transform JSX out of the box;

Also i'd recommend to configure babel using .baberlc file


来源: stackexchange

问:
Issue with Swift 2.2 generics (Xcode 7.3)
I've got a frustrating situation with Swift 2.2 (Xcode 7.3). To simulate it, just create a variable in a user defined, generic class, and reference that class from someplace else. For example:

```<code>class A<T> {
    let genVar = 1
}

class MyViewController: UIViewController {
    let myVar = A<Int>() // crash is here
}
</code>```

If you will run this code on a device running iOS 7 (iPhone 4, in my case), it will crash on the attempt of creating a variable of generic type. Here are the first lines of the device crash log:

```<code>Exception Type:  EXC_BAD_ACCESS (SIGBUS)
Exception Subtype: KERN_PROTECTION_FAILURE at 0x00298910
Triggered by Thread:  0

Thread 0 Crashed:
0   libswiftCore.dylib              0x006b1d64 0x4bd000 + 2051428
1   Phone                           0x001c76ec 0xab000 + 1165036
2   libswiftCore.dylib              0x006b307c 0x4bd000 + 2056316
3   libswiftCore.dylib              0x006b2f70 0x4bd000 + 2056048
4   libswiftCore.dylib              0x006b0f24 0x4bd000 + 2047780
5   libswiftCore.dylib              0x006b107c 0x4bd000 + 2048124
6   Phone                           0x0014e730 0xab000 + 669488
7   Phone                           0x00129390 0xab000 + 517008
8   UIKit                           0x31e9d9c4 -[UIClassSwapper initWithCoder:] + 188
</code>```

On iOS 8 and 9 simulators/devices, the code above works okay.

Is Swift support for iOS 7 going to be dropped in the near future?

答: With Xcode 7.3.1, the only problem with my generic class was that it was inheriting from NSObject. Removing the inheritance was enough, the order of property declaration didn't matter.</p>

ContentLicense: CC BY-SA 3.0

Body:
I've got a frustrating situation with Swift 2.2 (Xcode 7.3). To simulate it, just create a variable in a user defined, generic class, and reference that class from someplace else. For example:

class A<T> {
    let genVar = 1
}

class MyViewController: UIViewController {
    let myVar = A<Int>() // crash is here
}

If you will run this code on a device running iOS 7 (iPhone 4, in my case), it will crash on the attempt of creating a variable of generic type. Here are the first lines of the device crash log:

Exception Type:  EXC_BAD_ACCESS (SIGBUS)
Exception Subtype: KERN_PROTECTION_FAILURE at 0x00298910
Triggered by Thread:  0

Thread 0 Crashed:
0   libswiftCore.dylib              0x006b1d64 0x4bd000 + 2051428
1   Phone                           0x001c76ec 0xab000 + 1165036
2   libswiftCore.dylib              0x006b307c 0x4bd000 + 2056316
3   libswiftCore.dylib              0x006b2f70 0x4bd000 + 2056048
4   libswiftCore.dylib              0x006b0f24 0x4bd000 + 2047780
5   libswiftCore.dylib              0x006b107c 0x4bd000 + 2048124
6   Phone                           0x0014e730 0xab000 + 669488
7   Phone                           0x00129390 0xab000 + 517008
8   UIKit                           0x31e9d9c4 -[UIClassSwapper initWithCoder:] + 188

On iOS 8 and 9 simulators/devices, the code above works okay.

Is Swift support for iOS 7 going to be dropped in the near future?


问:
Maximum POST Variables PHP?
I am submitting 5 stings to PHP from HTML

I get an error on goDaddy (Internal Server error) when i try and pass 5 strings  BUT  it works for 4 strings.
I cannot figure out the problem. Is there a maximum amount of POST variables that can be passed?
I works for 4 strings, and when i add another string i get an error.
Godaddy support team was useless was on the phone with them for Hours.
The coding works fine on WAMP!

HTML

```<code><form action="login.php" method="post">

  <input type="text" name="username" placeholder="Username"/>
  <input type="password" name="password" placeholder="Password"/>
  <input type="text" name="clientID" id="client_id" value="" />
   <input type="text" name="redirect" id="redirect_uri" value="" />
    <input type="text" name="webstate" id="stateValue" value="" />

  <button>Login</button>
</form>
</code>```

PHP

```<code>$myusername=$_POST['username'];
$mypassword=$_POST['password'];
$client_id=$_POST['clientID'];
$redirect_uri=$_POST['redirect'];
/*$state=$_POST['webstate']; */  <---- When i add this line it Shows
                                       Internal Server Error

echo "Username: ".$myusername. "<br />";
echo "Client ID: ".$client_id. "<br />";
echo "Redirect URL: ".$redirect_uri. "<br />";
/*echo "State: ".$state. "<br />"; */ <--- I commented this becouse it
                                           useless
</code>```

答:
It's very important to check if the posted values are set before assigning them to a variable or doing something with them.

$myusername = isset($_POST['username']) ? $_POST['username'] : "" ;

$mypassword= isset($_POST['password']) ? $_POST['password'] : "" ;

$client_id= isset($_POST['clientID']) ? $_POST['clientID'] : "" ;

$redirect_uri= isset($_POST['redirect']) ? $_POST['redirect'] : "" ;

$state= isset($_POST['webstate']) ? $_POST['webstate'] : "" ;

Title: Maximum POST Variables PHP?

Body:
I am submitting 5 stings to PHP from HTML

I get an error on goDaddy (Internal Server error) when i try and pass 5 strings  BUT  it works for 4 strings.
I cannot figure out the problem. Is there a maximum amount of POST variables that can be passed?
I works for 4 strings, and when i add another string i get an error.
Godaddy support team was useless was on the phone with them for Hours.
The coding works fine on WAMP!

HTML

<form action="login.php" method="post">

  <input type="text" name="username" placeholder="Username"/>
  <input type="password" name="password" placeholder="Password"/>
  <input type="text" name="clientID" id="client_id" value="" />
   <input type="text" name="redirect" id="redirect_uri" value="" />
    <input type="text" name="webstate" id="stateValue" value="" />

  <button>Login</button>
</form>

PHP

$myusername=$_POST['username'];
$mypassword=$_POST['password'];
$client_id=$_POST['clientID'];
$redirect_uri=$_POST['redirect'];
/*$state=$_POST['webstate']; */  <---- When i add this line it Shows
                                       Internal Server Error

echo "Username: ".$myusername. "
";
echo "Client ID: ".$client_id. "
";
echo "Redirect URL: ".$redirect_uri. "
";
/*echo "State: ".$state. "
"; */ <--- I commented this becouse it
                                           useless


问:
What's your most controversial programming opinion?
This is definitely subjective, but I'd like to try to avoid it becoming argumentative. I think it could be an interesting question if people treat it appropriately.

The idea for this question came from the comment thread from my answer to the "What are five things you hate about your favorite language?" question. I contended that classes in C# should be sealed by default - I won't put my reasoning in the question, but I might write a fuller explanation as an answer to this question. I was surprised at the heat of the discussion in the comments (25 comments currently).

So, what contentious opinions do you hold? I'd rather avoid the kind of thing which ends up being pretty religious with relatively little basis (e.g. brace placing) but examples might include things like "unit testing isn't actually terribly helpful" or "public fields are okay really". The important thing (to me, anyway) is that you've got reasons behind your opinions.

Please present your opinion and reasoning - I would encourage people to vote for opinions which are well-argued and interesting, whether or not you happen to agree with them.

答:
Managers know everything

It's been my experience that managers didn't get there by knowing code usually.  No matter what you tell them it's too long, not right or too expensive.

And another that follows on from the first:

There's never time to do it right but there's always time to do it again

A good engineer friend once said that in anger to describe a situation where management halved his estimates, got a half-assed version out of him  then gave him twice as much time to rework it because it failed.  It's a fairly regular thing in the commercial software world.

And one that came to mind today while trying to configure a router with only a web interface:

Web interfaces are for suckers

The CLI on the previous version of the firmware was oh so nice.  This version has a web interface, which attempts to hide all of the complexity of networking from clueless IT droids, and can't even get VLANs correct.

OwnerDisplayName: Jon Skeet

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: brian d foy

OwnerDisplayName: Adam Hawes

LastEditorDisplayName: Adam Hawes


问:
"Python has stopped Working" when training a convolution neural net in tensorflow gpu
This is a tensorflow code I wrote to test convolution neural net with only 1 convolution and pooling layer with only 1 fully connected layer of 512 neurons.

My dataset is of only 2 images: http://imgur.com/et1Sn1k and http://imgur.com/ZWxOGgO

When I train my network windows gives an pop up saying "Python has stoped" (ss: http://imgur.com/tc5jWlA )

This is my code:

```<code>from scipy.misc import imread
import matplotlib.pyplot as plt
import numpy as np
import PIL.Image as Image

base_image = imread("base_image.jpg")
subject_image = imread("subject_image.jpg")

base_image = np.resize(base_image, [1024, 768, 3])
subject_image = np.resize(subject_image, [1024, 768, 3])

images = []

images.append(base_image)
images.append(subject_image)

# hyper parameters

epochs = 10
batch_size = 2
learning_rate = 0.01
n_classes = 2
import tensorflow as tf

# Model

x = tf.placeholder('float', [2, 1024, 768, 3])
y = tf.placeholder('float', [2])

weights = {
            "conv": tf.random_normal([10, 10, 3, 32]),
            "fc": tf.random_normal([-1, 512]), #7*7*64
            "out": tf.Variable(tf.random_normal([512, n_classes]))
}

conv = tf.nn.conv2d(x, filter=weights['conv'], strides=[1, 1, 1, 1], padding="SAME")
conv = tf.nn.max_pool(value=conv, ksize=[1,2,2,1], strides=[1,2,2,1], padding="SAME")

fc = tf.reshape(conv, shape=[2,-1])
fc = tf.nn.relu(tf.matmul(fc, weights['fc']))

output = tf.matmul(fc, weights['out'])

loss = tf.reduce_mean((output - y)**2)

train = tf.train.AdamOptimizer(learning_rate).minimize(loss)

sess = tf.Session()

sess.run(tf.global_variables_initializer())

for i in range(epochs):
    sess.run(train, feed_dict={x: images, y: [0, 1]})
    print(i)
</code>```

Output:

```<code>2017-07-09 02:29:43.688699: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.689131: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE2 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.689504: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE3 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.689998: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.690380: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.690646: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.691117: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.691436: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:44.197766: I c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\common_runtime\gpu\gpu_device.cc:940] Found device 0 with properties:
name: GeForce GTX 960M
major: 5 minor: 0 memoryClockRate (GHz) 1.176
pciBusID 0000:01:00.0
Total memory: 4.00GiB
Free memory: 3.35GiB
2017-07-09 02:29:44.198207: I c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\common_runtime\gpu\gpu_device.cc:961] DMA: 0
2017-07-09 02:29:44.198391: I c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\common_runtime\gpu\gpu_device.cc:971] 0:   Y
2017-07-09 02:29:44.198643: I c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\common_runtime\gpu\gpu_device.cc:1030] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 960M, pci bus id: 0000:01:00.0)
2017-07-09 02:29:44.881448: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\framework\op_kernel.cc:1158] Invalid argument: Dimension -1 must be >= 0
2017-07-09 02:29:44.881875: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\framework\op_kernel.cc:1158] Invalid argument: Dimension -1 must be >= 0
     [[Node: random_normal_1/RandomStandardNormal = RandomStandardNormal[T=DT_INT32, dtype=DT_FLOAT, seed=0, seed2=0, _device="/job:localhost/replica:0/task:0/gpu:0"](random_normal_1/shape)]]
2017-07-09 02:29:44.882604: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\framework\op_kernel.cc:1158] Invalid argument: Dimension -1 must be >= 0
     [[Node: random_normal_1/RandomStandardNormal = RandomStandardNormal[T=DT_INT32, dtype=DT_FLOAT, seed=0, seed2=0, _device="/job:localhost/replica:0/task:0/gpu:0"](random_normal_1/shape)]]
2017-07-09 02:29:45.362917: E c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\stream_executor\cuda\cuda_dnn.cc:352] Loaded runtime CuDNN library: 6021 (compatibility version 6000) but source was compiled with 5105 (compatibility version 5100).  If using a binary install, upgrade your CuDNN library to match.  If building from sources, make sure the library loaded at runtime matches a compatible version specified during compile configuration.
2017-07-09 02:29:45.364154: F c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\kernels\conv_ops.cc:671] Check failed: stream->parent()->GetConvolveAlgorithms(&algorithms)
[Finished in 22.7s with exit code 3221226505]
[shell_cmd: python -u "E:\workspace_py\convolotion_neural_net.py"]
[dir: E:\workspace_py]
[path: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\bin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\libnvvp;E:\Program Files\Python 3.5\Scripts\;E:\Program Files\Python 3.5\;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Python27\Scripts;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;E:\Program Files\MATLAB\runtime\win64;E:\Program Files\MATLAB\bin;E:\Program Files\MATLAB\polyspace\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Python27\Scripts;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;E:\Program Files\MATLAB\runtime\win64;E:\Program Files\MATLAB\bin;E:\Program Files\MATLAB\polyspace\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Users\guita\AppData\Local\Microsoft\WindowsApps;E:\Program Files\Python27\Scipts;e:\Program Files (x86)\Microsoft VS Code\bin;C:\Users\guita\AppData\Local\atom\bin]
</code>```

My pc specs (Lenovo Y50):
Nvidia GTX 960m 4 GB memory,
Intel I7 4th gen,
8 GB RAM

Python 3.5 + Tensorflow with GPU

答:
Your description 'smells' of lack of resources, most probably, memory.

If this happens every time you run the code, then the problem is probably in your code.

I suggest you profile its memory consumption with tools like memory_profiler or heapy.

If it happens only occasionally, then some other process, which runs concurrently with your Python process is consuming so many resources, that not enough is left for your Python process.

Body:
This is a tensorflow code I wrote to test convolution neural net with only 1 convolution and pooling layer with only 1 fully connected layer of 512 neurons.

My dataset is of only 2 images: http://imgur.com/et1Sn1k and http://imgur.com/ZWxOGgO

When I train my network windows gives an pop up saying "Python has stoped" (ss: http://imgur.com/tc5jWlA )

This is my code:

from scipy.misc import imread
import matplotlib.pyplot as plt
import numpy as np
import PIL.Image as Image

base_image = imread("base_image.jpg")
subject_image = imread("subject_image.jpg")

base_image = np.resize(base_image, [1024, 768, 3])
subject_image = np.resize(subject_image, [1024, 768, 3])

images = []

images.append(base_image)
images.append(subject_image)

# hyper parameters

epochs = 10
batch_size = 2
learning_rate = 0.01
n_classes = 2
import tensorflow as tf

# Model

x = tf.placeholder('float', [2, 1024, 768, 3])
y = tf.placeholder('float', [2])

weights = {
            "conv": tf.random_normal([10, 10, 3, 32]),
            "fc": tf.random_normal([-1, 512]), #7*7*64
            "out": tf.Variable(tf.random_normal([512, n_classes]))
}

conv = tf.nn.conv2d(x, filter=weights['conv'], strides=[1, 1, 1, 1], padding="SAME")
conv = tf.nn.max_pool(value=conv, ksize=[1,2,2,1], strides=[1,2,2,1], padding="SAME")

fc = tf.reshape(conv, shape=[2,-1])
fc = tf.nn.relu(tf.matmul(fc, weights['fc']))

output = tf.matmul(fc, weights['out'])

loss = tf.reduce_mean((output - y)**2)

train = tf.train.AdamOptimizer(learning_rate).minimize(loss)

sess = tf.Session()

sess.run(tf.global_variables_initializer())

for i in range(epochs):
    sess.run(train, feed_dict={x: images, y: [0, 1]})
    print(i)

Output:

2017-07-09 02:29:43.688699: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.689131: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE2 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.689504: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE3 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.689998: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.690380: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.690646: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.691117: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.691436: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:44.197766: I c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\common_runtime\gpu\gpu_device.cc:940] Found device 0 with properties:
name: GeForce GTX 960M
major: 5 minor: 0 memoryClockRate (GHz) 1.176
pciBusID 0000:01:00.0
Total memory: 4.00GiB
Free memory: 3.35GiB
2017-07-09 02:29:44.198207: I c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\common_runtime\gpu\gpu_device.cc:961] DMA: 0
2017-07-09 02:29:44.198391: I c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\common_runtime\gpu\gpu_device.cc:971] 0:   Y
2017-07-09 02:29:44.198643: I c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\common_runtime\gpu\gpu_device.cc:1030] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 960M, pci bus id: 0000:01:00.0)
2017-07-09 02:29:44.881448: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\framework\op_kernel.cc:1158] Invalid argument: Dimension -1 must be >= 0
2017-07-09 02:29:44.881875: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\framework\op_kernel.cc:1158] Invalid argument: Dimension -1 must be >= 0
     [[Node: random_normal_1/RandomStandardNormal = RandomStandardNormal[T=DT_INT32, dtype=DT_FLOAT, seed=0, seed2=0, _device="/job:localhost/replica:0/task:0/gpu:0"](random_normal_1/shape)]]
2017-07-09 02:29:44.882604: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\framework\op_kernel.cc:1158] Invalid argument: Dimension -1 must be >= 0
     [[Node: random_normal_1/RandomStandardNormal = RandomStandardNormal[T=DT_INT32, dtype=DT_FLOAT, seed=0, seed2=0, _device="/job:localhost/replica:0/task:0/gpu:0"](random_normal_1/shape)]]
2017-07-09 02:29:45.362917: E c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\stream_executor\cuda\cuda_dnn.cc:352] Loaded runtime CuDNN library: 6021 (compatibility version 6000) but source was compiled with 5105 (compatibility version 5100).  If using a binary install, upgrade your CuDNN library to match.  If building from sources, make sure the library loaded at runtime matches a compatible version specified during compile configuration.
2017-07-09 02:29:45.364154: F c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\kernels\conv_ops.cc:671] Check failed: stream->parent()->GetConvolveAlgorithms(&algorithms)
[Finished in 22.7s with exit code 3221226505]
[shell_cmd: python -u "E:\workspace_py\convolotion_neural_net.py"]
[dir: E:\workspace_py]
[path: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\bin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\libnvvp;E:\Program Files\Python 3.5\Scripts\;E:\Program Files\Python 3.5\;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Python27\Scripts;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;E:\Program Files\MATLAB\runtime\win64;E:\Program Files\MATLAB\bin;E:\Program Files\MATLAB\polyspace\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Python27\Scripts;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;E:\Program Files\MATLAB\runtime\win64;E:\Program Files\MATLAB\bin;E:\Program Files\MATLAB\polyspace\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Users\guita\AppData\Local\Microsoft\WindowsApps;E:\Program Files\Python27\Scipts;e:\Program Files (x86)\Microsoft VS Code\bin;C:\Users\guita\AppData\Local\atom\bin]

My pc specs (Lenovo Y50):
Nvidia GTX 960m 4 GB memory,
Intel I7 4th gen,
8 GB RAM

Python 3.5 + Tensorflow with GPU


问:
Taking advantage of move semantics in C++
I have a problem where I want to store vectors of structs inside individual container class.

The problem is that while creating this container for these vectors, I waste resources because the vectors are copied; not moved. Why are the resources in the temporary returned by create() not transferred to local variable master_data in the main function?

Sample code that I assumed would work is presented below (and in coliru HERE):

```<code>#include <stdio.h>
#include <vector>
#include <stdlib.h>

// Specific data struct
typedef struct DataA {
    DataA(): a(rand()),
             b(rand()) {}
    int a,b;
} DataA;

// Another specific data struct
typedef struct DataB {
    DataB(): c(rand()),
             d(rand()) {}
    int c,d;
} DataB;

// Container of all relevant data
typedef struct Master {
    Master(const std::vector<DataA> &a, const std::vector<DataB> &b) : data_a(std::move(a)), data_b(std::move(b)) {}
    Master(const Master &rhs) : data_a(std::move(rhs.data_a)), data_b(std::move(rhs.data_b)) {}

    std::vector<DataA> data_a;
    std::vector<DataB> data_b;
} Master;

Master create() {
    std::vector<DataA> data_a(10);
    std::vector<DataB> data_b(10);

    printf("data_a address inside create()   : %p\n", (void*)data_a.data());
    printf("data_b address inside create()   : %p\n", (void*)data_b.data());

    return {data_a, data_b};
}

int main()
{
    Master master_data(create());

    printf("data_a address outside create()  : %p\n", (void*)master_data.data_a.data());
    printf("data_b address outside create()  : %p\n", (void*)master_data.data_b.data());
    return 0;
}
</code>```

答:
Here:

```<code>Master(const Master &rhs) : data_a(std::move(rhs.data_a)), data_b(std::move(rhs.data_b)) {}
</code>```

the parameters are constant, which prevent them from being moved, since they are immutable.

Try using something like this instead:

```<code>Master(Master&& rhs) : data_a(std::move(rhs.data_a)), data_b(std::move(rhs.data_b)) {}
</code>```

where I dropped const and enhanced your parameter with &&.

Similarly for the constructor, you would do:

```<code>Master(std::vector<DataA>&& a, std::vector<DataB>&& b) : data_a(std::move(a)), data_b(std::move(b)) {}
</code>```

Last, but not least, you should modify your create function like so (otherwise you will get a compilation error about not being able to bind):

```<code>Master create() {
    ...
    return {std::move(data_a), std::move(data_b)};
}
</code>```

Body:
I have a problem where I want to store vectors of structs inside individual container class.

The problem is that while creating this container for these vectors, I waste resources because the vectors are copied; not moved. Why are the resources in the temporary returned by create() not transferred to local variable master_data in the main function?

Sample code that I assumed would work is presented below (and in coliru HERE):

#include <stdio.h>
#include <vector>
#include <stdlib.h>

// Specific data struct
typedef struct DataA {
    DataA(): a(rand()),
             b(rand()) {}
    int a,b;
} DataA;

// Another specific data struct
typedef struct DataB {
    DataB(): c(rand()),
             d(rand()) {}
    int c,d;
} DataB;

// Container of all relevant data
typedef struct Master {
    Master(const std::vector<DataA> &a, const std::vector<DataB> &b) : data_a(std::move(a)), data_b(std::move(b)) {}
    Master(const Master &rhs) : data_a(std::move(rhs.data_a)), data_b(std::move(rhs.data_b)) {}

    std::vector<DataA> data_a;
    std::vector<DataB> data_b;
} Master;

Master create() {
    std::vector<DataA> data_a(10);
    std::vector<DataB> data_b(10);

    printf("data_a address inside create()   : %p\n", (void*)data_a.data());
    printf("data_b address inside create()   : %p\n", (void*)data_b.data());

    return {data_a, data_b};
}

int main()
{
    Master master_data(create());

    printf("data_a address outside create()  : %p\n", (void*)master_data.data_a.data());
    printf("data_b address outside create()  : %p\n", (void*)master_data.data_b.data());
    return 0;
}

Body:
Here:

Master(const Master &rhs) : data_a(std::move(rhs.data_a)), data_b(std::move(rhs.data_b)) {}

the parameters are constant, which prevent them from being moved, since they are immutable.

Try using something like this instead:

Master(Master&& rhs) : data_a(std::move(rhs.data_a)), data_b(std::move(rhs.data_b)) {}

where I dropped const and enhanced your parameter with &&.

Similarly for the constructor, you would do:

Master(std::vector<DataA>&& a, std::vector<DataB>&& b) : data_a(std::move(a)), data_b(std::move(b)) {}

Last, but not least, you should modify your create function like so (otherwise you will get a compilation error about not being able to bind):

Master create() {
    ...
    return {std::move(data_a), std::move(data_b)};
}


答:
Your constructor:

```<code>Master(const std::vector<DataA> &a, const std::vector<DataB> &b);
</code>```

accepts the a and the b parameters as constant references. You have to define it to accept rvalue references as following:

```<code>Master(std::vector<DataA>&& a, std::vector<DataB>&& b);
</code>```

But in this case you have to indicate that data_a and data_b inside the create() function may be moved:

```<code>Master create() {
    std::vector<DataA> data_a(10);
    std::vector<DataB> data_b(10);

    printf("data_a address inside create()   : %p\n", (void*)data_a.data());
    printf("data_b address inside create()   : %p\n", (void*)data_b.data());

    return { std::move(data_a), std::move(data_b) };
}
</code>```

Title: Taking advantage of move semantics in C++

Body:
Your constructor:

Master(const std::vector<DataA> &a, const std::vector<DataB> &b);

accepts the a and the b parameters as constant references. You have to define it to accept rvalue references as following:

Master(std::vector<DataA>&& a, std::vector<DataB>&& b);

But in this case you have to indicate that data_a and data_b inside the create() function may be moved:

Master create() {
    std::vector<DataA> data_a(10);
    std::vector<DataB> data_b(10);

    printf("data_a address inside create()   : %p\n", (void*)data_a.data());
    printf("data_b address inside create()   : %p\n", (void*)data_b.data());

    return { std::move(data_a), std::move(data_b) };
}


问:
How to send PDF attachment file in gmail using PHP?
I want to send PDF attachment file in gmail account using php mailer (class.phpmailer.php) ?</p>

```<code><?php
require_once('phpmailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->From      = '';
$mail->FromName  = '';
$mail->Subject   = '';
$MESSAGE_BODY = "Name: ".$username." "."\r\n";
$MESSAGE_BODY .= "Contact No.: ".$contact." "."\r\n";
$MESSAGE_BODY .= "Message: ".$message." "."\r\n";
$mail->Body      = $MESSAGE_BODY;
$mail->AddAddress( '' );
$mail->AddAttachment($_FILES['file']['tmp_name'],
$_FILES['file']['username']);
if ($mail->Send())
{
  echo "Mail Sent";
}
else
{
echo "Could not send mail";
}
?>
</code>```

答:
PHPMailer class only lets you use Google's SMTP server.
You should send it the ordinary way. By using  $mail->AddAttachment($filePath);
If you have any specific problem please be more specific.</p>

Body:
I want to send PDF attachment file in gmail account using php mailer (class.phpmailer.php) ?

<?php
require_once('phpmailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->From      = '';
$mail->FromName  = '';
$mail->Subject   = '';
$MESSAGE_BODY = "Name: ".$username." "."\r\n";
$MESSAGE_BODY .= "Contact No.: ".$contact." "."\r\n";
$MESSAGE_BODY .= "Message: ".$message." "."\r\n";
$mail->Body      = $MESSAGE_BODY;
$mail->AddAddress( '' );
$mail->AddAttachment($_FILES['file']['tmp_name'],
$_FILES['file']['username']);
if ($mail->Send())
{
  echo "Mail Sent";
}
else
{
echo "Could not send mail";
}
?>


问:
python flask how to pass a dynamic parameter to a decorator
I am using python flask framework. I write a decorator which will be need a parameter, and this parameter will be dynamic.

my decorator like below, will be get a key ,and using the key fetch data from redis.

```<code>def redis_hash_shop_style(key):
    def fn_wrapper(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            data = redis_hash(key)
            return data
        return decorated_function
return fn_wrapper
</code>```

and I have a class to using this decorater, code like this

```<code>class ShopAreaAndStyleListAPI(Resource):
    @redis_hash_shop_style(key='shop_{}_style'.format(g.city.id))
    def get(self):
        # if not found from redis, query from mysql
        pass
</code>```

As you see, my decorator need a parameter named key, and I pass the key like this

@redis_hash_shop_style(key='shop_{}_style'.format(g.city.id))

g.city.id will be get the city's id, if everything is ok, the key will be like this

shop_100_style

but I got the error:

```<code>class ShopAreaAndStyleListAPI(Resource):
File "xx.py", line 659, in ShopAreaAndStyleListAPI

@redis_hash_shop_style(key='shop_{}_style'.format(g.city.id))

File "/Users/xx/.virtualenvs/yy/lib/python2.7/site-packages/werkzeug/local.py", line 347, in __getattr__
return getattr(self._get_current_object(), name)
File "/Users/xx/.virtualenvs/yy/lib/python2.7/site-packages/werkzeug/local.py", line 306, in _get_current_object
return self.__local()
File "/Users/xx/.virtualenvs/yy/lib/python2.7/site-packages/flask/globals.py", line 44, in _lookup_app_object
raise RuntimeError(_app_ctx_err_msg)
RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that
needed to interface with the current application object in a way.
To solve this set up an application context with app.app_context().
See the documentation for more information.
</code>```

I am quite confused , in flask, how to pass a dynamic parameter to a decorator?

Thanks.

答:
If we check the docs for flask application global, flask.g, it says:

To share data that is valid for one request only from one function to another, a global variable is not good enough because it would break in threaded environments. Flask provides you with a special object that ensures it is only valid for the active request and that will return different values for each request.

This is achieved by using a thread-local proxy (in flask/globals.py):

```<code>g = LocalProxy(partial(_lookup_app_object, 'g'))
</code>```

The other thing we should keep in mind is that Python is executing the first pass of our decorator during the "compile" phase, outside of any request, or flask application. That means key argument get assigned a value of  'shop_{}_style'.format(g.city.id) when your application starts (when your class is being parsed/decorated), outside of flask request context.

But we can easily delay accessing to flask.g by using a lazy proxy, which fetches the value only when used, via callback function. Let's use the one already bundled with flask, the werkzeug.local.LocalProxy:

```<code>from werkzeug.local import LocalProxy

class ShopAreaAndStyleListAPI(Resource):
    @redis_hash_shop_style(key=LocalProxy(lambda: 'shop_{}_style'.format(g.city.id)))
    def get(self):
        # if not found from redis, query from mysql
        pass
</code>```

In general (for non-flask or non-werkzeug apps), we can use a similar LazyProxy from the ProxyTypes package.

Unrelated to this, you'll also want to fix your redis_hash_shop_style decorator to not only fetch from redis, but to also update (or create) the value if stale (or non-existing), by calling the wrapped f() when appropriate.

Body:
I am using python flask framework. I write a decorator which will be need a parameter, and this parameter will be dynamic.

my decorator like below, will be get a key ,and using the key fetch data from redis.

def redis_hash_shop_style(key):
    def fn_wrapper(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            data = redis_hash(key)
            return data
        return decorated_function
return fn_wrapper

and I have a class to using this decorater, code like this

class ShopAreaAndStyleListAPI(Resource):
    @redis_hash_shop_style(key='shop_{}_style'.format(g.city.id))
    def get(self):
        # if not found from redis, query from mysql
        pass

As you see, my decorator need a parameter named key, and I pass the key like this

@redis_hash_shop_style(key='shop_{}_style'.format(g.city.id))

g.city.id will be get the city's id, if everything is ok, the key will be like this

shop_100_style

but I got the error:

class ShopAreaAndStyleListAPI(Resource):
File "xx.py", line 659, in ShopAreaAndStyleListAPI

@redis_hash_shop_style(key='shop_{}_style'.format(g.city.id))

File "/Users/xx/.virtualenvs/yy/lib/python2.7/site-packages/werkzeug/local.py", line 347, in __getattr__
return getattr(self._get_current_object(), name)
File "/Users/xx/.virtualenvs/yy/lib/python2.7/site-packages/werkzeug/local.py", line 306, in _get_current_object
return self.__local()
File "/Users/xx/.virtualenvs/yy/lib/python2.7/site-packages/flask/globals.py", line 44, in _lookup_app_object
raise RuntimeError(_app_ctx_err_msg)
RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that
needed to interface with the current application object in a way.
To solve this set up an application context with app.app_context().
See the documentation for more information.

I am quite confused , in flask, how to pass a dynamic parameter to a decorator?

Thanks.

Body:
If we check the docs for flask application global, flask.g, it says:

To share data that is valid for one request only from one function to another, a global variable is not good enough because it would break in threaded environments. Flask provides you with a special object that ensures it is only valid for the active request and that will return different values for each request.

This is achieved by using a thread-local proxy (in flask/globals.py):

g = LocalProxy(partial(_lookup_app_object, 'g'))

The other thing we should keep in mind is that Python is executing the first pass of our decorator during the "compile" phase, outside of any request, or flask application. That means key argument get assigned a value of  'shop_{}_style'.format(g.city.id) when your application starts (when your class is being parsed/decorated), outside of flask request context.

But we can easily delay accessing to flask.g by using a lazy proxy, which fetches the value only when used, via callback function. Let's use the one already bundled with flask, the werkzeug.local.LocalProxy:

from werkzeug.local import LocalProxy

class ShopAreaAndStyleListAPI(Resource):
    @redis_hash_shop_style(key=LocalProxy(lambda: 'shop_{}_style'.format(g.city.id)))
    def get(self):
        # if not found from redis, query from mysql
        pass

In general (for non-flask or non-werkzeug apps), we can use a similar LazyProxy from the ProxyTypes package.

Unrelated to this, you'll also want to fix your redis_hash_shop_style decorator to not only fetch from redis, but to also update (or create) the value if stale (or non-existing), by calling the wrapped f() when appropriate.


问:
Unit testing: Am I doing right when using another method in unit testing a method?
To my best knowledge, unit testing should be done on each public API separately. But, I have been experiencing with a situation in which I have not found out a clear way to unit test each API independently as shown in the following example:

```<code>class MyStorage {
private:
    std::vector<int> int_vec_;

public:
    bool insert_int(int value);
    int get_value_at(int idx);
}
</code>```

I used GooogleTest framework and wrote unit tests as follows:

```<code>int int_tenth(int x) { return x * 10; }

TEST_F(MyStorageTest, insert_int) {
    for(int i = 0; i < 10; i++) {
        int value = int_tenth(i);
        bool ret = my_storage.insert_int(value);
        ASSERT_TRUE(ret);
    }
}

TEST_F(MyStorageTest, get_value_at) {
    for(int i = 0; i < 10; i++) {
        int value = int_tenth(i);
        my_storage.insert_int(value);
    }

    for(int i = 0; i < 10; i++) {
        int expected_value = int_tenth(i);
        int value = my_storage.get_value_at(i);
        ASSERT_EQ(expected_value, value);
    }
}
</code>```

Am I doing right? If not, how can I make unit tests for this example?

答:
I think this looks "okay". Your test case is exercising both APIs - and yes, you need to use the insert method in order to test the get method.

What is missing: corner cases, especially for get. Like: having test cases for negative indixes. Or invalid indexes. Such tests should result in certain errors - and you might want to make sure that the expected errors (for example exceptions)  show up.

Beyond that you might want to look into libraries that are based on the QickCheck idea (where the test framework runs random tests to find violations of properties that you specify for your production code).

Body:
To my best knowledge, unit testing should be done on each public API separately. But, I have been experiencing with a situation in which I have not found out a clear way to unit test each API independently as shown in the following example:

class MyStorage {
private:
    std::vector<int> int_vec_;

public:
    bool insert_int(int value);
    int get_value_at(int idx);
}

I used GooogleTest framework and wrote unit tests as follows:

int int_tenth(int x) { return x * 10; }

TEST_F(MyStorageTest, insert_int) {
    for(int i = 0; i < 10; i++) {
        int value = int_tenth(i);
        bool ret = my_storage.insert_int(value);
        ASSERT_TRUE(ret);
    }
}

TEST_F(MyStorageTest, get_value_at) {
    for(int i = 0; i < 10; i++) {
        int value = int_tenth(i);
        my_storage.insert_int(value);
    }

    for(int i = 0; i < 10; i++) {
        int expected_value = int_tenth(i);
        int value = my_storage.get_value_at(i);
        ASSERT_EQ(expected_value, value);
    }
}

Am I doing right? If not, how can I make unit tests for this example?


问:
Having trouble with python object name and input string
I am having a problem with python classes and string I would like to name a class object using a string given from raw_input I don't even now if this is possible.this is how I tried to did it but the code didn't work. I searched in many posts on stackoverflow.com but none of these was answered; I am a neofite of Python, I know how classes and instance works but I don't know any function that help me to fix this problem.</p>

```<code>class example:
    def _init_(self ,name):
        self.name=name
        input1 = raw_input("")

input1 = example()
</code>```

答:
I'm not recommending that you do this, but one way to do it is with exec():

```<code>class Example:
    pass

name = raw_input("Enter name: ")
exec('{} = Example()'.format(name))
</code>```

Assuming that the user entered "abcd" at the prompt, an instance of class Example would be bound to a variable named "abcd":

```<code>>>> abcd
<__main__.Example instance at 0x7f841fb45908>
</code>```

There is rarely any genuine reason to do this,  and I do not recommend this approach because exec() can execute arbitrary user input, creating a serious security issue.

Another way is to update the globals() dictionary:

```<code>name = raw_input("Enter name: ")
globals()[name] = Example()
</code>```

but this is probably not the best thing to do either, and there is usually a better way depending on what you are trying to achieve.

A safer way could be to use a dictionary with user's input used as the key:

```<code>user_vars = {}
name = raw_input("Enter name: ")
user_vars[name] = Example()

>>> user_vars['abcd']
<__main__.Example instance at 0x7f841fb45908>
</code>```

Body:
I am having a problem with python classes and string I would like to name a class object using a string given from raw_input I don't even now if this is possible.this is how I tried to did it but the code didn't work. I searched in many posts on stackoverflow.com but none of these was answered; I am a neofite of Python, I know how classes and instance works but I don't know any function that help me to fix this problem.

class example:
    def _init_(self ,name):
        self.name=name
        input1 = raw_input("")

input1 = example()

Body:
I'm not recommending that you do this, but one way to do it is with exec():

class Example:
    pass

name = raw_input("Enter name: ")
exec('{} = Example()'.format(name))

Assuming that the user entered "abcd" at the prompt, an instance of class Example would be bound to a variable named "abcd":

>>> abcd
<__main__.Example instance at 0x7f841fb45908>

There is rarely any genuine reason to do this,  and I do not recommend this approach because exec() can execute arbitrary user input, creating a serious security issue.

Another way is to update the globals() dictionary:

name = raw_input("Enter name: ")
globals()[name] = Example()

but this is probably not the best thing to do either, and there is usually a better way depending on what you are trying to achieve.

A safer way could be to use a dictionary with user's input used as the key:

user_vars = {}
name = raw_input("Enter name: ")
user_vars[name] = Example()

>>> user_vars['abcd']
<__main__.Example instance at 0x7f841fb45908>


问:
How to use OpenStreetMap to get distance between two points
I am working on a vehicle-routing program that needs to accurately get the driving distance between different locations for a vehicle using .NET. I could have used the Google API to get the distances, but the company isn't willing to commit at least USD11,000 per year for subscription fee subject to usage volume.

I tried using the Haversine formula to get the distances, but the correction factor for the route is overwhelmingly high for it to even get close to calculating the total travel time correctly. I have spent quite some time researching OpenStreetMap, but the documentation does not have any specific examples to suit my requirements. I do not need the actual "tiles" to display the maps, only text-response with the distance would suffice.

I was hoping there would be some free to use service I could invoke within OpenStreetMap or others similar, or maybe someone could point me in the right direction to get started.

答:
OpenStreetMap does not have their own routing algorithm.

On the OpenStreetMap wiki, there's a list of software libraries that perform routing.  The Intermodal Transport Routing Information System is written in C#.

ContentLicense: CC BY-SA 4.0


问:
Need assistance to remove outdated =* join operator from SQL 2005 query
Following query no longer compatible in SQL2012 and above. Need assistance to convert.</p>

```<code>select distinct po.name , sc.name, sc2.name
from sysobjects fo, sysobjects po, sysforeignkeys fk, sysobjects oo
    , syscolumns sc, sysreferences ref, syscolumns sc2
where fo.xtype = 'F' and oo.name = @tab_name
  and po.id = fo.parent_obj and fo.id = fk.constid and oo.id = fk.rkeyid
  and sc.id = po.id and ref.constid = fk.constid and sc.colid = ref.fkey1
  and sc2.id =* po.id and sc2.colid =* ref.fkey2;
</code>```

答:
=*'s point here is to give results even when no record can be found for sc2. Therefore, that's what absolutely needs to be turned into a left join:

```<code>select distinct po.name , sc.name, sc2.name
from (sysobjects fo, sysobjects po, sysforeignkeys fk, sysobjects oo
    , syscolumns sc, sysreferences ref)
left join syscolumns sc2
  on sc2.id = po.id and sc2.colid = ref.fkey2
where fo.xtype = 'F' and oo.name = @tab_name
  and po.id = fo.parent_obj and fo.id = fk.constid and oo.id = fk.rkeyid
  and sc.id = po.id and ref.constid = fk.constid and sc.colid = ref.fkey1;
</code>```

For readability, do prefer to rewrite the rest of the old-style cross joins into inner joins as well though. You've already seen that the old-style syntax is too hard to understand.

Body:
Following query no longer compatible in SQL2012 and above. Need assistance to convert.

select distinct po.name , sc.name, sc2.name
from sysobjects fo, sysobjects po, sysforeignkeys fk, sysobjects oo
    , syscolumns sc, sysreferences ref, syscolumns sc2
where fo.xtype = 'F' and oo.name = @tab_name
  and po.id = fo.parent_obj and fo.id = fk.constid and oo.id = fk.rkeyid
  and sc.id = po.id and ref.constid = fk.constid and sc.colid = ref.fkey1
  and sc2.id =* po.id and sc2.colid =* ref.fkey2;

Body:
=*'s point here is to give results even when no record can be found for sc2. Therefore, that's what absolutely needs to be turned into a left join:

select distinct po.name , sc.name, sc2.name
from (sysobjects fo, sysobjects po, sysforeignkeys fk, sysobjects oo
    , syscolumns sc, sysreferences ref)
left join syscolumns sc2
  on sc2.id = po.id and sc2.colid = ref.fkey2
where fo.xtype = 'F' and oo.name = @tab_name
  and po.id = fo.parent_obj and fo.id = fk.constid and oo.id = fk.rkeyid
  and sc.id = po.id and ref.constid = fk.constid and sc.colid = ref.fkey1;

For readability, do prefer to rewrite the rest of the old-style cross joins into inner joins as well though. You've already seen that the old-style syntax is too hard to understand.


问:
How to add my Telegram bot to existing private channel
Is there a way to add my Telegram bot to existing private channel?
When I click 'Add to group' button on my bot's profile page, I cannot see this channel in list, though I am in this channel.</p>

答:
Bots can only be admin of a channel. You should be the creator or authorized admin of that channel to be able to add a bot as an admin of that channel.

Ask the authorized admin to add your bot to that channel, otherwise use telegram clients instead of bots. (Telegram is open source and has released cli, web, android,... source codes)


问:
why it float left is not working and these codes
my question is that why float left is not working under these codes
when i use them all the result just display on single div and other 7 where showing under that div at same place so please tell me what is the solution of this prob

```<code><div class="tv_l" style="top:1465px;
left:10px;

position:absolute;

width:1690px;
height:10px;
border-radius:3px/3px;
padding-right:10px;
padding-top:px;
border-left:10px;">

<hr>
</div>

<?php

$link = mysqli_connect("localhost" , "***" ,"***" , "***");
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
 exit();
} else {
    echo "";
}
?>
<?php
$result = mysqli_query($link, "SELECT * FROM **** ORDER BY RAND()
LIMIT 8" )
or die(mysqli_error());
while($row = mysqli_fetch_array( $result )){
?>;

<div class="son_s_p" style="top:1957px;
left:12px;
-webkit-box-shadow:0 3px 8px rgba(0, 0, 0, .25);
position:inherit;
background:white;
width:190px;
height:240px;
border-radius:3px/3px;
padding-right:10px;
padding-top:px;
border-left:10px;
text-align:center;
float:left;

">

 <img src="../lu/music/tumb/<?php echo $row['img']; ?>"style="width:198px; height:148px;"  >
<br>

 <?php echo $row['name']; ?><br><br>

 <div id="son_s_p" style="top:218px;
left:px;

position:absolute;

border-radius:3px/3px;
padding-right:10px;
padding-top:px;
border-left:10px;
text-align:justify;">

 <?php echo $row['time']; ?>    <span class="time&type" style="top;10px;"><?php echo $row['type']; ?></span>

</div>
</div>

<?php
}
?>
</code>```

with using position

without using position data will go top and top do not work

答:
your wrong is that you put in div "float: left;" and thats wrong.you should put before it style attribute and it is Style="float: left;"

correct code is:

```<code><div class="tv_l" style="top:1465px;
left:10px;

position:absolute;

width:1690px;
height:10px;
border-radius:3px/3px;
padding-right:10px;
padding-top:px;
border-left:10px;">

<hr>
</div>

<?php

$link = mysqli_connect("localhost" , "***" ,"***" , "***");
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
 exit();
} else {
    echo "";
}
?>
<?php
$result = mysqli_query($link, "SELECT * FROM **** ORDER BY RAND()
LIMIT 8" )
or die(mysqli_error());
while($row = mysqli_fetch_array( $result )){
?>;

<div class="son_s_p" style="top:1957px;
left:12px;
-webkit-box-shadow:0 3px 8px rgba(0, 0, 0, .25);
position:inherit;
background:white;
width:190px;
height:240px;
border-radius:3px/3px;
padding-right:10px;
padding-top:px;
border-left:10px;
text-align:center;
float:left;

">

 <img src="../lu/music/tumb/<?php echo $row['img']; ?>"style="width:198px; height:148px;"  >
<br>

 <?php echo $row['name']; ?><br><br>

 <div id="son_s_p" style="top:218px;
left:px;

position:absolute;

border-radius:3px/3px;
padding-right:10px;
padding-top:px;
border-left:10px;
text-align:justify;">

 <?php echo $row['time']; ?>    <span class="time&type" style="top;10px;"><?php echo $row['type']; ?></span>

</div>
</div>

<?php
}
?>
</code>```

Body:
my question is that why float left is not working under these codes
when i use them all the result just display on single div and other 7 where showing under that div at same place so please tell me what is the solution of this prob

<?php

$link = mysqli_connect("localhost" , "***" ,"***" , "***");
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
 exit();
} else {
    echo "";
}
?>
<?php
$result = mysqli_query($link, "SELECT * FROM **** ORDER BY RAND()
LIMIT 8" )
or die(mysqli_error());
while($row = mysqli_fetch_array( $result )){
?>;

 <img src="../lu/music/tumb/<?php echo $row['img']; ?>"style="width:198px; height:148px;"  >

 <?php echo $row['name']; ?>

 <?php echo $row['time']; ?>    <?php echo $row['type']; ?>

<?php
}
?>

with using position

without using position data will go top and top do not work

Body:
your wrong is that you put in div "float: left;" and thats wrong.you should put before it style attribute and it is Style="float: left;"

correct code is:

<div class="tv_l" style="top:1465px;
left:10px;

position:absolute;

width:1690px;
height:10px;
border-radius:3px/3px;
padding-right:10px;
padding-top:px;
border-left:10px;">

<hr>
</div>

<?php

$link = mysqli_connect("localhost" , "***" ,"***" , "***");
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
 exit();
} else {
    echo "";
}
?>
<?php
$result = mysqli_query($link, "SELECT * FROM **** ORDER BY RAND()
LIMIT 8" )
or die(mysqli_error());
while($row = mysqli_fetch_array( $result )){
?>;

<div class="son_s_p" style="top:1957px;
left:12px;
-webkit-box-shadow:0 3px 8px rgba(0, 0, 0, .25);
position:inherit;
background:white;
width:190px;
height:240px;
border-radius:3px/3px;
padding-right:10px;
padding-top:px;
border-left:10px;
text-align:center;
float:left;

">

 <img src="../lu/music/tumb/<?php echo $row['img']; ?>"style="width:198px; height:148px;"  >
<br>

 <?php echo $row['name']; ?><br><br>

 <div id="son_s_p" style="top:218px;
left:px;

position:absolute;

border-radius:3px/3px;
padding-right:10px;
padding-top:px;
border-left:10px;
text-align:justify;">

&nbsp;<?php echo $row['time']; ?> &nbsp; &nbsp;<span class="time&amp;type" style="top;10px;"><?php echo $row['type']; ?></span>

</div>
</div>

<?php
}
?>


问:
How can I change default python shell version?
I am using Windows 10, and I have python 2.7 and 3.6 installed. I want to open a .py file in IDLE 3.6, but when I try to open it, it opens in 2.7. How can I change the default?</p>

答:
There are different versions of IDLE installed for each Python version. Depending on how you installed Python on Mac OS X, you may find different folders in /Applications. Look for a Python 3.n (n = 1 or 2) folder with an IDLE in it. Or, from a terminal command line, you may find an idle2.6 and an idle3 or idle3.1 or idle3.2.

https://stackoverflow.com/a/4776403/3900156


答:
What you want is the str_pad function, check out the documentation. It will left or right pad a string with another string to a given length.

```<code>foreach ($outMonth as $key => $value) {
    $outMonth[$key] = str_pad($value, 2, '0', STR_PAD_LEFT);
}
</code>```

Title: php array update values if string length is equal to 1

Body:
I have an array like this:

array(53) { [0]=> string(2) "11" [1]=> string(1) "1" [2]=> string(2) "11" [3]=> string(1) "7" [4]=> string(2) "11" [5]=> string(1) "7" [6]=> string(2) "10" [7]=> string(2) "10" [8]=> string(1) "9" [9]=> string(1) "8" [10]=> string(1) "8" [11]=> string(2) "12" [12]=> string(1) "6" [13]=> string(2) "10" [14]=> string(2) "10" [15]=> string(2) "12" [16]=> string(1) "2" [17]=> string(1) "3" [18]=> string(1) "8" [19]=> string(1) "5" [20]=> string(1) "4" [21]=> string(1) "3" [22]=> string(1) "2" [23]=> string(1) "2" [24]=> string(1) "3" [25]=> string(1) "7" [26]=> string(1) "3" [27]=> string(1) "6" [28]=> string(1) "9" [29]=> string(1) "3" [30]=> string(1) "3" [31]=> string(2) "12" [32]=> string(2) "12" [33]=> string(1) "1" [34]=> string(2) "12" [35]=> string(1) "5" [36]=> string(1) "2" [37]=> string(1) "8" [38]=> string(1) "6" [39]=> string(1) "9" [40]=> string(1) "9" [41]=> string(2) "10" [42]=> string(1) "1" [43]=> string(1) "2" [44]=> string(1) "3" [45]=> string(2) "10" [46]=> string(1) "7" [47]=> string(1) "4" [48]=> string(2) "11" [49]=> string(2) "12" [50]=> string(1) "1" [51]=> string(1) "9" [52]=> string(1) "9" }

I want to every value in this array to have two character length, if array value is:9 to change to 09.

With this I can`t achieve... somewhere I missed something

foreach ($outMonth as $key => $value) {
    if (strlen($outMonth[$value]) == 1 ) {
        $outMonth[$value] = "0".$value;
        //echo (strlen($outMonth[$value])). "
";
    }
}

If I dump, I got:

array(53) { [0]=> string(2) "11" [1]=> string(2) "01" [2]=> string(2) "11" [3]=> string(2) "03" [4]=> string(2) "11" [5]=> string(2) "05" [6]=> string(2) "10" [7]=> string(2) "10" [8]=> string(2) "08" [9]=> string(2) "09" [10]=> string(3) "010" [11]=> string(2) "12" [12]=> string(3) "012" [13]=> string(2) "10" [14]=> string(2) "10" [15]=> string(2) "12" [16]=> string(1) "2" [17]=> string(1) "3" [18]=> string(1) "8" [19]=> string(1) "5" [20]=> string(1) "4" [21]=> string(1) "3" [22]=> string(1) "2" [23]=> string(1) "2" [24]=> string(1) "3" [25]=> string(1) "7" [26]=> string(1) "3" [27]=> string(1) "6" [28]=> string(1) "9" [29]=> string(1) "3" [30]=> string(1) "3" [31]=> string(2) "12" [32]=> string(2) "12" [33]=> string(1) "1" [34]=> string(2) "12" [35]=> string(1) "5" [36]=> string(1) "2" [37]=> string(1) "8" [38]=> string(1) "6" [39]=> string(1) "9" [40]=> string(1) "9" [41]=> string(2) "10" [42]=> string(1) "1" [43]=> string(1) "2" [44]=> string(1) "3" [45]=> string(2) "10" [46]=> string(1) "7" [47]=> string(1) "4" [48]=> string(2) "11" [49]=> string(2) "12" [50]=> string(1) "1" [51]=> string(1) "9" [52]=> string(1) "9" }

You can see that only few values are changed...

Thanks your time!

Body:
What you want is the str_pad function, check out the documentation. It will left or right pad a string with another string to a given length.

foreach ($outMonth as $key => $value) {
    $outMonth[$key] = str_pad($value, 2, '0', STR_PAD_LEFT);
}


问:
Forcasting Data with Arima Model in R
I am a beginner in the R language, I have a monthly data list for requests received quantities by product, how I can make the forecast with ARIMA model (best model) can any kind of data.
I used the code below but I don’t know if the results are correct and reliable or I have to change another model or a simple change in this code.

Script :

```<code>#Step 1: Plot Qty data as time series

data <- structure(c(3108L, 2508L, 3516L, 3828L, 3755L, 6612L, 6708L,
  3624L, 4032L, 4104L, 3000L, 3204L, 2640L, 2124L, 1884L, 12382L,
  1488L, 1356L, 2028L, 1764L, 1524L, 7248L, 1248L, 816L, 804L,
  708L, 756L, 972L, 4104L, 1296L, 2268L, 588L, 768L, 792L, 744L,
  1680L, 684L, 2052L, 672L, 492L, 744L, 768L, 828L, 936L, 840L,
  5364L, 408L, 528L, 60L, 612L, 684L, 852L, 756L, 972L),
  .Tsp = c(2013, 2017.41666666667, 12), class = "ts")

plot(data, xlab='Years', ylab = ' Qty ')

# Step 2: Difference data to make data stationary on mean (remove trend)
plot(diff(data),ylab='Differenced Qty')

#Step 3: log transform data to make data stationary on variance
plot(log10(data),ylab='Log (Qty)')

#Step 4: Difference log transform data to make data stationary on both mean and variance
plot(diff(log10(data)),ylab='Differenced Log (Qty)')

# Step 5: Plot ACF and PACF to identify potential AR and MA model
par(mfrow = c(1,2))
acf(ts(diff(log10(data))),main='ACF Qty')
pacf(ts(diff(log10(data))),main='PACF Qty ')

# Step 6: Identification of best fit ARIMA model

require(forecast)
ARIMAfit = auto.arima(log10(data), approximation=FALSE,trace=FALSE)
summary(ARIMAfit)

# Step 6: Forecast sales using the best fit ARIMA model
par(mfrow = c(1,1))
pred = predict(ARIMAfit, n.ahead = 36)
pred
plot(data,type='l',xlim=c(2004,2018),ylim=c(1,1600),xlab = 'Year',ylab = ' Qty ')
lines(10^(pred$pred),col='blue')
lines(10^(pred$pred+2*pred$se),col='orange')
lines(10^(pred$pred-2*pred$se),col='orange')

# Step 7: Plot ACF and PACF for residuals of ARIMA model to ensure no more information is left for extraction
par(mfrow=c(1,2))
acf(ts(ARIMAfit$residuals),main='ACF Residual')
</code>```

答:
You're making it a little more complicated than it needs to be. auto.arima will determine the number of AR, MA, and differencing terms to use automatically.

Here is a link to read more on it.

Ultimately, if you just want the code for the fit though you could do this

```<code>library(forecast)
data = ts(data[,2],start = c(2013,1),frequency = 12)
model = auto.arima(data)
</code>```

We can look at the summary of the model to determine which model it fit

```<code>> summary(model)
Series: dat
ARIMA(0,1,1)

Coefficients:
          ma1
      -0.8501
s.e.   0.0591

sigma^2 estimated as 4166267:  log likelihood=-479.27
AIC=962.53   AICc=962.77   BIC=966.47
</code>```

So, we have ARIMA(0, 1, 1). There is one difference and 1 MA term in the model that it picked automatically.

If we forecast the model we can plot it like so

```<code>plot(forecast(model,h=12),include=24)
</code>```

The reason that we don't see the spikes like we did in the previous data is that the model isn't including any seasonal parameters. Looking at  the plot it doesn't seem like the peaks happen in the same time frame. If the peaks are related to some event those need to be included in the model and this could be  done using the xreg parameter having a binary indicator  for the event.

Title: Forcasting Data with Arima Model in R

Body:
I am a beginner in the R language, I have a monthly data list for requests received quantities by product, how I can make the forecast with ARIMA model (best model) can any kind of data.
I used the code below but I don’t know if the results are correct and reliable or I have to change another model or a simple change in this code.

Script :

#Step 1: Plot Qty data as time series

data <- structure(c(3108L, 2508L, 3516L, 3828L, 3755L, 6612L, 6708L,
  3624L, 4032L, 4104L, 3000L, 3204L, 2640L, 2124L, 1884L, 12382L,
  1488L, 1356L, 2028L, 1764L, 1524L, 7248L, 1248L, 816L, 804L,
  708L, 756L, 972L, 4104L, 1296L, 2268L, 588L, 768L, 792L, 744L,
  1680L, 684L, 2052L, 672L, 492L, 744L, 768L, 828L, 936L, 840L,
  5364L, 408L, 528L, 60L, 612L, 684L, 852L, 756L, 972L),
  .Tsp = c(2013, 2017.41666666667, 12), class = "ts")

plot(data, xlab='Years', ylab = ' Qty ')

# Step 2: Difference data to make data stationary on mean (remove trend)
plot(diff(data),ylab='Differenced Qty')

#Step 3: log transform data to make data stationary on variance
plot(log10(data),ylab='Log (Qty)')

#Step 4: Difference log transform data to make data stationary on both mean and variance
plot(diff(log10(data)),ylab='Differenced Log (Qty)')

# Step 5: Plot ACF and PACF to identify potential AR and MA model
par(mfrow = c(1,2))
acf(ts(diff(log10(data))),main='ACF Qty')
pacf(ts(diff(log10(data))),main='PACF Qty ')

# Step 6: Identification of best fit ARIMA model

require(forecast)
ARIMAfit = auto.arima(log10(data), approximation=FALSE,trace=FALSE)
summary(ARIMAfit)

# Step 6: Forecast sales using the best fit ARIMA model
par(mfrow = c(1,1))
pred = predict(ARIMAfit, n.ahead = 36)
pred
plot(data,type='l',xlim=c(2004,2018),ylim=c(1,1600),xlab = 'Year',ylab = ' Qty ')
lines(10^(pred$pred),col='blue')
lines(10^(pred$pred+2*pred$se),col='orange')
lines(10^(pred$pred-2*pred$se),col='orange')

# Step 7: Plot ACF and PACF for residuals of ARIMA model to ensure no more information is left for extraction
par(mfrow=c(1,2))
acf(ts(ARIMAfit$residuals),main='ACF Residual')

Body:
You're making it a little more complicated than it needs to be. auto.arima will determine the number of AR, MA, and differencing terms to use automatically.

Here is a link to read more on it.

Ultimately, if you just want the code for the fit though you could do this

library(forecast)
data = ts(data[,2],start = c(2013,1),frequency = 12)
model = auto.arima(data)

We can look at the summary of the model to determine which model it fit

> summary(model)
Series: dat
ARIMA(0,1,1)

Coefficients:
          ma1
      -0.8501
s.e.   0.0591

sigma^2 estimated as 4166267:  log likelihood=-479.27
AIC=962.53   AICc=962.77   BIC=966.47

So, we have ARIMA(0, 1, 1). There is one difference and 1 MA term in the model that it picked automatically.

If we forecast the model we can plot it like so

plot(forecast(model,h=12),include=24)

The reason that we don't see the spikes like we did in the previous data is that the model isn't including any seasonal parameters. Looking at  the plot it doesn't seem like the peaks happen in the same time frame. If the peaks are related to some event those need to be included in the model and this could be  done using the xreg parameter having a binary indicator  for the event.


问:
Why won't my external image load in my Silverlight Page?
To make this as simple as possible, I created a new default Silverlight 4 Application and added an Images folder to the test web site that is automatically created when the application is generated.  I put the same image, let's call it "imageName.png" in the ClientBin folder and the Images folder.  Now, everything works fine when I just use the image in ClientBin using XAML like this:

```<code><Grid x:Name="LayoutRoot" Background="White">
    <StackPanel>
        <Image Source="imageName.png" Width="16" Height="16"/>
        <TextBox Text="Hello" />
    </StackPanel>
</Grid>
</code>```

But the image doesn't load when I try to access the image in the Images folder like this:

```<code><Grid x:Name="LayoutRoot" Background="White">
    <StackPanel>
        <Image Source="../Images/imageName.png" Width="16" Height="16"/>
        <TextBox Text="Hello" />
    </StackPanel>
</Grid>
</code>```

I don't get any errors, but the image just isn't there.  Can anyone tell me what's going on?  Everything I've been able to find seems to suggest that this should work.

答:
The problem here is that the folder containing the Xap and the top content in the Xap itself is considered to be at the root of the path.  Hence the path "/" maps to the top content in Xap and the folder where the Xap is sited (usually ClientBin).  Any attempt to use a parent path past what is considered the root will result in a Silverlight Network Error.

Any content outside of the folder that the Xap is found in can only be accessed using an absolute Uri.

What need to do then is convert the relative address containing a parent path to an absolute address before passing it to the Image.Source property.  Preferably we would want to avoid hardcoding the base absolute address into the source code.

We can get the current acquire the absolute Url for the Xap using the BaseAddress property of the WebClient object.  From that we can compose the desired absolute address by combining it with the relative address even one that contains a parent path.

A value converter can make this easier in Xaml:-

```<code>public class WebRelativeConverter : IValueConverter
{
    public Uri Base { get; set; }

    public WebRelativeConverter()
    {
        Base = new Uri((new WebClient()).BaseAddress, UriKind.Absolute);
    }

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        Uri result = null;

        if (value is Uri)
        {
            result = new Uri(Base, (Uri)value);
        }
        else if (value != null)
        {
            result = new Uri(Base, value.ToString());
        }
        return result;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
</code>```

Now a fixed value in Xaml would look like this:-

```<code><Grid x:Name="LayoutRoot" Background="White">
    <Grid.Resources>
         <local:WebRelativeConverter x:Key="wrc" />
    </Grid.Resources>
    <StackPanel>
        <Image DataContext="../Images/imageName.png" Source="{Binding Converter={StaticResource wrc}}" Width="16" Height="16"/>
        <TextBox Text="Hello" />
    </StackPanel>
</Grid>
</code>```

Now if you actually were binding the source to a Uri or String property of some object you only need to add the converter and it should work.

Body:
To make this as simple as possible, I created a new default Silverlight 4 Application and added an Images folder to the test web site that is automatically created when the application is generated.  I put the same image, let's call it "imageName.png" in the ClientBin folder and the Images folder.  Now, everything works fine when I just use the image in ClientBin using XAML like this:

<Grid x:Name="LayoutRoot" Background="White">
    <StackPanel>
        <Image Source="imageName.png" Width="16" Height="16"/>
        <TextBox Text="Hello" />
    </StackPanel>
</Grid>

But the image doesn't load when I try to access the image in the Images folder like this:

<Grid x:Name="LayoutRoot" Background="White">
    <StackPanel>
        <Image Source="../Images/imageName.png" Width="16" Height="16"/>
        <TextBox Text="Hello" />
    </StackPanel>
</Grid>

I don't get any errors, but the image just isn't there.  Can anyone tell me what's going on?  Everything I've been able to find seems to suggest that this should work.

Body:
The problem here is that the folder containing the Xap and the top content in the Xap itself is considered to be at the root of the path.  Hence the path "/" maps to the top content in Xap and the folder where the Xap is sited (usually ClientBin).  Any attempt to use a parent path past what is considered the root will result in a Silverlight Network Error.

Any content outside of the folder that the Xap is found in can only be accessed using an absolute Uri.

What need to do then is convert the relative address containing a parent path to an absolute address before passing it to the Image.Source property.  Preferably we would want to avoid hardcoding the base absolute address into the source code.

We can get the current acquire the absolute Url for the Xap using the BaseAddress property of the WebClient object.  From that we can compose the desired absolute address by combining it with the relative address even one that contains a parent path.

A value converter can make this easier in Xaml:-

public class WebRelativeConverter : IValueConverter
{
    public Uri Base { get; set; }

    public WebRelativeConverter()
    {
        Base = new Uri((new WebClient()).BaseAddress, UriKind.Absolute);
    }

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        Uri result = null;

        if (value is Uri)
        {
            result = new Uri(Base, (Uri)value);
        }
        else if (value != null)
        {
            result = new Uri(Base, value.ToString());
        }
        return result;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Now a fixed value in Xaml would look like this:-

<Grid x:Name="LayoutRoot" Background="White">
    <Grid.Resources>
         <local:WebRelativeConverter x:Key="wrc" />
    </Grid.Resources>
    <StackPanel>
        <Image DataContext="../Images/imageName.png" Source="{Binding Converter={StaticResource wrc}}" Width="16" Height="16"/>
        <TextBox Text="Hello" />
    </StackPanel>
</Grid>

Now if you actually were binding the source to a Uri or String property of some object you only need to add the converter and it should work.


问:
Angular cli with webpack: not refreshing executed code with build?
I'm building an angular-cli based web app. I had an error in my chrome developer tools console, which I think is now resolved in my code. However when I rebuild and refresh my browser (and even delete my browser cache), I still see the error!

The error has to do with a shared component I am importing from an external library that I'm building.

Here it is:

```<code>compiler.es5.js:1689 Uncaught Error: Can't resolve all parameters for AuthService: (?, [object Object]).
at syntaxError (compiler.es5.js:1689)
at CompileMetadataResolver.webpackJsonp.../../../compiler/@angular/compiler.es5.js.CompileMetadataResolver._getDependenciesMetadata (compiler.es5.js:15756)
at CompileMetadataResolver.webpackJsonp.../../../compiler/@angular/compiler.es5.js.CompileMetadataResolver._getTypeMetadata (compiler.es5.js:15624)
at CompileMetadataResolver.webpackJsonp.../../../compiler/@angular/compiler.es5.js.CompileMetadataResolver._getInjectableMetadata (compiler.es5.js:15610)
at CompileMetadataResolver.webpackJsonp.../../../compiler/@angular/compiler.es5.js.CompileMetadataResolver.getProviderMetadata (compiler.es5.js:15901)
at compiler.es5.js:15830
at Array.forEach (<anonymous>)
at CompileMetadataResolver.webpackJsonp.../../../compiler/@angular/compiler.es5.js.CompileMetadataResolver._getProvidersMetadata (compiler.es5.js:15790)
at compiler.es5.js:15365
at Array.forEach (<anonymous>)
</code>```

When I run ng serve --prod, the error disappears and my code runs beautifully.
Then, if I run ng serve again, without the --prod, I see the error again.

This is driving me nuts.

What might be causing this? Does webpack cache? If so, how can I refresh so my newest code is being run?

Thanks in advance for your help.

答:
I've seen this happen too (not always though). By default, the browser caches the bundles, and when you use ng serve, the name of your bundle remains the same. The reason you don't see this error with ng serve -prod is that each production build has a different hash code in the bundle name so the browser doesn't use the cached version.

If you run the browser in the incognito mode you shouldn't have this issue.

Body:
I'm building an angular-cli based web app. I had an error in my chrome developer tools console, which I think is now resolved in my code. However when I rebuild and refresh my browser (and even delete my browser cache), I still see the error!

The error has to do with a shared component I am importing from an external library that I'm building.

Here it is:

compiler.es5.js:1689 Uncaught Error: Can't resolve all parameters for AuthService: (?, [object Object]).
at syntaxError (compiler.es5.js:1689)
at CompileMetadataResolver.webpackJsonp.../../../compiler/@angular/compiler.es5.js.CompileMetadataResolver._getDependenciesMetadata (compiler.es5.js:15756)
at CompileMetadataResolver.webpackJsonp.../../../compiler/@angular/compiler.es5.js.CompileMetadataResolver._getTypeMetadata (compiler.es5.js:15624)
at CompileMetadataResolver.webpackJsonp.../../../compiler/@angular/compiler.es5.js.CompileMetadataResolver._getInjectableMetadata (compiler.es5.js:15610)
at CompileMetadataResolver.webpackJsonp.../../../compiler/@angular/compiler.es5.js.CompileMetadataResolver.getProviderMetadata (compiler.es5.js:15901)
at compiler.es5.js:15830
at Array.forEach (<anonymous>)
at CompileMetadataResolver.webpackJsonp.../../../compiler/@angular/compiler.es5.js.CompileMetadataResolver._getProvidersMetadata (compiler.es5.js:15790)
at compiler.es5.js:15365
at Array.forEach (<anonymous>)

When I run ng serve --prod, the error disappears and my code runs beautifully.
Then, if I run ng serve again, without the --prod, I see the error again.

This is driving me nuts.

What might be causing this? Does webpack cache? If so, how can I refresh so my newest code is being run?

Thanks in advance for your help.