问:
Parsing a JSONArray inside a keyless JSONArray using Gson
I had just started doing android development recently and I have come up with a json that looks like this,

```<code>"rows": [

    [
        { "val": "abc",
          "val1":"cde"
        },

        { "val": "efg",
          "val1":"hij"
        },
    ],

    [
        { "val": "klm",
          "val1":"nop"
        },

        { "val": "qrs",
          "val1":"tuv"
        },
    ],
    ........
    ........
    ........
]
</code>```

Now as you can see the outer array has no keys but the inner ones do. I am using Gson for parsing the json. How should i approach to create a model class for this json? Any help would be appreciated!!

答:
First of all, this JSON string looks invalid. There shouldn't be a comma after the second element of every two-element inner array. And wrap the whole thing in {} brackets. Like this:

```<code>{"rows": [
    [
        { "val": "abc",
          "val1":"cde"
        },
        { "val": "efg",
          "val1":"hij"
        }
    ],
    [
        { "val": "klm",
          "val1":"nop"
        },
        { "val": "qrs",
          "val1":"tuv"
        }
    ]
]}
</code>```

If you correct those, you can parse it with GSON like this:

```<code>    JsonElement root = new JsonParser().parse(jstring);
    root.getAsJsonObject().get("rows")
        .getAsJsonArray().forEach(innerArray -> {
            innerArray.getAsJsonArray().forEach(element -> {
                System.out.println("val equals "+element.getAsJsonObject().get("val"));
                System.out.println("val1 equals "+element.getAsJsonObject().get("val1"));
            });
    });
</code>```

Obviously, instead of printing you can do whatever you like with those parsed values.

Body:
I had just started doing android development recently and I have come up with a json that looks like this,

"rows": [

    [
        { "val": "abc",
          "val1":"cde"
        },

        { "val": "efg",
          "val1":"hij"
        },
    ],

    [
        { "val": "klm",
          "val1":"nop"
        },

        { "val": "qrs",
          "val1":"tuv"
        },
    ],
    ........
    ........
    ........
]

Now as you can see the outer array has no keys but the inner ones do. I am using Gson for parsing the json. How should i approach to create a model class for this json? Any help would be appreciated!!

Body:
First of all, this JSON string looks invalid. There shouldn't be a comma after the second element of every two-element inner array. And wrap the whole thing in {} brackets. Like this:

{"rows": [
    [
        { "val": "abc",
          "val1":"cde"
        },
        { "val": "efg",
          "val1":"hij"
        }
    ],
    [
        { "val": "klm",
          "val1":"nop"
        },
        { "val": "qrs",
          "val1":"tuv"
        }
    ]
]}

If you correct those, you can parse it with GSON like this:

    JsonElement root = new JsonParser().parse(jstring);
    root.getAsJsonObject().get("rows")
        .getAsJsonArray().forEach(innerArray -> {
            innerArray.getAsJsonArray().forEach(element -> {
                System.out.println("val equals "+element.getAsJsonObject().get("val"));
                System.out.println("val1 equals "+element.getAsJsonObject().get("val1"));
            });
    });

Obviously, instead of printing you can do whatever you like with those parsed values.


来源: stackexchange

问:
Accessing elements in JSON array
I haven't worked much with JSON and I'm using Google Maps Distance Matrix API to get generate some data I'd like to use.

I'd like to pull the number 14147 from duration.

```<code>{
   "destination_addresses" : [ "Washington, DC, USA" ],
   "origin_addresses" : [ "New York, NY, USA" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "226 mi",
                  "value" : 364089
               },
               "duration" : {
                  "text" : "3 hours 56 mins",
                  "value" : 14147
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}
</code>```

I've tried a few different things, here's what I tried last (data is just the array above):

```<code>String data = getOutputAsText(geoService);
JSONObject json = new JSONObject(data);
String duration = json.getJSONArray("rows").getString("duration");
</code>```

Here's the console output:

```<code> org.json.JSONException: JSONObject["duration"] not found
</code>```

I made sure to look around before posting but I haven't found anything that has been able to help me with this particular problem.

I want to pass the value from duration to my own web service, which I can do, I just don't know how to extract the value.  Thank you in advance!

答:
First of all, please have a look at this answer. Using org.json you can do smth. like that:

```<code>JSONObject obj = new JSONObject("Content of your string here");
JSONArray rows = obj.getJSONArray("rows");
for (int i = 0; i < rows.length(); i++) {
 JSONArray elements = rows.getJSONObject(i).getJSONArray("elements");
  for(int j = 0; j < elements.length(); j++) {
   JSONObject element = elements.getJSONObject(j);
   JSONObject duration = element.getJSONObject("duration");
   int value = duration.getInt("value");
  }
 }
</code>```

The code above has produced following output using your json String: 14147

P.S. You can make use of a library you wish. This one used here was purposed for the demonstrating.

ContentLicense: CC BY-SA 3.0

Title: Accessing elements in JSON array

Body:
I haven't worked much with JSON and I'm using Google Maps Distance Matrix API to get generate some data I'd like to use.

I'd like to pull the number 14147 from duration.

{
   "destination_addresses" : [ "Washington, DC, USA" ],
   "origin_addresses" : [ "New York, NY, USA" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "226 mi",
                  "value" : 364089
               },
               "duration" : {
                  "text" : "3 hours 56 mins",
                  "value" : 14147
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

I've tried a few different things, here's what I tried last (data is just the array above):

String data = getOutputAsText(geoService);
JSONObject json = new JSONObject(data);
String duration = json.getJSONArray("rows").getString("duration");

Here's the console output:

 org.json.JSONException: JSONObject["duration"] not found

I made sure to look around before posting but I haven't found anything that has been able to help me with this particular problem.

I want to pass the value from duration to my own web service, which I can do, I just don't know how to extract the value.  Thank you in advance!

Body:
First of all, please have a look at this answer. Using org.json you can do smth. like that:

JSONObject obj = new JSONObject("Content of your string here");
JSONArray rows = obj.getJSONArray("rows");
for (int i = 0; i < rows.length(); i++) {
 JSONArray elements = rows.getJSONObject(i).getJSONArray("elements");
  for(int j = 0; j < elements.length(); j++) {
   JSONObject element = elements.getJSONObject(j);
   JSONObject duration = element.getJSONObject("duration");
   int value = duration.getInt("value");
  }
 }

The code above has produced following output using your json String: 14147

P.S. You can make use of a library you wish. This one used here was purposed for the demonstrating.


问:
Can't get ImageMagick working on MediaWiki
The problem:

For some reason I can't get ImageMagick working on MediaWiki site. MediaWiki installed on Linux server. MediaWiki: 1.16.4. PHP: 5.2.17. ImageMagick: 6.6.0-4 2010-11-16 Q16

Using the next configuration in LocalSettings.php

```<code>$wgEnableUploads = true;
$wgUseImageMagick = true;
$wgImageMagickConvertCommand = "/usr/bin/convert";
$wgFileExtensions[] = 'svg';
$wgSVGConverter = 'ImageMagick';
</code>```

path /usr/bin/convert available from the home directory. /image has the permissions: drwxt-xr-x.

As soon as I enable ImageMagick ($wgUseImageMagick = true;) all thumbnail generation stopping working (even for PNG, JPG, GIF). I get error message on all generated thumbnails: "Error creating thumbnail:" (without any additional message). If I disable it, that it works fine for PNG, GIF and JPG formats. But the problem that I have to support SVG format as well...

Any ideas how I can get ImageMagick working?

Regards,
Alex

答:
You must edit the file policy.xml (try `find -name policy.xml, the location may vary depending on your OS) using sudo and your preferred text editor and perform the following changes:

Remove:

```<code><policy domain="coder" rights="none" pattern="MVG" />
</code>```

And add this line:

```<code><policy domain="coder" rights="read | write" pattern="MSVG" />
</code>```

Save the file and try to upload another svg file. The error must be gone away.

Body:
The problem:

For some reason I can't get ImageMagick working on MediaWiki site. MediaWiki installed on Linux server. MediaWiki: 1.16.4. PHP: 5.2.17. ImageMagick: 6.6.0-4 2010-11-16 Q16

Using the next configuration in LocalSettings.php

$wgEnableUploads = true;
$wgUseImageMagick = true;
$wgImageMagickConvertCommand = "/usr/bin/convert";
$wgFileExtensions[] = 'svg';
$wgSVGConverter = 'ImageMagick';

path /usr/bin/convert available from the home directory. /image has the permissions: drwxt-xr-x.

As soon as I enable ImageMagick ($wgUseImageMagick = true;) all thumbnail generation stopping working (even for PNG, JPG, GIF). I get error message on all generated thumbnails: "Error creating thumbnail:" (without any additional message). If I disable it, that it works fine for PNG, GIF and JPG formats. But the problem that I have to support SVG format as well...

Any ideas how I can get ImageMagick working?

Regards,
Alex

Body:
You must edit the file policy.xml (try `find -name policy.xml, the location may vary depending on your OS) using sudo and your preferred text editor and perform the following changes:

Remove:

<policy domain="coder" rights="none" pattern="MVG" />

And add this line:

<policy domain="coder" rights="read | write" pattern="MSVG" />

Save the file and try to upload another svg file. The error must be gone away.


问:
What is the universal runtime component #ifdef for windows (UWP) not iOS?
I'm trying to build a universal runtime component using cross-platform C++ code in a git submodule. I need to figure out what the #ifdef is for when I want code to build for the universal runtime component (UWP) and not for xcode on iOS.

```<code>#ifdef __WINDOWS_ONLY_COMPILE_FLAG?
    // some code i want to compile on windows
#endif
</code>```

答: By default, Universal Windows projects get the WINDOWS_UWP compiler directive defined.

Body:
I'm trying to build a universal runtime component using cross-platform C++ code in a git submodule. I need to figure out what the #ifdef is for when I want code to build for the universal runtime component (UWP) and not for xcode on iOS.

#ifdef __WINDOWS_ONLY_COMPILE_FLAG?
    // some code i want to compile on windows
#endif


问:
Keras Fully-Connected Dense Output M x N?
I am looking at the examples/image_orc.py example in Keras, when I run it I see something like

```<code>_______________
max2 (MaxPooling2D)              (None, 32, 16, 16)    0           conv2[0][0]
____________________________________________________________________________________________________
reshape (Reshape)                (None, 32, 256)       0           max2[0][0]
____________________________________________________________________________________________________
dense1 (Dense)                   (None, 32, 32)        8224        reshape[0][0]
_____________________________________________________________________________________
</code>```

The Dense layer outputs a tensor 32x32. I am trying to replicate this in pur TensorFlow where tf.matmul would be used, but how can I output 32x32 using matmul?

Addition:

I am not trying to replicate the Keras example exactly,

```<code>w = 128; h = 64
# junk image, only one
dataset = np.zeros((1,w,h,1))

import tensorflow as tf

pool_size = 1
num_filters = 16

def weight_variable(shape):
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)

def bias_variable(shape):
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)

def conv2d(x, W):
  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                        strides=[1, 2, 2, 1], padding='SAME')

inputs = tf.placeholder(tf.float32, [None, w, h, 1])

W_conv1 = weight_variable([3, 3, 1, num_filters])
b_conv1 = bias_variable([num_filters])
h_conv1 = tf.nn.relu(conv2d(inputs, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)

W_conv2 = weight_variable([3, 3, num_filters, num_filters])
b_conv2 = bias_variable([num_filters])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

h_pool2_flat = tf.reshape(h_pool2, [-1, 32, 256])

W_fc1 = weight_variable([256, 32])
b_fc1 = bias_variable([32])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

print inputs.shape
with tf.Session() as sess:
     sess.run(tf.global_variables_initializer())
     output = sess.run(h_pool2_flat, feed_dict={inputs: dataset})
     print 'output',output.shape
</code>```

And I get

```<code>ValueError: Shape must be rank 2 but is rank 3 for 'MatMul_5' (op: 'MatMul') with input shapes: [?,32,256], [256,32].
</code>```

A smaller example

```<code>import numpy as np
import tensorflow as tf

dataset = np.zeros((3,2,4))

inputs = tf.placeholder(tf.float32, [None, 2, 4])
print inputs
W = tf.zeros((4,5))
print W
W2 = tf.matmul(inputs, W)

with tf.Session() as sess:
     sess.run(tf.global_variables_initializer())
     output = sess.run(W2, feed_dict={inputs: dataset})
     print 'output',output.shape
</code>```

This also gives similar error

```<code>ValueError: Shape must be rank 2 but is rank 3 for 'MatMul_12' (op: 'MatMul') with input shapes: [?,2,4], [4,5].
</code>```

Any ideas?

Thanks,

答:
That 32 is there because it was in the previous layer. It keeps unchanged.

The tf.matmul multiplies considering the two last dimensions, as stated here. (See the examples taking more than two dimensions)

I see you've got a Dense(32) there, with input size = 256.

This means that the weights matrix is (256,32). In keras, the multiplication as seen here is inputs x kernel.

So, if you have the input tensor shaped as (?, any, 256), and the weights matrix shaped as (256,32), all you need is:

```<code>output = tf.matmul(input,weights)
</code>```

This will output a shape (?, any, 32) - any is there untouched because it just was there before.

You may also want to sum the biases, which will follow the same principle. You need a bias vector of shape (32,).

Body:
I am looking at the examples/image_orc.py example in Keras, when I run it I see something like

_______________
max2 (MaxPooling2D)              (None, 32, 16, 16)    0           conv2[0][0]
____________________________________________________________________________________________________
reshape (Reshape)                (None, 32, 256)       0           max2[0][0]
____________________________________________________________________________________________________
dense1 (Dense)                   (None, 32, 32)        8224        reshape[0][0]
_____________________________________________________________________________________

The Dense layer outputs a tensor 32x32. I am trying to replicate this in pur TensorFlow where tf.matmul would be used, but how can I output 32x32 using matmul?

Addition:

I am not trying to replicate the Keras example exactly,

w = 128; h = 64
# junk image, only one
dataset = np.zeros((1,w,h,1))

import tensorflow as tf

pool_size = 1
num_filters = 16

def weight_variable(shape):
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)

def bias_variable(shape):
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)

def conv2d(x, W):
  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                        strides=[1, 2, 2, 1], padding='SAME')

inputs = tf.placeholder(tf.float32, [None, w, h, 1])

W_conv1 = weight_variable([3, 3, 1, num_filters])
b_conv1 = bias_variable([num_filters])
h_conv1 = tf.nn.relu(conv2d(inputs, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)

W_conv2 = weight_variable([3, 3, num_filters, num_filters])
b_conv2 = bias_variable([num_filters])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

h_pool2_flat = tf.reshape(h_pool2, [-1, 32, 256])

W_fc1 = weight_variable([256, 32])
b_fc1 = bias_variable([32])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

print inputs.shape
with tf.Session() as sess:
     sess.run(tf.global_variables_initializer())
     output = sess.run(h_pool2_flat, feed_dict={inputs: dataset})
     print 'output',output.shape

And I get

ValueError: Shape must be rank 2 but is rank 3 for 'MatMul_5' (op: 'MatMul') with input shapes: [?,32,256], [256,32].

A smaller example

import numpy as np
import tensorflow as tf

dataset = np.zeros((3,2,4))

inputs = tf.placeholder(tf.float32, [None, 2, 4])
print inputs
W = tf.zeros((4,5))
print W
W2 = tf.matmul(inputs, W)

with tf.Session() as sess:
     sess.run(tf.global_variables_initializer())
     output = sess.run(W2, feed_dict={inputs: dataset})
     print 'output',output.shape

This also gives similar error

ValueError: Shape must be rank 2 but is rank 3 for 'MatMul_12' (op: 'MatMul') with input shapes: [?,2,4], [4,5].

Any ideas?

Thanks,

Body:
That 32 is there because it was in the previous layer. It keeps unchanged.

The tf.matmul multiplies considering the two last dimensions, as stated here. (See the examples taking more than two dimensions)

I see you've got a Dense(32) there, with input size = 256.

This means that the weights matrix is (256,32). In keras, the multiplication as seen here is inputs x kernel.

So, if you have the input tensor shaped as (?, any, 256), and the weights matrix shaped as (256,32), all you need is:

output = tf.matmul(input,weights)

This will output a shape (?, any, 32) - any is there untouched because it just was there before.

You may also want to sum the biases, which will follow the same principle. You need a bias vector of shape (32,).


问:
Python - If I create a variable inside a function, how can I then use it outside the function?
I would like to create a variable inside a function and then use that variable outside the function. Is there a way to do this? For example:

```<code>def Function():
    score = 5

Function()

print(score)
</code>```

Thank you :)

答:
You have to return it</p>

```<code>def Function():
    score = 5
    return score

score=Function()

print(score)
</code>```

Body:
I would like to create a variable inside a function and then use that variable outside the function. Is there a way to do this? For example:

def Function():
    score = 5

Function()

print(score)

Thank you :)

Body:
You have to return it

def Function():
    score = 5
    return score

score=Function()

print(score)


问:
how to git log amendments
So basically, I know that to see past git commits, you do git log. But at my company we work with gerrit on one commit and you make amendments to that commits. How do I see all the past amendments to that specific commit, so I see each of their commit message and I can diff between the amendments? THANKS!</p>

答:
Short answer, that is not possible.

From Atlassian's Git Tutorials:

Amended commits are actually entirely new commits and the previous commit will no longer be on your current branch.

That is, you won't be able to access amended commits.

As an alternative, you could apply all changes as separate commits and when you finished the review squash (section: Squashing commits) them using interactive rebase.

Title: how to git log amendments


问:
CSS align and size
I am designing a layout and I am having two difficulties:

1) Don' t understand why the height of the div where calendar is in (green), is different from its parent.

2) I put a ul inside a div and want to set background color '#d1d2e0' to it (full width). It's going only to the 'Link four'.

div.container
{
width:100%;
margin:0px;
background: #005884;
}

div.left
{
float:left;
width:160px;
margin:0;
padding:1em;
color: #d1d2e0;
background: green;
}

h3.header
{
padding:0;
margin:0;
}

div.right
{
margin-left:190px;
padding:1em;
text-align: right;
}

label.year{
 padding: 0.4em 0.6em;
    margin: 0;
 background: #d1d2e0;
 color: #36384e;
    border-bottom: 1px solid #d1d2e0;
}

select#DropYear{
 background: #36384e;
 color: #d1d2e0;
 width: 70px;
 height: 30px;
 margin: 0;
 font-size: 16px;
 text-align: center;
 text-align-last: center;
}

div.nav{
    width: 100%;
    height: 30px;
 color: 5px soldi red;
    display: table-cell;
    vertical-align: middle;
}

ul {
    float: left;
    width: 100%;
    padding: 0;
    margin: 0;
    list-style-type: none;
}

a {
    float: left;
    width: 6em;
    text-decoration: none;
    color: #005884;
    background-color: #d1d2e0;
    padding: 0.2em 0.6em;
    border-right: 1px solid white;
}

a.last { border-right: none; }

li.nav {
 display: inline;
    text-align: center;
}

.form{
 width: auto;
    height: 60px;
 background: lightgrey;
}

select.form{
}

.content{
 margin: 5px 0px;
 width: auto;
    height: 150px;
 background: yellow;
}

.footer{
 width: auto;
    height: 20px;
 background: grey;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="left"><h3 class="header">Calendar</h3></div>
  <div class="right">
    <label class="year" for="DropYear">Year</label><!--
    --><select id="DropYear" class="drop">
      <option value="2016">2016</option>
      <option value="2017">2017</option>
      <option value="2018">2018</option>
    </select>
  </div>
</div>
<div class="nav">
  <ul>
    <li class="nav">Link one</li>
    <li class="nav">Link two</li>
    <li class="nav">Link three</li>
    <li class="nav">Link four</li>
  </ul>
</div>
<div class="form"></div>
<div class="content"></div>
<div class="footer"></div></code>```

Regards,
Elio Fernandes

答:
You could move the right container into the left container and then just change some paddings (e.g. add padding to h3 and drop from .left). The smaller container, .left in this case, will then grow to all its content to fit.

```<code><div class="container">
  <div class="left"><h3 class="header">Calendar</h3>
  <div class="right">
    <label class="year" for="DropYear">Year</label><!--
    --><select id="DropYear" class="drop">
      <option value="2016">2016</option>
      <option value="2017">2017</option>
      <option value="2018">2018</option>
    </select>
  </div>
  </div>
</div>
</code>```

As for your links, float them all left and set their width to 25%. You will also need to lose the display:table-cell from the containing div

Title: CSS align and size

Body:
I am designing a layout and I am having two difficulties:

1) Don' t understand why the height of the div where calendar is in (green), is different from its parent.

2) I put a ul inside a div and want to set background color '#d1d2e0' to it (full width). It's going only to the 'Link four'.

div.container
{
width:100%;
margin:0px;
background: #005884;
}

div.left
{
float:left;
width:160px;
margin:0;
padding:1em;
color: #d1d2e0;
background: green;
}

h3.header
{
padding:0;
margin:0;
}

div.right
{
margin-left:190px;
padding:1em;
text-align: right;
}

label.year{
 padding: 0.4em 0.6em;
    margin: 0;
 background: #d1d2e0;
 color: #36384e;
    border-bottom: 1px solid #d1d2e0;
}

select#DropYear{
 background: #36384e;
 color: #d1d2e0;
 width: 70px;
 height: 30px;
 margin: 0;
 font-size: 16px;
 text-align: center;
 text-align-last: center;
}

div.nav{
    width: 100%;
    height: 30px;
 color: 5px soldi red;
    display: table-cell;
    vertical-align: middle;
}

ul {
    float: left;
    width: 100%;
    padding: 0;
    margin: 0;
    list-style-type: none;
}

a {
    float: left;
    width: 6em;
    text-decoration: none;
    color: #005884;
    background-color: #d1d2e0;
    padding: 0.2em 0.6em;
    border-right: 1px solid white;
}

a.last { border-right: none; }

li.nav {
 display: inline;
    text-align: center;
}

.form{
 width: auto;
    height: 60px;
 background: lightgrey;
}

select.form{
}

.content{
 margin: 5px 0px;
 width: auto;
    height: 150px;
 background: yellow;
}

.footer{
 width: auto;
    height: 20px;
 background: grey;
}

Calendar

    Year<select id="DropYear" class="drop">
      <option value="2016">2016</option>
      <option value="2017">2017</option>
      <option value="2018">2018</option>
    </select>

Link one

Link two

Link three

Link four

Regards,
Elio Fernandes

Body:
You could move the right container into the left container and then just change some paddings (e.g. add padding to h3 and drop from .left). The smaller container, .left in this case, will then grow to all its content to fit.

<div class="container">
  <div class="left"><h3 class="header">Calendar</h3>
  <div class="right">
    <label class="year" for="DropYear">Year</label><!--
    --><select id="DropYear" class="drop">
      <option value="2016">2016</option>
      <option value="2017">2017</option>
      <option value="2018">2018</option>
    </select>
  </div>
  </div>
</div>

As for your links, float them all left and set their width to 25%. You will also need to lose the display:table-cell from the containing div


问:
Matplotlib: Time axes and limits
I have a matplotlib plot for which the x data is a Pandas DateTimeIndex.

The user can zoom the x-axis using the scroll wheel.  The limits are recalculated like this:

```<code>limits = ax.get_xlim()
span = limits[1] - limits[0]
pos = (1 - (limits[1] - evt.xdata) / span)
if evt.button == 'up':
    limits = ( limits[0] + span / 1.3 / 2 * pos,
               limits[1] - span / 1.3 / 2 * (1 - pos) )
elif evt.button == 'down':
    limits = ( limits[0] - span / 1.3 / 2 * pos,
               limits[1] + span / 1.3 / 2 * (1 - pos) )
</code>```

This works and zooms the x-axis in or out on the point where the scroll event happened.  Now I'm trying to recalculate the y-axis limits to zoom to the data displayed but can't figure out how the x-axis data and the x-limits relate to each other:

```<code>lines = ax.get_lines()
y_lim = np.inf, -np.inf
for line in lines:
    xd = line.get_xdata()
    yd = line.get_ydata()
    y_displayed = yd[((xd > limits[0]) & (xd < limits[1]))]
    y_lim = min(np.min(y_displayed), y_lim[0]), max(np.max(y_displayed), y_lim[1])
ax.set_ylim(y_lim)
</code>```

This fails with the message TypeError: Invalid type promotion.

As far as I can make out, the x-data is being stored as numpy.datetime64 but matplotlib returns the limits as a float which represents the number of days since 0001-01-01 00:00 plus 1.  How do I get this into some form I can compare with an array of datetime64?

答:
Nevermind, as soon as I posted the question I figured it out:</p>

```<code>from matplotlib.dates import num2date

limits = (np.datetime64(num2date(limits[0])), np.datetime64(num2date(limits[1])))
</code>```

Title: Matplotlib: Time axes and limits

Body:
I have a matplotlib plot for which the x data is a Pandas DateTimeIndex.

The user can zoom the x-axis using the scroll wheel.  The limits are recalculated like this:

limits = ax.get_xlim()
span = limits[1] - limits[0]
pos = (1 - (limits[1] - evt.xdata) / span)
if evt.button == 'up':
    limits = ( limits[0] + span / 1.3 / 2 * pos,
               limits[1] - span / 1.3 / 2 * (1 - pos) )
elif evt.button == 'down':
    limits = ( limits[0] - span / 1.3 / 2 * pos,
               limits[1] + span / 1.3 / 2 * (1 - pos) )

This works and zooms the x-axis in or out on the point where the scroll event happened.  Now I'm trying to recalculate the y-axis limits to zoom to the data displayed but can't figure out how the x-axis data and the x-limits relate to each other:

lines = ax.get_lines()
y_lim = np.inf, -np.inf
for line in lines:
    xd = line.get_xdata()
    yd = line.get_ydata()
    y_displayed = yd[((xd > limits[0]) & (xd < limits[1]))]
    y_lim = min(np.min(y_displayed), y_lim[0]), max(np.max(y_displayed), y_lim[1])
ax.set_ylim(y_lim)

This fails with the message TypeError: Invalid type promotion.

As far as I can make out, the x-data is being stored as numpy.datetime64 but matplotlib returns the limits as a float which represents the number of days since 0001-01-01 00:00 plus 1.  How do I get this into some form I can compare with an array of datetime64?

Body:
Nevermind, as soon as I posted the question I figured it out:

from matplotlib.dates import num2date

limits = (np.datetime64(num2date(limits[0])), np.datetime64(num2date(limits[1])))


问:
Is there a way to install and run a local server on my Windows XP Home laptop?
I'm looking to set up a local server on my laptop which is running Windows XP Home Edition. I've noticed that it is impossible to install IIS on the Home Edition, but is there a way around this? Is there other software that I can install to run a server?

the purpose behind this is to mess around and play with ASP to create dynamic websites and my only computer I own has Home Edition.

Also, would running a server on my 5 year old laptop with 2GB of RAM be a good idea?

答:
Windows XP Home Edition does not come with IIS (only Professional). There are workarounds available, but Home Edition was not designed for this. Visual Studio (full and express) come with Cassini, which is a version of IIS you can use for testing/development.

What is your desired result?

ContentLicense: CC BY-SA 2.5


问:
Data type mismatch when using form control as criteria
I have a form in MS Access that has an unbound control named boxReferenceMonthGtis that correctly displays a date.

This control Control Source property is =[GTIS_subform].[Form]![ReferenceMonth] which is a field of type Date/Time in a subform.

When I try to use this control in a query in the SELECT clause it shows this gibberish �䃤.

After reading this I added PARAMETERS [Forms]![Conciliacao]![boxReferenceMonthGtis] DateTime to my SQL, and the SELECT statement started showing the correct value.

However, If I try to use my control as a criteria to filter another field like:

```<code>WHERE DateSerial(Year([Departure]),Month([Departure]),1)=[Forms]![Conciliacao]![boxReferenceMonthGtis]
</code>```

I'm prompted with

Data type mismatch in criteria expression.

What is weird is that if I filter the field [Departure] like:

```<code>WHERE ShippingTrack.Departure=[Forms]![Conciliacao]![boxReferenceMonthGtis]
</code>```

There is no error!

What else I have tried without success

Same error (Data type mismatch)

```<code>WHERE CDate(DateSerial(Year([Departure]),Month([Departure]),1)=[Forms]![Conciliacao]![boxReferenceMonthGtis]

WHERE CDate(DateSerial(Year([Departure]),Month([Departure]),1)=CDate([Forms]![Conciliacao]![boxReferenceMonthGtis]

WHERE CVDate(DateSerial(Year([Departure]),Month([Departure]),1)=CVDate([Forms]![Conciliacao]![boxReferenceMonthGtis]
</code>```

Does anybody knows how to make this work?

What is even weirder is that I have another query in the same database that I can use WHERE DateSerial(Year([Departure]),Month([Departure]),1)=[Forms]![Conciliacao]![boxReferenceMonthGtis] without any issue!

答:
OK:

It could be that some records have Null for Departure.

Body:
I have a form in MS Access that has an unbound control named boxReferenceMonthGtis that correctly displays a date.

This control Control Source property is =[GTIS_subform].[Form]![ReferenceMonth] which is a field of type Date/Time in a subform.

When I try to use this control in a query in the SELECT clause it shows this gibberish �䃤.

After reading this I added PARAMETERS [Forms]![Conciliacao]![boxReferenceMonthGtis] DateTime to my SQL, and the SELECT statement started showing the correct value.

However, If I try to use my control as a criteria to filter another field like:

WHERE DateSerial(Year([Departure]),Month([Departure]),1)=[Forms]![Conciliacao]![boxReferenceMonthGtis]

I'm prompted with

Data type mismatch in criteria expression.

What is weird is that if I filter the field [Departure] like:

WHERE ShippingTrack.Departure=[Forms]![Conciliacao]![boxReferenceMonthGtis]

There is no error!

What else I have tried without success

Same error (Data type mismatch)

WHERE CDate(DateSerial(Year([Departure]),Month([Departure]),1)=[Forms]![Conciliacao]![boxReferenceMonthGtis]

WHERE CDate(DateSerial(Year([Departure]),Month([Departure]),1)=CDate([Forms]![Conciliacao]![boxReferenceMonthGtis]

WHERE CVDate(DateSerial(Year([Departure]),Month([Departure]),1)=CVDate([Forms]![Conciliacao]![boxReferenceMonthGtis]

Does anybody knows how to make this work?

What is even weirder is that I have another query in the same database that I can use WHERE DateSerial(Year([Departure]),Month([Departure]),1)=[Forms]![Conciliacao]![boxReferenceMonthGtis] without any issue!


问:
How to get all users that the logged in user is not friends with in MySQL?
I am fully able to get all of the logged in users current friends, which I do with this query here -

```<code>SELECT users.*
FROM users
LEFT JOIN friends
ON users.id = friends.friend_id
WHERE friends.user_id = $user_logged_in_id
</code>```

But I want to do the opposite, and I can't figure it out.

I am trying to do friends logic.

I need to get all the users who the currently logged in user is not already friends with

I have a users table and a friends table to act as a many to many relationship between users and their friends. The keys in the friends table are user_id friend_id.

To illustrate that someone is friends with another user I put (say the logged in user id is 3, and friends user id is 6) user_id = 3 and friend_id = 6 as one row, and then put another row with the id's flipped to illustrate the friendship the other way, user_id = 6 and friend_id = 3.

users table

```<code>|---------------------|------------------|
|          id         |     username     |
|---------------------|------------------|
|          1          |     sonja12      |
|---------------------|------------------|
|          2          |     dorris32     |
|---------------------|------------------|
|          3          |     billy32      |
|---------------------|------------------|
|          4          |     micha97      |
|---------------------|------------------|
|          5          |     travis841    |
|---------------------|------------------|
|          6          |     johnny28     |
|---------------------|------------------|
</code>```

friends table

```<code>|---------------------|------------------|------------------|
|          id         |     user_id      |     friend_id    |
|---------------------|------------------|------------------|
|          1          |        3         |         6        |
|---------------------|------------------|------------------|
|          2          |        6         |         3        |
|---------------------|------------------|------------------|
</code>```

EDIT:

I think I have narrowed down my question a bit to be more concise.

I want to get all users from the users table where their id does not appear as a friend id beside the user_id of the current logged in user in the friends table.

答:
```<code>SELECT DISTINCT users.id, users.username
  FROM users
       LEFT OUTER JOIN friends
    ON (friends.user_id = $user_logged_in_id and friends.friend_id = users.id)
 WHERE users.id <> $user_logged_in_id
   AND friends.friend_id is null;
</code>```

This query is likely to be more performant than a NOT IN Sub Query if the user is expected to have lots of friends. If not NOT IN sub query performs the same if not better.

Please note the DISTINCT. You need this because the relationship is many to many.

Body:
I am fully able to get all of the logged in users current friends, which I do with this query here -

SELECT users.*
FROM users
LEFT JOIN friends
ON users.id = friends.friend_id
WHERE friends.user_id = $user_logged_in_id

But I want to do the opposite, and I can't figure it out.

I am trying to do friends logic.

I need to get all the users who the currently logged in user is not already friends with

I have a users table and a friends table to act as a many to many relationship between users and their friends. The keys in the friends table are user_id friend_id.

To illustrate that someone is friends with another user I put (say the logged in user id is 3, and friends user id is 6) user_id = 3 and friend_id = 6 as one row, and then put another row with the id's flipped to illustrate the friendship the other way, user_id = 6 and friend_id = 3.

users table

|---------------------|------------------|
|          id         |     username     |
|---------------------|------------------|
|          1          |     sonja12      |
|---------------------|------------------|
|          2          |     dorris32     |
|---------------------|------------------|
|          3          |     billy32      |
|---------------------|------------------|
|          4          |     micha97      |
|---------------------|------------------|
|          5          |     travis841    |
|---------------------|------------------|
|          6          |     johnny28     |
|---------------------|------------------|

friends table

|---------------------|------------------|------------------|
|          id         |     user_id      |     friend_id    |
|---------------------|------------------|------------------|
|          1          |        3         |         6        |
|---------------------|------------------|------------------|
|          2          |        6         |         3        |
|---------------------|------------------|------------------|

EDIT:

I think I have narrowed down my question a bit to be more concise.

I want to get all users from the users table where their id does not appear as a friend id beside the user_id of the current logged in user in the friends table.

Body:
SELECT DISTINCT users.id, users.username
  FROM users
       LEFT OUTER JOIN friends
    ON (friends.user_id = $user_logged_in_id and friends.friend_id = users.id)
 WHERE users.id <> $user_logged_in_id
   AND friends.friend_id is null;

This query is likely to be more performant than a NOT IN Sub Query if the user is expected to have lots of friends. If not NOT IN sub query performs the same if not better.

Please note the DISTINCT. You need this because the relationship is many to many.


问:
Recursively change array results
I am using an API which is returning results in a format that includes extra nodes.  I want to recursively run through the results to remove the "data" nodes so that I can use it in my application.

Can I do this with plain javascript or Lodash?

This is the results that I am getting:

```<code>"pages": {
    "data": [
        {
            "id": 32,
            "pages": {
                "data": [
                    {
                        "id": 33,
                        "pages": {
                            "data": []
                        }
                    },
                    {
                        "id": 34,
                        "pages": {
                            "data": [
                                {
                                    "id": 35,
                                    "pages": {
                                        "data": []
                                    }
                                }
                            ]
                        }
                    }
                ]
            }
        },
        {
            "id": 36,
            "pages": {
                "data": []
            }
        }
    ]
</code>```

This is what I would like to have returned:

```<code>"pages": [
        {
            "id": 32,
            "pages": [
                {
                    "id": 33,
                    "pages":  []
                },
                {
                    "id": 34,
                    "pages": [
                        {
                            "id": 35,
                            "pages": []
                        }
                    ]
                }
            ]
        },
        {
            "id": 36,
            "pages": []
        }
    ]
</code>```

答:
You could take a check and a recursive approach for nested arrays.

function clean(object) {
    if (object.pages && object.pages.data) {
        object.pages = object.pages.data;
        delete object.pages.data;
    }
    object.pages.forEach(clean);
}

var object = { pages: { data: [{ id: 32, pages: { data: [{ id: 33, pages: { data: [] } }, { id: 34, pages: { data: [{ id: 35, pages: { data: [] } }] } }] } }, { id: 36, pages: { data: [] } }] } };

clean(object);

console.log(object);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: Recursively change array results

Body:
I am using an API which is returning results in a format that includes extra nodes.  I want to recursively run through the results to remove the "data" nodes so that I can use it in my application.

Can I do this with plain javascript or Lodash?

This is the results that I am getting:

"pages": {
    "data": [
        {
            "id": 32,
            "pages": {
                "data": [
                    {
                        "id": 33,
                        "pages": {
                            "data": []
                        }
                    },
                    {
                        "id": 34,
                        "pages": {
                            "data": [
                                {
                                    "id": 35,
                                    "pages": {
                                        "data": []
                                    }
                                }
                            ]
                        }
                    }
                ]
            }
        },
        {
            "id": 36,
            "pages": {
                "data": []
            }
        }
    ]

This is what I would like to have returned:

"pages": [
        {
            "id": 32,
            "pages": [
                {
                    "id": 33,
                    "pages":  []
                },
                {
                    "id": 34,
                    "pages": [
                        {
                            "id": 35,
                            "pages": []
                        }
                    ]
                }
            ]
        },
        {
            "id": 36,
            "pages": []
        }
    ]

Body:
You could take a check and a recursive approach for nested arrays.

function clean(object) {
    if (object.pages && object.pages.data) {
        object.pages = object.pages.data;
        delete object.pages.data;
    }
    object.pages.forEach(clean);
}

var object = { pages: { data: [{ id: 32, pages: { data: [{ id: 33, pages: { data: [] } }, { id: 34, pages: { data: [{ id: 35, pages: { data: [] } }] } }] } }, { id: 36, pages: { data: [] } }] } };

clean(object);

console.log(object);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Removing Duplicate Words from a UITextView
having this delegate of UItextview i want to remove tagging words that are already in text with this delegate </p>

```<code>func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if text == " ",let lastWord = textView.text.components(separatedBy: " ").last, lastWord.hasPrefix("@"), let lastWordRange = (textView.text as NSString?)?.range(of: lastWord){
        if self.search(in: lastWord), searchDuplicate(this: lastWord) == 1  {
            let attributes = [NSForegroundColorAttributeName: UIColor.blue, NSFontAttributeName: self.textView.font!] as [String : Any]
            let attributedString = NSMutableAttributedString(string: lastWord, attributes: attributes)
            textView.textStorage.replaceCharacters(in:lastWordRange, with:attributedString)

        }else{
            if searchDuplicate(this: lastWord) > 1 {
                textView.text.removeSubrange(Range(uncheckedBounds: (lower: textView.text.index(textView.text.endIndex, offsetBy: -lastWord.characters.count ), upper: textView.text.endIndex)))
            }
            let realLW = lastWord.replacingOccurrences(of: "@", with: "")
            textView.textStorage.replaceCharacters(in:lastWordRange, with:realLW)
        }
    }
    return true
}
</code>```

<p>the function dectect a word with @ format and check out if is valid as a tag, but if the tag is input is not the first time it would not get the appropiated format since the range only detecs it in the first apperance so i have to remove it but in the replacing text of the textview.text all word lost their format . so how i can detect the range of the word that is repeated to delete it. </p>

答:
try this </p>

```<code>func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

  if text == " " {
    let newText = removeDuplicates(text: textView.attributedText.string ?? "")
    let attributes = [NSForegroundColorAttributeName: UIColor.blue, NSFontAttributeName: self.textView.font!] as [String : Any]
    let attributedString = NSMutableAttributedString(string: newText, attributes: attributes)
    textView.attributedText = attributedString
  }
  return true
}

func removeDuplicates(text: String) -> String {
  let words = text.components(separatedBy: " ")
  let filtered = words.filter { $0.characters.first == "@" }
  return Array(Set(filtered)).joined()
}
</code>```

Body:
having this delegate of UItextview i want to remove tagging words that are already in text with this delegate

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if text == " ",let lastWord = textView.text.components(separatedBy: " ").last, lastWord.hasPrefix("@"), let lastWordRange = (textView.text as NSString?)?.range(of: lastWord){
        if self.search(in: lastWord), searchDuplicate(this: lastWord) == 1  {
            let attributes = [NSForegroundColorAttributeName: UIColor.blue, NSFontAttributeName: self.textView.font!] as [String : Any]
            let attributedString = NSMutableAttributedString(string: lastWord, attributes: attributes)
            textView.textStorage.replaceCharacters(in:lastWordRange, with:attributedString)

        }else{
            if searchDuplicate(this: lastWord) > 1 {
                textView.text.removeSubrange(Range(uncheckedBounds: (lower: textView.text.index(textView.text.endIndex, offsetBy: -lastWord.characters.count ), upper: textView.text.endIndex)))
            }
            let realLW = lastWord.replacingOccurrences(of: "@", with: "")
            textView.textStorage.replaceCharacters(in:lastWordRange, with:realLW)
        }
    }
    return true
}

the function dectect a word with @ format and check out if is valid as a tag, but if the tag is input is not the first time it would not get the appropiated format since the range only detecs it in the first apperance so i have to remove it but in the replacing text of the textview.text all word lost their format . so how i can detect the range of the word that is repeated to delete it.

Body:
try this

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

  if text == " " {
    let newText = removeDuplicates(text: textView.attributedText.string ?? "")
    let attributes = [NSForegroundColorAttributeName: UIColor.blue, NSFontAttributeName: self.textView.font!] as [String : Any]
    let attributedString = NSMutableAttributedString(string: newText, attributes: attributes)
    textView.attributedText = attributedString
  }
  return true
}

func removeDuplicates(text: String) -> String {
  let words = text.components(separatedBy: " ")
  let filtered = words.filter { $0.characters.first == "@" }
  return Array(Set(filtered)).joined()
}


问:
Replacing Key-List in Free format SQLRPGLE
I am converting RPGLE fixed format to Free format and while converting i got a issue the KEY-LIST & Fields got converted into Data-structure. which is basically redefining fields which are already defined either directly or indirectly...

```<code>DCL-DS Key_List;
     Field1 CHAR(4);
     Field2 CHAR(4);
END-DS;
</code>```

both field1 & field2 are file's fields. below is old style (fixed format)

```<code>C     Key_list      KLIST
C                   KFLD                    Field1
C                   KFLD                    Field2
</code>```

Please Advice...program is giving compile time error (SQL0314) field1 & field are not Unique

答:
You can use %kds() with a data structured defined with EXTNAME(...:*KEY) or LIKEREC(...:*KEY)

```<code>dcl-ds key_list likerec(myfileR:*key);
//
chain %kds(key_list) myfile;
</code>```

Or simply use the fields directly since they are already defined...

```<code>chain (field1:field2) myfile;
</code>```

Either method should get rid of the duplicate define and stop the SQL0314 error from the pre-compiler.

Body:
I am converting RPGLE fixed format to Free format and while converting i got a issue the KEY-LIST & Fields got converted into Data-structure. which is basically redefining fields which are already defined either directly or indirectly...

DCL-DS Key_List;
     Field1 CHAR(4);
     Field2 CHAR(4);
END-DS;

both field1 & field2 are file's fields. below is old style (fixed format)

C     Key_list      KLIST
C                   KFLD                    Field1
C                   KFLD                    Field2

Please Advice...program is giving compile time error (SQL0314) field1 & field are not Unique

Body:
You can use %kds() with a data structured defined with EXTNAME(...:*KEY) or LIKEREC(...:*KEY)

dcl-ds key_list likerec(myfileR:*key);
//
chain %kds(key_list) myfile;

Or simply use the fields directly since they are already defined...

chain (field1:field2) myfile;

Either method should get rid of the duplicate define and stop the SQL0314 error from the pre-compiler.


问:
For high scalability & performance needs, is it preferable to have C++ or Java implementation at the backend of a PHP application?
For high scalability & performance needs for a social portal, is it advisable to have C++ or Java implementation at the backend of an PHP application ?

What are the benefits & trade-offs of the same ?

答: You aren't writing the next facebook. Write it in PHP (or whatever language you're most comfortable with) for now. If you're lucky enough to grow large enough to the point where php can't handle the load then you can redesign your site. Unless you're running one of the top 100 sites it the world you're just engaged in premature optimisation.</p>


问:
MVC Razor build onclick event dynamically to show modal
I am currently trying to attach a click handler to my  tag which will pop up my modal which has a dynamic id. I am having trouble figuring out the syntax to accomplish this- my current attempt can be found below and has a syntax error on onclick="$('#"+ @modalId + "')" (which is the part im struggling a bit with). How can I accomplish this?

```<code>var modalId = string.Format("docusign{0}", doc.Id)
<a href="#" onclick="$('#"+ @modalId + "').modal('toggle')">@string.Format("Document {0}", EnumHelper.GetDisplayName(doc.DocumentType))</a>

<div id="@modalId" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header" style="background-color:#337ab7;color:#ffffff">
         <button type="button" class="close" data-dismiss="modal">×</button>
         <h4 class="modal-title">DocuSign Notice</h4>
      </div>
      <div class="modal-body form-group">
      <h5>Please allow up to 10 minutes for us to receive your e-form after you have completed it. To continue and fill out the necessary e-form, please click the "Fill Form" button below</h5>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default pull-right" data-dismiss="modal">Close</button>
      <a class="btn btn-default pull-left" href=@doc.DocuSignPowerFormLink>Fill Form</a>
      </div>
    </div>
  </div>
</div>
</code>```

答:
Your current code is rendering markup like this (Assuming the value of doc.Id is 123

```<code><a href="#" onclick="$('#" +="" docusign123"" "').modal('toggle')"="">Your text</a>
</code>```

You have  extra " before  and after the value the C# variable. and extra +

So basically your jQuery selector is

```<code> $('#" +="" docusign1324"" "')
</code>```

which is not correct

All you need is, render the value of @modalId and use that after # part of your jQuery selector.

This should work

```<code><a href="#" onclick="$('#@modalId').modal('toggle');">Your text</a>
</code>```

If you want to be more readable, you can wrap the C# expression inside ( and )

```<code><a href="#" onclick="$('#@(modalId)').modal('toggle');">Your text</a>
</code>```

Body:
I am currently trying to attach a click handler to my  tag which will pop up my modal which has a dynamic id. I am having trouble figuring out the syntax to accomplish this- my current attempt can be found below and has a syntax error on onclick="$('#"+ @modalId + "')" (which is the part im struggling a bit with). How can I accomplish this?

var modalId = string.Format("docusign{0}", doc.Id)
@string.Format("Document {0}", EnumHelper.GetDisplayName(doc.DocumentType))

         <button type="button" class="close" data-dismiss="modal">×</button>

DocuSign Notice

Please allow up to 10 minutes for us to receive your e-form after you have completed it. To continue and fill out the necessary e-form, please click the "Fill Form" button below

      <button type="button" class="btn btn-default pull-right" data-dismiss="modal">Close</button>
      Fill Form

Body:
Your current code is rendering markup like this (Assuming the value of doc.Id is 123

<a href="#" onclick="$('#" +="" docusign123"" "').modal('toggle')"="">Your text</a>

You have  extra " before  and after the value the C# variable. and extra +

So basically your jQuery selector is

 $('#" +="" docusign1324"" "')

which is not correct

All you need is, render the value of @modalId and use that after # part of your jQuery selector.

This should work

<a href="#" onclick="$('#@modalId').modal('toggle');">Your text</a>

If you want to be more readable, you can wrap the C# expression inside ( and )

<a href="#" onclick="$('#@(modalId)').modal('toggle');">Your text</a>


问:
Redux add websocket as prop
I have react application with that needed single websocket connection, so i connect websocket from redux action and trying to set websocket instance as prop; so I can access this instance any ware in my application

```<code>const initWebSocket = uri => {
    const ws = new WebSocket(uri)
    return {
        type: WEB_SOCKET_CONNECTION_SUCCESS,
        ws
    }
}
// reducer
export default function (state = initialState, action) {
    switch (action.type) {
        case WEB_SOCKET_CONNECTION_SUCCESS:
            return {...state, ws: action.ws}
        default:
            return state;
    }
}
</code>```

but aster state change ws is empty object

答:
It's technically possibly to put a Websocket connection instance into a Redux store, but that's a bad idea.  The Redux docs discourage putting anything that's not serializable in the Redux store.

The right place for Websockets and other persistent connection objects in a Redux app is inside of middleware.  In fact, there's already dozens of existing middleware for managing Websocket connections available.

Title: Redux add websocket as prop

Body:
I have react application with that needed single websocket connection, so i connect websocket from redux action and trying to set websocket instance as prop; so I can access this instance any ware in my application

const initWebSocket = uri => {
    const ws = new WebSocket(uri)
    return {
        type: WEB_SOCKET_CONNECTION_SUCCESS,
        ws
    }
}
// reducer
export default function (state = initialState, action) {
    switch (action.type) {
        case WEB_SOCKET_CONNECTION_SUCCESS:
            return {...state, ws: action.ws}
        default:
            return state;
    }
}

but aster state change ws is empty object


问:
Sending a message using IBM MQ, getting 2059 error or hang on construction of Queue Manager
I'm tasked with sending a test message to an (as yet) unknown MQ endpoint.

I've stood a trial version of IBM WebSphere MQ (v8.0.0.5) on a server, which I believe is configured correctly.

However, given the code included below I get either the exception:

An unhandled exception of type 'IBM.WMQ.MQException' occurred in
  amqmdnet.dll

Additional information: 2059

Or if I am on the server itself using localhost instead of the remote server name, the constructor line hangs.

This is C#:

```<code>Hashtable connectionProperties = new Hashtable();

string connectionType = MQC.TRANSPORT_MQSERIES_MANAGED
connectionProperties.Add(MQC.TRANSPORT_PROPERTY, connectionType);

// Set up the rest of the connection properties, based on the
// connection type requested
switch (_connectionType)
{
    case MQC.TRANSPORT_MQSERIES_BINDINGS:
        break;
    case MQC.TRANSPORT_MQSERIES_CLIENT:
    case MQC.TRANSPORT_MQSERIES_XACLIENT:
    case MQC.TRANSPORT_MQSERIES_MANAGED:
        connectionProperties.Add(MQC.HOST_NAME_PROPERTY, "server.com");
        connectionProperties.Add(MQC.CHANNEL_PROPERTY, "SYSTEM.DEF.CLNTCONN");
        break;
}

MQQueueManager qMgr = new MQQueueManager("test", connectionProperties);
MqClientTest mqClientTest=new MqClientTest("TEST_QM","localhost", "SYSTEM.DEF.CLNTCONN");
</code>```

Is there anything we're missing in this?

Update 1:

In the amqerr01.log file in the errors folder, we now have the text:

AMQ6183: An internal WebSphere MQ error has occurred.

Update 2:

The "internal WebSphere MQ error" was likely due to my probing the 1414 port to see if the port was "up" and listening. Seems it was and it obviously didn't like me doing that.

Update 3:

@Roger suggested I use 127.0.0.1 and capitals, which I've now applied - and changed the example above to reflect.

@JoshMc kindly pointed to a second AMQERR01.LOG file within the Queue Manager folder. I now get the error:

14/11/2017 15:35:08 - Process(336.6) User(xxxx)
  Program(amqrmppa.exe)
                        Host(xxxx) Installation(xxxx)
                        VRMF(8.0.0.5) QMgr(TEST_QM)
                        AMQ9519: Channel 'SYSTEM.DEF.CLNTCONN' not found.

EXPLANATION: The requested operation failed because the program could
  not find a definition of channel 'SYSTEM.DEF.CLNTCONN'.

TEST_QM is my Queue Manager, with the default (?) channel SYSTEM.DEF.CLNTCONN

答:
With IBM MQ there are always a pair of channels that work together.  For example if one MQ Queue Manager needs to send to message to another queue manager it would normally have a SDR (Sender) channel defined, which would point to a RCVR (Receiver) channel with the same name on the other queue manager.

For a MQ client connection the client application side of the channel is called a MQCD, and the MQ Queue Manager side is a SVRCONN (Server Connection) channel.  The client side MQCD can be specified in a few different ways.  The way you are demonstrating in the example you posted is programmatically specifying the MQCD information (channel name, hostname, etc).

An alternate way to specify the information is by pointing to a CCDT (Client Channel Definition Table) which is commonly referred to as a Channel Table, this is where a CLNTCONN channel would be used, since you are not using a Channel table I'll move on to why you are getting an error, but at the end of this answer I'll provide more details on Channel Tables.

In summary your application should not be specifying a CLNTCONN channel as the MQC.CHANNEL_PROPERTY it should be pointing to a SVRCONN channel.

Two things to note:

You should not use the predefined SYSTEM.* channels for this purpose (for example SYSTEM.DEF.SVRCONN), you should define a new channel for your application to use.  The default channels are meant to hold parameters that you want to be the defaults when creating a new channel of the same type.

MQ v7.1 and later come with a few CHLAUTH rules enabled by default which will block access to the SYSTEM.* channels.

If you want to define a SVRCONN channel using the command line program runmqsc on Windows run the following on a CMD prompt:

```<code>echo DEFINE CHL(TEST_QM_CHANNEL1) CHLTYPE(SVRCONN)|runmqsc TEST_QM
</code>```

Few more details about Channel Tables:

Prior to MQ v8 the only supported method to generate a Channel Table was by defining CLNTCONN channels on a queue manager which creates a file called AMQCLCHL.TAB under the queue manager name folder in a directory called @ipcc.  The reason a queue manager comes with a channel called SYSTEM.DEF.CLNTCONNis to provide the default values when you create a new CLNTCONN channel. With v8 and later you can create the channel table using only the runmqsc -n mode, this will directly edit the channel table vs needing to create a CLNTCONN channel on a queue manager.  The MQ Client for v8 and later now comes with a client version of runmqsc that can be used to create and alter channel tables.

An application can point to the channel table file in a few different ways, a common way is by setting two environment variables (MQCHLLIB and MQCHLTAB).  The app then does not specify channel name, host name, etc in the program, it only needs to specify the name of the queue manager to connect to.

The order and where MQ looks for connection information is documented at the IBM v7.5 (or later) Knowledge Center page "Connecting IBM WebSphere MQ MQI client applications to queue managers".  Note this link is for MQI clients, but the same basic order applies to .NET clients as well.

Body:
I'm tasked with sending a test message to an (as yet) unknown MQ endpoint.

I've stood a trial version of IBM WebSphere MQ (v8.0.0.5) on a server, which I believe is configured correctly.

However, given the code included below I get either the exception:

An unhandled exception of type 'IBM.WMQ.MQException' occurred in
  amqmdnet.dll

Additional information: 2059

Or if I am on the server itself using localhost instead of the remote server name, the constructor line hangs.

This is C#:

Hashtable connectionProperties = new Hashtable();

string connectionType = MQC.TRANSPORT_MQSERIES_MANAGED
connectionProperties.Add(MQC.TRANSPORT_PROPERTY, connectionType);

// Set up the rest of the connection properties, based on the
// connection type requested
switch (_connectionType)
{
    case MQC.TRANSPORT_MQSERIES_BINDINGS:
        break;
    case MQC.TRANSPORT_MQSERIES_CLIENT:
    case MQC.TRANSPORT_MQSERIES_XACLIENT:
    case MQC.TRANSPORT_MQSERIES_MANAGED:
        connectionProperties.Add(MQC.HOST_NAME_PROPERTY, "server.com");
        connectionProperties.Add(MQC.CHANNEL_PROPERTY, "SYSTEM.DEF.CLNTCONN");
        break;
}

MQQueueManager qMgr = new MQQueueManager("test", connectionProperties);
MqClientTest mqClientTest=new MqClientTest("TEST_QM","localhost", "SYSTEM.DEF.CLNTCONN");

Is there anything we're missing in this?

Update 1:

In the amqerr01.log file in the errors folder, we now have the text:

AMQ6183: An internal WebSphere MQ error has occurred.

Update 2:

The "internal WebSphere MQ error" was likely due to my probing the 1414 port to see if the port was "up" and listening. Seems it was and it obviously didn't like me doing that.

Update 3:

@Roger suggested I use 127.0.0.1 and capitals, which I've now applied - and changed the example above to reflect.

@JoshMc kindly pointed to a second AMQERR01.LOG file within the Queue Manager folder. I now get the error:

14/11/2017 15:35:08 - Process(336.6) User(xxxx)
  Program(amqrmppa.exe)
                        Host(xxxx) Installation(xxxx)
                        VRMF(8.0.0.5) QMgr(TEST_QM)
                        AMQ9519: Channel 'SYSTEM.DEF.CLNTCONN' not found.

EXPLANATION: The requested operation failed because the program could
  not find a definition of channel 'SYSTEM.DEF.CLNTCONN'.

TEST_QM is my Queue Manager, with the default (?) channel SYSTEM.DEF.CLNTCONN

Body:
With IBM MQ there are always a pair of channels that work together.  For example if one MQ Queue Manager needs to send to message to another queue manager it would normally have a SDR (Sender) channel defined, which would point to a RCVR (Receiver) channel with the same name on the other queue manager.

For a MQ client connection the client application side of the channel is called a MQCD, and the MQ Queue Manager side is a SVRCONN (Server Connection) channel.  The client side MQCD can be specified in a few different ways.  The way you are demonstrating in the example you posted is programmatically specifying the MQCD information (channel name, hostname, etc).

An alternate way to specify the information is by pointing to a CCDT (Client Channel Definition Table) which is commonly referred to as a Channel Table, this is where a CLNTCONN channel would be used, since you are not using a Channel table I'll move on to why you are getting an error, but at the end of this answer I'll provide more details on Channel Tables.

In summary your application should not be specifying a CLNTCONN channel as the MQC.CHANNEL_PROPERTY it should be pointing to a SVRCONN channel.

Two things to note:

You should not use the predefined SYSTEM.* channels for this purpose (for example SYSTEM.DEF.SVRCONN), you should define a new channel for your application to use.  The default channels are meant to hold parameters that you want to be the defaults when creating a new channel of the same type.

MQ v7.1 and later come with a few CHLAUTH rules enabled by default which will block access to the SYSTEM.* channels.

If you want to define a SVRCONN channel using the command line program runmqsc on Windows run the following on a CMD prompt:

echo DEFINE CHL(TEST_QM_CHANNEL1) CHLTYPE(SVRCONN)|runmqsc TEST_QM

Few more details about Channel Tables:

Prior to MQ v8 the only supported method to generate a Channel Table was by defining CLNTCONN channels on a queue manager which creates a file called AMQCLCHL.TAB under the queue manager name folder in a directory called @ipcc.  The reason a queue manager comes with a channel called SYSTEM.DEF.CLNTCONNis to provide the default values when you create a new CLNTCONN channel. With v8 and later you can create the channel table using only the runmqsc -n mode, this will directly edit the channel table vs needing to create a CLNTCONN channel on a queue manager.  The MQ Client for v8 and later now comes with a client version of runmqsc that can be used to create and alter channel tables.

An application can point to the channel table file in a few different ways, a common way is by setting two environment variables (MQCHLLIB and MQCHLTAB).  The app then does not specify channel name, host name, etc in the program, it only needs to specify the name of the queue manager to connect to.

The order and where MQ looks for connection information is documented at the IBM v7.5 (or later) Knowledge Center page "Connecting IBM WebSphere MQ MQI client applications to queue managers".  Note this link is for MQI clients, but the same basic order applies to .NET clients as well.


问:
How to convert QImage(QPixmap) to PIL Image in Python 3?
I would like to convert a image from QImage or Qpixmap class to PIL Image.
I found this: Convert PyQt to PIL image

But it seems to doesn't work in Python3. Is the way to implement this to Pyhton3 or do it more simply using new approaches exist?

答:
According to the docs:

The StringIO and cStringIO modules are gone. Instead, import the io
  module and use io.StringIO or io.BytesIO for text and data
  respectively.

So the solution is to do the conversion of cStringIO.StringIO to io.BytesIO.

PyQt5:

```<code>import io
from PIL import Image
from PyQt5.QtGui import QImage
from PyQt5.QtCore import QBuffer

img = QImage("image.png")
buffer = QBuffer()
buffer.open(QBuffer.ReadWrite)
img.save(buffer, "PNG")
pil_im = Image.open(io.BytesIO(buffer.data()))
pil_im.show()
</code>```

PyQt4:

```<code>import io
from PIL import Image
from PyQt4.QtGui import QImage
from PyQt4.QtCore import QBuffer

img = QImage("image.png")
buffer = QBuffer()
buffer.open(QBuffer.ReadWrite)
img.save(buffer, "PNG")
pil_im = Image.open(io.BytesIO(buffer.data()))
pil_im.show()
</code>```

Body:
According to the docs:

The StringIO and cStringIO modules are gone. Instead, import the io
  module and use io.StringIO or io.BytesIO for text and data
  respectively.

So the solution is to do the conversion of cStringIO.StringIO to io.BytesIO.

PyQt5:

import io
from PIL import Image
from PyQt5.QtGui import QImage
from PyQt5.QtCore import QBuffer

img = QImage("image.png")
buffer = QBuffer()
buffer.open(QBuffer.ReadWrite)
img.save(buffer, "PNG")
pil_im = Image.open(io.BytesIO(buffer.data()))
pil_im.show()

PyQt4:

import io
from PIL import Image
from PyQt4.QtGui import QImage
from PyQt4.QtCore import QBuffer

img = QImage("image.png")
buffer = QBuffer()
buffer.open(QBuffer.ReadWrite)
img.save(buffer, "PNG")
pil_im = Image.open(io.BytesIO(buffer.data()))
pil_im.show()


问:
UIScrollView's origin changes after popping back to the UIViewController
I have a UIViewController subclass as a scene in the storyboard that contains a UIScrollView containing various subviews.  One of the subviews is a UIButton which segues into another scene UIViewController subclass.  When I come back from the view (pop the UIViewController off the navigation controller stack), I find that the scroll view's origin has somehow changed, although the contentsize and contentoffset seem correct.

What's also interesting is that the app has a tab bar, and when I tab away and back to that view, the scroll view is set back correctly with offset at (0, 0).

There is basically no code involved in this process, as it's pretty much all in the storyboard.  As I am fairly new to using the storyboard, I figure I'm doing something wrong, although I don't know what.  Any ideas as to what that may be?  Perhaps sizing issues or constraints?

答:
Have you tried checking the Extend Edges Under Opaque Bars option? It can be found in your controller attributes inspector inside the storyboard.

It did the trick for me using XCode 9 iOS 11.


问:
Latest records/messages present in a topic kafka
Is there a way to fetch the latest 1000 records/messages present in a topic in kafka ? similar to tail -f 1000 in case of a file in linux ?

答:
```<code>consumer = KafkaConsumer()
partition = TopicPartition('foo', 0)
start = 1234
end = 2345
consumer.assign([partition])
consumer.seek(partition, start)
for msg in consumer:
    if msg.offset > end:
        break
    else:
        print msg
</code>```

source

Body:
consumer = KafkaConsumer()
partition = TopicPartition('foo', 0)
start = 1234
end = 2345
consumer.assign([partition])
consumer.seek(partition, start)
for msg in consumer:
    if msg.offset > end:
        break
    else:
        print msg

source


问:
Time Based Eviction in Hazelcast
I am working on a requirement where i'd have N hazelcast instances running in a cluster and also have kafka consumers running on all of them.

Now the ask is, each message that comes in on kafka, should be added to the distributed map and the entry must be evicted every 20 seconds, which i did by using a combination of time to live and max-idle seconds parameters in the map config.

But what i really want is that when the entry is evicted, only one of the nodes should process it, right now, the entry eviction is being informed to all the nodes.

Let me know if any more information is needed.

答:
You have to add a localEntryListener to your distributed map so that a member will only receive notifications for which it is an owner.

e.g.

```<code>if(map != null){
            map.addLocalEntryListener(new EntryAddedListener<Long, Long>() {
                @Override
                public void entryAdded(EntryEvent<Long, Long> event) {
                    log.info("LOCAL ENTRY ADDED : {} at {}", event, System.currentTimeMillis());
                }
            });
</code>```

The above example is for the EntryAddedListener, you can similarly implement a EntryEvictedListener as well.

Title: Time Based Eviction in Hazelcast

Body:
You have to add a localEntryListener to your distributed map so that a member will only receive notifications for which it is an owner.

e.g.

if(map != null){
            map.addLocalEntryListener(new EntryAddedListener<Long, Long>() {
                @Override
                public void entryAdded(EntryEvent<Long, Long> event) {
                    log.info("LOCAL ENTRY ADDED : {} at {}", event, System.currentTimeMillis());
                }
            });

The above example is for the EntryAddedListener, you can similarly implement a EntryEvictedListener as well.


问:
What is the equivalent of T-SQL ISNUMERIC function in HANA Sqlscript?
I have a requirement where I need to convert all SQL Server stored procedures into HANA stored procedures. I have come across a function ISNUMERIC in T-SQL and I am not getting the equivalent of it in HANA.

After searching the web, I found that HANA does not have built in ISNUMERIC equivalent function. Then I tried writing my own function to achieve this and there I stuck with error handling and regular expression limitations.

My HANA version is 70.

答:
This solution should cover really all strings that are convertable as a number:

```<code>PROCEDURE "SCHEMA"."package::IS_NUMERIC" (
        in stringToCheck nvarchar(5000)
        ,out isNumeric integer
)
    LANGUAGE SQLSCRIPT
    SQL SECURITY INVOKER
    --DEFAULT SCHEMA <default_schema_name>
    READS SQL DATA AS
BEGIN

DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
    isNumeric := 0;
END;

select cast(:stringToCheck as double) from dummy;

isNumeric := 1;

END;
</code>```

e.g. also covers: call "SCHEMA"."package::IS_NUMERIC"('-12.345', ?)

Body:
This solution should cover really all strings that are convertable as a number:

PROCEDURE "SCHEMA"."package::IS_NUMERIC" (
        in stringToCheck nvarchar(5000)
        ,out isNumeric integer
)
    LANGUAGE SQLSCRIPT
    SQL SECURITY INVOKER
    --DEFAULT SCHEMA <default_schema_name>
    READS SQL DATA AS
BEGIN

DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
    isNumeric := 0;
END;

select cast(:stringToCheck as double) from dummy;

isNumeric := 1;

END;

e.g. also covers: call "SCHEMA"."package::IS_NUMERIC"('-12.345', ?)


问:
How can I include <bits/stdc++> in Xcode
I have tried to include the header file bits/stdc++ in my C++ code, but it seems the compiler doesn't support it. Is there any way to make it work?

I use OS X Yosemite 10.10.2 and Xcode 6.1.1.

答:
Open Finder.

Click Go on menu bar then click Go to folder or Press Command+Shift+G directly.

Enter the path /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1

Now, get the stdc++.h file from here, then create bits directory in the above long address, and copy the file stdc++.h to the bits directory.

ContentLicense: CC BY-SA 4.0


问:
SSRS 2017: Want to set a parameter to a default of NULL in a shared dateaset

the problem

I have a problem with a SSRS 2017 shared dataset.

This dataset is calling a stored procedure. One of the SP's parameters is of type DateTime. Within the dataset's parameters dialog I've set the default to (Null). But this seems to be ignored...

With paginated reports everything works fine. The defined report parameters (or built-in parameters) can be used to pass valid values.

But when I try to use this dataset within a mobile report I get an error. I cannot even add the dataset! After quite some search I found, that the SP was called with a blank instead of NULL (Pofiler tells me: ,@ClientTime=N''), hence the type conversion to DateTime failed.

I do not want to change this parameter to a string type, because this report will run in various environments. The correct date getting into the stored proc if taken as string is really awful: Nov 14 2017  3:35PM (culture and language dependant!) I do not want to rely on any conversion from string!

the question

How can I force a SSRS shared dataset to use a real NULL for a parameter?

答:
Are you hosting this dataset in SharePoint? If so, are you sure the default value is actually set on the SharePoint saved version? I've always observed, that while you can set the value to null in your report designer, when it saves to SharePoint, the null default is lost.  Simply, edit the dataset parameters from the SharePoint interface and select Null for the appropriate parameter after you have saved it. Although I haven't profiled parameters in a long timer, I often do a "@param IS NULL" test within my SQL and have never had issues.

Note that you don't have to do this each time you edit the dataset/report in the future, just on the initial save.


问:
MySQL - How to set to NOW() and NULL while inserting a row into a table?
```<code>INSERT INTO rental (rental_date, last_update, return_date)
    SET rental_date, last_update = NOW()
    AND return_date = NULL.
</code>```

I'm trying to insert rental_date, last_update and return_date into the table rental while also setting their timestamp to NOW() and NULL.

答:
You are mixing two different styles of INSERT.

Either use the syntax

```<code>INSERT INTO table (column1, column2) VALUES (value1, value2)
</code>```

or use

```<code>INSERT INTO table SET column1 = value1, column2 = value2
</code>```

but don't mix both.

Your values NOW() and NULL are basically correct so it's simply the way you do the insert.

Body:
INSERT INTO rental (rental_date, last_update, return_date)
    SET rental_date, last_update = NOW()
    AND return_date = NULL.

I'm trying to insert rental_date, last_update and return_date into the table rental while also setting their timestamp to NOW() and NULL.

Body:
You are mixing two different styles of INSERT.

Either use the syntax

INSERT INTO table (column1, column2) VALUES (value1, value2)

or use

INSERT INTO table SET column1 = value1, column2 = value2

but don't mix both.

Your values NOW() and NULL are basically correct so it's simply the way you do the insert.


问:
JavaScript smooth scroll - iphone
Are there any plugins or does anyone know of a good way to achieve the iPhone elastic band scroll?
working example in flash
http://www.shinedraw.com/text-effect/silverlight-3-and-flash-iphone-dragging-effect/

I'm looking to drag and scroll a div, but if it goes past a certain point it bounces back.

Thanks

答: Drew McCormack wrote an article for MacResearch about the physics of the bounce and momentum scrolling here, which includes JavaScript code for replicating much of the behavior you see on the iPhone.</p>

Title: JavaScript smooth scroll - iphone


问:
How to correctly malloc a struct in C
Here is my full code, it looks like to work, but it's not working very well.
I would accept any code, that is working like this.

Firstly, the code works, but when I want to add the third name to the struct, it crashes.

Is there any other way to do this?

I need struct, because in the future, I want to add some other params, like age, average, gender, etc.

Please, help me out.

```<code>//The student table
typedef struct students {
    char name[50];
} students;

//Global params
int scount = 0;
students *s;

//Basic functions
void addNewStudent();

int main()
{
    int loop = 1;
    char in;
    int ch;
    printf("Willkommen.\n Wahlen Sie bitte von die folgenden Optionen:\n");
    while (loop)
    {
        printf("\t[1] Neue Student eingeben\n");
        printf("\t[9] Programm beenden\n");

        scanf(" %c", &in);
        while ((ch = getchar()) != '\n');
        switch (in)
        {
        case '1':
            addNewStudent();
            break;
        case '9':
            loop = 0;
            break;
        default: printf("------\nOption nicht gefunden.\n------\n");
            break;
        }
    }
    free(s);
    return 0;
}

void addNewStudent()
{
    int index = 0;
    if (scount == 0)
    {
        s = (students*)malloc(sizeof(students));
    }
    else
    {
        realloc(s, sizeof(students) * scount);
    }

    printf("Geben Sie Bitte die Name:\n");
    fgets(s[scount].name, sizeof(s[scount].name), stdin);

    while (s[scount].name[index] != '\n')
    {
        index++;
    }
    s[scount].name[index] = '\0';
    scount++;
}
</code>```

I'm using Visual Studio.

Thanks for help!

答:
How to correctly malloc a struct in C ?

```<code>p = malloc(sizeof *p);
if (p == NULL) Handle_OutOfMemory();
</code>```

How to correctly re-allocate a struct in C ?

```<code>void *t = realloc(p, sizeof *p * number_of_elements);
if (t == NULL && number_of_elements > 0) {
  Handle_OutOfMemory();
} else {
  p = t;
}
</code>```

p points to some struct.  Notice no coding of that type in above.

OP' primary problem is not using the return value of realloc() and allocating 1-too-small

```<code>// realloc(s, sizeof(students) * scount);
s = realloc(s, sizeof *s * (scount+1));  // or use above code with check for out-of-memory.
</code>```

Title: How to correctly malloc a struct in C

Body:
Here is my full code, it looks like to work, but it's not working very well.
I would accept any code, that is working like this.

Firstly, the code works, but when I want to add the third name to the struct, it crashes.

Is there any other way to do this?

I need struct, because in the future, I want to add some other params, like age, average, gender, etc.

Please, help me out.

//The student table
typedef struct students {
    char name[50];
} students;

//Global params
int scount = 0;
students *s;

//Basic functions
void addNewStudent();

int main()
{
    int loop = 1;
    char in;
    int ch;
    printf("Willkommen.\n Wahlen Sie bitte von die folgenden Optionen:\n");
    while (loop)
    {
        printf("\t[1] Neue Student eingeben\n");
        printf("\t[9] Programm beenden\n");

        scanf(" %c", &in);
        while ((ch = getchar()) != '\n');
        switch (in)
        {
        case '1':
            addNewStudent();
            break;
        case '9':
            loop = 0;
            break;
        default: printf("------\nOption nicht gefunden.\n------\n");
            break;
        }
    }
    free(s);
    return 0;
}

void addNewStudent()
{
    int index = 0;
    if (scount == 0)
    {
        s = (students*)malloc(sizeof(students));
    }
    else
    {
        realloc(s, sizeof(students) * scount);
    }

    printf("Geben Sie Bitte die Name:\n");
    fgets(s[scount].name, sizeof(s[scount].name), stdin);

    while (s[scount].name[index] != '\n')
    {
        index++;
    }
    s[scount].name[index] = '\0';
    scount++;
}

I'm using Visual Studio.

Thanks for help!

Body:
How to correctly malloc a struct in C ?

p = malloc(sizeof *p);
if (p == NULL) Handle_OutOfMemory();

How to correctly re-allocate a struct in C ?

void *t = realloc(p, sizeof *p * number_of_elements);
if (t == NULL && number_of_elements > 0) {
  Handle_OutOfMemory();
} else {
  p = t;
}

p points to some struct.  Notice no coding of that type in above.

OP' primary problem is not using the return value of realloc() and allocating 1-too-small

// realloc(s, sizeof(students) * scount);
s = realloc(s, sizeof *s * (scount+1));  // or use above code with check for out-of-memory.


问:
Android DatePicker calendar's last row is cropped
I want to display a DatePicker, that contains only a calendar, but i get this kind of bug:

Screen with error

I found some people had this kind of problem too, but have somebody found a solution for this?

It occurs on Api > 21, most of resolutions.

答:
Found out that this can be easily reproduced after we set the Setting->Display->Display Size to Large. And then go to a month that needs to show 6 rows. The Google Calendar app have the same problem.

So it should be a bug in the DatePicker. The only easy solution is to change the datepicker to the spinner style.


问:
Nunitlite-runner.exe - Dll file has no TestFixtures
I'm trying run tests from nunitlite-runner.exe but i got Error message

1) Invalid : /myfile.dll
  Has no TestFixtures

I have in source code

```<code>[TestFixture]
public class MyClassName
{
   [Order(1)]
   [Test]
   public void Case1()
   {
       //
   }

   [Order(2)]
   [Test]
   public void Case2()
   {
       //
   }
}
</code>```

How can i fix code or run my tests?

答:
I got this problem with nunit3-console.exe. I had, in my enthusiasm to upgrade to the latest and greatest, updated my NUnit project references to the latest version (3.9 at this writing), along with my console exe (3.7). But it seems that the console exe is a build or two behind the core libraries, so you can't reference a later version of NUnit than the version you have of the console exe.

I downgraded my NUnit project reference to 3.7, and that fixed it for me.

Body:
I'm trying run tests from nunitlite-runner.exe but i got Error message

1) Invalid : /myfile.dll
  Has no TestFixtures

I have in source code

[TestFixture]
public class MyClassName
{
   [Order(1)]
   [Test]
   public void Case1()
   {
       //
   }

   [Order(2)]
   [Test]
   public void Case2()
   {
       //
   }
}

How can i fix code or run my tests?


问:
git rebase leaves extra "branch" in the commits
I was trying to squash some old commits back together, that have already been pushed to master.  I'm the only developer though so it's fine to force update the repository.  I started with this:

```<code>% git log --oneline --decorate --graph --all
* 4b2fec5 (HEAD -> master, tag: v6.2.5, origin/master, origin/HEAD) Version 6.2.5 - Fixed MegaMillions payout bug
* b0ae8a9 (tag: v6.2.4) Version 6.2.4 - Handles large size text
* f4763bd (tag: v6.2.3) 6.2.3
* 3f02a27 (tag: v6.2.1) Version 6.2.1
* 7703d55 (tag: v6.2.0) Updated revision
* a2c6366 Removed legacy NSNotification stuff.
* 1e3b359 Changes UITextFieldTextDidChange to use an onPost  handler.
* 35b910b Turns off the request for app store rating.
* 5c20d46 Put the detail segue back in.
* f90722d Got rid of stack view from MasterViewController
* eb34f07 Removed unnecessary null coalesce operator.
* c969126 Changed for Megamillions new payout structure.
* 2a32838 Version 6.2.0
* efb33b0 Initial commit
* 13a5b0e (tag: v6.0.1) 6.0.1 for app store
* 45ab2ba Downloads new numbers after creating a new ticket now.
* 2d60f30 Cancel button didn't have an exit segue on the master.
* 2185112 Changed to static size text for loser
* 872f408 Initial Commit
</code>```

And now I want to squish everything between the v6.2.0 tag and the Version 6.2.0 commit into a single commit, so I did a
git rebase -i efb33b0 which said it was successful.  But now I'm left with the following:

```<code>% git log --oneline --decorate --graph --all
* 0fb2623 (HEAD -> master) Version 6.2.5 - Fixed MegaMillions payout bug
* 81d3553 Version 6.2.4 - Handles large size text
* d7d7578 6.2.3
* eae8973 Version 6.2.1
* ded0fe9 Version 6.2.0
| * 4b2fec5 (tag: v6.2.5, origin/master, origin/HEAD) Version 6.2.5 - Fixed MegaMillions payout bug
| * b0ae8a9 (tag: v6.2.4) Version 6.2.4 - Handles large size text
| * f4763bd (tag: v6.2.3) 6.2.3
| * 3f02a27 (tag: v6.2.1) Version 6.2.1
| * 7703d55 (tag: v6.2.0) Updated revision
| * a2c6366 Removed legacy NSNotification stuff.
| * 1e3b359 Changes UITextFieldTextDidChange to use an onPost  handler.
| * 35b910b Turns off the request for app store rating.
| * 5c20d46 Put the detail segue back in.
| * f90722d Got rid of stack view from MasterViewController
| * eb34f07 Removed unnecessary null coalesce operator.
| * c969126 Changed for Megamillions new payout structure.
| * 2a32838 Version 6.2.0
|/
* efb33b0 Initial commit
* 13a5b0e (tag: v6.0.1) 6.0.1 for app store
* 45ab2ba Downloads new numbers after creating a new ticket now.
* 2d60f30 Cancel button didn't have an exit segue on the master.
* 2185112 Changed to static size text for loser
* 872f408 Initial Commit
</code>```

How do I get rid of that extra "branch" that's in there?  Basically it looks like that entire branch to the right just needs to go away, so that it only follows the main path...and somehow change the tags over too.

答:
The short answer is that you don't / can't.  (But see exception below.)

What git rebase does is copy some commits to make new, different commits, and then abandon the original set of commits in favor of the new-and-improved commits.

The problem that comes in at this point is that abandoning those commits works fine if and only if the branch you are "on" (as in git status says on branch master) is the only reference to those particular commits.  If there are additional reference(s) to some or all of the original commits, those references don't change!

This is true even, or maybe especially, if those references are in some other repository.  The latter can occur if you have git push-ed the commits to some other repository and had that other repository set some of its references to remember those commits.  This is why it's generally not great form to amend or rebase commits that you have already git pushed.

(Small side note: a reference is Git's generalization of branch and tag names.  There are more kinds, but these two are the most familiar ones.  A branch name is just a reference whose full name starts with refs/heads/: the rest of the name is the branch name.  So refs/heads/master is the full reference name of branch name master.)

It can be done, if it's OK with everyone

If:

you're sure no one else has these commit hashes stored away in some other clones, or

you have pre-arranged with everyone else who does have these commit hashes stored away, that everyone will switch all their references as needed,

then (and only then) it is perfectly fine to rebase shared commits like this.  To do that, after copying the old, slightly-defective commits to shiny new commits, you must find all references (in all repository copies!) that use the old commits, and move them so that they refer instead to the shiny new commits.

In your case, I count at least six (6) such references:

tag v6.2.0 (refs/tags/v6.2.0);

tag v6.2.1;

tag v6.2.3;

tag v6.2.4;

tag v6.2.5;

branch master on another Git over at origin, which your Git is remembering for you as your origin/master (that's their refs/heads/master and your refs/remotes/origin/master).

If you convince them to move their master (by force-push for instance), your own Git's memory in your refs/remotes/origin/master reference will change automatically.  If you convince them to move all five of the other tags, and you move all five of your tags, that will eliminate all six of these names-for-the-old commits.  Git will then stop showing you the old commits, and eventually they will truly expire and be garbage-collected away.

To force-push your new master you can just git push --force origin master (but hold off on it for a moment).  That still leaves you to re-adjust each of your tags, one by one, to point to the shiny new copied commits—each one has a different new, shiny hash ID—and then force-push those tags, with git push --force --tags, and hope that they (whoever "they" are on origin) allow all these force-pushes.  You can push them all at once with git push --force --tags master.

The problem with changing other people's references lies in getting all of them.  Otherwise the old references, and hence the old commits, can come back to haunt you.  But if your Git and the Git on origin are the only copies of this repository, and you control both of those, you can do what you want.

Body:
I was trying to squash some old commits back together, that have already been pushed to master.  I'm the only developer though so it's fine to force update the repository.  I started with this:

% git log --oneline --decorate --graph --all
* 4b2fec5 (HEAD -> master, tag: v6.2.5, origin/master, origin/HEAD) Version 6.2.5 - Fixed MegaMillions payout bug
* b0ae8a9 (tag: v6.2.4) Version 6.2.4 - Handles large size text
* f4763bd (tag: v6.2.3) 6.2.3
* 3f02a27 (tag: v6.2.1) Version 6.2.1
* 7703d55 (tag: v6.2.0) Updated revision
* a2c6366 Removed legacy NSNotification stuff.
* 1e3b359 Changes UITextFieldTextDidChange to use an onPost  handler.
* 35b910b Turns off the request for app store rating.
* 5c20d46 Put the detail segue back in.
* f90722d Got rid of stack view from MasterViewController
* eb34f07 Removed unnecessary null coalesce operator.
* c969126 Changed for Megamillions new payout structure.
* 2a32838 Version 6.2.0
* efb33b0 Initial commit
* 13a5b0e (tag: v6.0.1) 6.0.1 for app store
* 45ab2ba Downloads new numbers after creating a new ticket now.
* 2d60f30 Cancel button didn't have an exit segue on the master.
* 2185112 Changed to static size text for loser
* 872f408 Initial Commit

And now I want to squish everything between the v6.2.0 tag and the Version 6.2.0 commit into a single commit, so I did a
git rebase -i efb33b0 which said it was successful.  But now I'm left with the following:

% git log --oneline --decorate --graph --all
* 0fb2623 (HEAD -> master) Version 6.2.5 - Fixed MegaMillions payout bug
* 81d3553 Version 6.2.4 - Handles large size text
* d7d7578 6.2.3
* eae8973 Version 6.2.1
* ded0fe9 Version 6.2.0
| * 4b2fec5 (tag: v6.2.5, origin/master, origin/HEAD) Version 6.2.5 - Fixed MegaMillions payout bug
| * b0ae8a9 (tag: v6.2.4) Version 6.2.4 - Handles large size text
| * f4763bd (tag: v6.2.3) 6.2.3
| * 3f02a27 (tag: v6.2.1) Version 6.2.1
| * 7703d55 (tag: v6.2.0) Updated revision
| * a2c6366 Removed legacy NSNotification stuff.
| * 1e3b359 Changes UITextFieldTextDidChange to use an onPost  handler.
| * 35b910b Turns off the request for app store rating.
| * 5c20d46 Put the detail segue back in.
| * f90722d Got rid of stack view from MasterViewController
| * eb34f07 Removed unnecessary null coalesce operator.
| * c969126 Changed for Megamillions new payout structure.
| * 2a32838 Version 6.2.0
|/
* efb33b0 Initial commit
* 13a5b0e (tag: v6.0.1) 6.0.1 for app store
* 45ab2ba Downloads new numbers after creating a new ticket now.
* 2d60f30 Cancel button didn't have an exit segue on the master.
* 2185112 Changed to static size text for loser
* 872f408 Initial Commit

How do I get rid of that extra "branch" that's in there?  Basically it looks like that entire branch to the right just needs to go away, so that it only follows the main path...and somehow change the tags over too.


问:
What is target protocol address in ARP request message
I am trying to understand about ARP and its application.
So far i have read about the structure of an ARP request message header. It consists of following fields with relevant info to be filled

```<code>Hardware Type(2 Bytes):  1 (for Ethernet is 1)
Protocol Type(2 Bytes): IPv4 2048
Hardware Address Length (1 Bytes): Ethernet MAC address is 6 bytes
Protocol Address Length(1 Byte): IPv4 is 4
OP Code(2 bytes) : 1 for ARP request and 2 arp reply
Sender Hardware Address(6 Bytes): MAC address of device sending message (my         MAC)
Sender Protocol Address( bytes 1 and 2):protocol address of device sending(my IP)
target hardware address (6 bytes):should all be set to 0
Target Protocol Address (4 bytes):What should be in this field?
</code>```

Well my simple question is:

If ARP is a broadcast message (which means, it is a message sent to many from a single node), how would I know what target protocol address to fill? Which raises another question, can ARP not be used to ping all the devices connected (known and unknown) in the network and get their MAC and IP.

答:
ARP (Address Resolution Protocol) resolves a layer-2 address from a layer-3 address. An ARP request is broadcast at layer-2 with a specific layer-3 address for which you want to resolve the layer-2 address.

Basically, you are asking every host on the layer-2 domain, "Who has this specific layer-3 address?" Every host on the layer-2 domain will receive the request, but only the host with that layer-3 address will respond to the request, supplying its layer-2 address to the requesting host.

Body:
I am trying to understand about ARP and its application.
So far i have read about the structure of an ARP request message header. It consists of following fields with relevant info to be filled

Hardware Type(2 Bytes):  1 (for Ethernet is 1)
Protocol Type(2 Bytes): IPv4 2048
Hardware Address Length (1 Bytes): Ethernet MAC address is 6 bytes
Protocol Address Length(1 Byte): IPv4 is 4
OP Code(2 bytes) : 1 for ARP request and 2 arp reply
Sender Hardware Address(6 Bytes): MAC address of device sending message (my         MAC)
Sender Protocol Address( bytes 1 and 2):protocol address of device sending(my IP)
target hardware address (6 bytes):should all be set to 0
Target Protocol Address (4 bytes):What should be in this field?

Well my simple question is:

If ARP is a broadcast message (which means, it is a message sent to many from a single node), how would I know what target protocol address to fill? Which raises another question, can ARP not be used to ping all the devices connected (known and unknown) in the network and get their MAC and IP.