问:
Why does Newtonsoft Replace function only replace the value if it is changed?
Take the following code:

```<code>JProperty toke = new JProperty("value", new JValue(50)); //toke.Value is 50
toke.Value.Replace(new JValue(20)); //toke.Value is 20
</code>```

This works as expected. Now examine the following code:

```<code>JValue val0 = new JValue(50);
JProperty toke = new JProperty("value", val0); //toke.Value is 50
JValue val1 = new JValue(20);
toke.Value.Replace(val1); //toke.Value is 20
</code>```

This also works as expected, but there is an important detail. val0 is no longer part of the toke's JSON tree, and val1 is part of the JSON tree; this means that val0 has no valid parent, while val1 does.

Now take this code.

```<code>JValue val0 = new JValue(50);
JProperty toke = new JProperty("value", val0); //toke.Value is 50
JValue val1 = new JValue(50);
toke.Value.Replace(val1); //toke.Value is 50
</code>```

The behavior is different; val0 is still part of toke's JSON tree, and val1 is not. Now val0 has a valid parent, while val1 does not.

This is a critical distinction, and if you are using Newtonsoft JSON tree's to represent a structure, and storing JTokens as references into the tree, the way the references are structure can change based on the value being Replaced, which seems incorrect.

Is there any flaw with my reasoning? Or is behavior incorrect, as I believe it is?

答:
I think you have a valid point: Replace should replace the token instance and set the parent properly even if the tokens have the same values.

This works as you would expect if the property value is a JObject and you replace it with an identical JObject:

JObject obj1 = JObject.Parse(@"{ ""foo"" : 1 }");
JProperty prop = new JProperty("bar", obj1);

JObject obj2 = JObject.Parse(@"{ ""foo"" : 1 }");
prop.Value.Replace(obj2);

Console.WriteLine("obj1 parent is " +
        (ReferenceEquals(obj1.Parent, prop) ? "prop" : "not prop"));    // "not prop"
Console.WriteLine("obj2 parent is " +
        (ReferenceEquals(obj2.Parent, prop) ? "prop" : "not prop"));    // "prop"
```

<p>However, the code seems to have been deliberately written to work differently for <code>JValues</code>.  In the source code we see that <code>JToken.Replace()</code> calls <code>JContainer.ReplaceItem()</code>, which in turn calls <code>SetItem()</code>.  In the <code>JProperty</code> class, <code>SetItem()</code> is implemented like this:</p>

<pre class="lang-cs prettyprint-override"><code>internal override void SetItem(int index, JToken item)
{
    if (index != 0)
    {
        throw new ArgumentOutOfRangeException();
    }

    if (IsTokenUnchanged(Value, item))
    {
        return;
    }

    if (Parent != null)
    {
        ((JObject)Parent).InternalPropertyChanging(this);
    }

    base.SetItem(0, item);

    if (Parent != null)
    {
        ((JObject)Parent).InternalPropertyChanged(this);
    }
}
</code>```

You can see that it checks whether the value is "unchanged", and if so, it returns without doing anything.  If we look at the implementation of IsTokenUnchanged() we see this:

internal static bool IsTokenUnchanged(JToken currentValue, JToken newValue)
{
    JValue v1 = currentValue as JValue;
    if (v1 != null)
    {
        // null will get turned into a JValue of type null
        if (v1.Type == JTokenType.Null && newValue == null)
        {
            return true;
        }

        return v1.Equals(newValue);
    }

    return false;
}
```

So, if the current token is a JValue, it checks whether it Equals the other token, otherwise the token is automatically considered to have changed.  And Equals for a JValue is of course based on whether the underlying primitives themselves are equal.

I cannot speak to the reasoning behind this implementation decision, but it seems to be worth reporting an issue to the author.  The "correct" fix, I think, would be to make SetItem use ReferenceEquals(Value, item) instead of IsTokenUnchanged(Value, item).

Body:
Take the following code:

JProperty toke = new JProperty("value", new JValue(50)); //toke.Value is 50
toke.Value.Replace(new JValue(20)); //toke.Value is 20

This works as expected. Now examine the following code:

JValue val0 = new JValue(50);
JProperty toke = new JProperty("value", val0); //toke.Value is 50
JValue val1 = new JValue(20);
toke.Value.Replace(val1); //toke.Value is 20

This also works as expected, but there is an important detail. val0 is no longer part of the toke's JSON tree, and val1 is part of the JSON tree; this means that val0 has no valid parent, while val1 does.

Now take this code.

JValue val0 = new JValue(50);
JProperty toke = new JProperty("value", val0); //toke.Value is 50
JValue val1 = new JValue(50);
toke.Value.Replace(val1); //toke.Value is 50

The behavior is different; val0 is still part of toke's JSON tree, and val1 is not. Now val0 has a valid parent, while val1 does not.

This is a critical distinction, and if you are using Newtonsoft JSON tree's to represent a structure, and storing JTokens as references into the tree, the way the references are structure can change based on the value being Replaced, which seems incorrect.

Is there any flaw with my reasoning? Or is behavior incorrect, as I believe it is?

Body:
I think you have a valid point: Replace should replace the token instance and set the parent properly even if the tokens have the same values.

This works as you would expect if the property value is a JObject and you replace it with an identical JObject:

JObject obj1 = JObject.Parse(@"{ ""foo"" : 1 }");
JProperty prop = new JProperty("bar", obj1);

JObject obj2 = JObject.Parse(@"{ ""foo"" : 1 }");
prop.Value.Replace(obj2);

Console.WriteLine("obj1 parent is " +
        (ReferenceEquals(obj1.Parent, prop) ? "prop" : "not prop"));    // "not prop"
Console.WriteLine("obj2 parent is " +
        (ReferenceEquals(obj2.Parent, prop) ? "prop" : "not prop"));    // "prop"

However, the code seems to have been deliberately written to work differently for JValues.  In the source code we see that JToken.Replace() calls JContainer.ReplaceItem(), which in turn calls SetItem().  In the JProperty class, SetItem() is implemented like this:

internal override void SetItem(int index, JToken item)
{
    if (index != 0)
    {
        throw new ArgumentOutOfRangeException();
    }

    if (IsTokenUnchanged(Value, item))
    {
        return;
    }

    if (Parent != null)
    {
        ((JObject)Parent).InternalPropertyChanging(this);
    }

    base.SetItem(0, item);

    if (Parent != null)
    {
        ((JObject)Parent).InternalPropertyChanged(this);
    }
}

You can see that it checks whether the value is "unchanged", and if so, it returns without doing anything.  If we look at the implementation of IsTokenUnchanged() we see this:

internal static bool IsTokenUnchanged(JToken currentValue, JToken newValue)
{
    JValue v1 = currentValue as JValue;
    if (v1 != null)
    {
        // null will get turned into a JValue of type null
        if (v1.Type == JTokenType.Null && newValue == null)
        {
            return true;
        }

        return v1.Equals(newValue);
    }

    return false;
}

So, if the current token is a JValue, it checks whether it Equals the other token, otherwise the token is automatically considered to have changed.  And Equals for a JValue is of course based on whether the underlying primitives themselves are equal.

I cannot speak to the reasoning behind this implementation decision, but it seems to be worth reporting an issue to the author.  The "correct" fix, I think, would be to make SetItem use ReferenceEquals(Value, item) instead of IsTokenUnchanged(Value, item).


来源: stackexchange

问:
Change output variable PHP fputcsv
I'm outputting SQL data into a CSV file and want to make the data more user readable. Currently field terminal_id returns various integers and I want to translate it into more user readable data.

In the different rows I have integers from 1-10 in this field. I essentially want it to output as a simple text string in the CSV file dependent on what the integer is. So for instance, instead of outputting 3 in the CSV file (just a random example), I need it to output New York.

I have a separate table called terminal that has columns id and name. name is what I actually want outputting to the CSV file rather than terminal_id.

The column in table terminalcashcollectionrecord that has the 3 in it is terminal_id. This is the correlating data in table terminal that also has column name in it.

Here's the code a snippet of that specific code:

```<code>//query the database
$query = 'SELECT terminaltime, terminal_id, amount, terminaltime FROM terminalcashcollectionrecord';

if ($rows = mysqli_query($link, $query))
{
    // loop over the rows, outputting them
    while ($row = mysqli_fetch_assoc($rows))
    {
        fputcsv($output, $row);
    }
</code>```

答:
This should select terminaltime and amount from terminalcashcollectionrecord and name from terminal where terminal_id equals id. You had terminaltime listed twice so I removed the second one:

```<code>SELECT a.terminaltime, b.name, a.amount
    FROM terminalcashcollectionrecord a
    LEFT JOIN terminal b
    ON a.terminal_id = b.id
</code>```

See MySQL JOIN Syntax.

ContentLicense: CC BY-SA 3.0

Title: Change output variable PHP fputcsv

Body:
I'm outputting SQL data into a CSV file and want to make the data more user readable. Currently field terminal_id returns various integers and I want to translate it into more user readable data.

In the different rows I have integers from 1-10 in this field. I essentially want it to output as a simple text string in the CSV file dependent on what the integer is. So for instance, instead of outputting 3 in the CSV file (just a random example), I need it to output New York.

I have a separate table called terminal that has columns id and name. name is what I actually want outputting to the CSV file rather than terminal_id.

The column in table terminalcashcollectionrecord that has the 3 in it is terminal_id. This is the correlating data in table terminal that also has column name in it.

Here's the code a snippet of that specific code:

//query the database
$query = 'SELECT terminaltime, terminal_id, amount, terminaltime FROM terminalcashcollectionrecord';

if ($rows = mysqli_query($link, $query))
{
    // loop over the rows, outputting them
    while ($row = mysqli_fetch_assoc($rows))
    {
        fputcsv($output, $row);
    }

Body:
This should select terminaltime and amount from terminalcashcollectionrecord and name from terminal where terminal_id equals id. You had terminaltime listed twice so I removed the second one:

SELECT a.terminaltime, b.name, a.amount
    FROM terminalcashcollectionrecord a
    LEFT JOIN terminal b
    ON a.terminal_id = b.id

See MySQL JOIN Syntax.


问:
Check python var if int
I am trying to get python to check if a certain variable is an int

```<code>    numbergames = input("Number of Games to Analyze: ")
valuenumber = True
while valuenumber == True:
    if numbergames == int:
        valuenumber = False
    if numbergames != int:
        numbergames = input("Please type a valid number: ")
print("Thanks")
</code>```

The code is getting stuck and is not getting out of the loop even thought the number typed is an int.

答:
In general, it is discouraged to use type() as identifying if an input is int, float, etc. This is because it does not register a subclass of int as an int.

Instead, use isinstance('var', (int, long)) which will give the right result expected. So your code will take the form of:

```<code>numberGames = input("Number of Games to Analyze: ")

while True:
    if isinstance( numberGames, (int, long) ):
        break
    else:
        numberGames = input("Please type a valid number: ")
print("Thanks")
</code>```

You don't need the valueNumber variable because its only use is as a flag for the while loop. Instead, it could continue running indefinitely with True until it reaches break because the statement tells the program to exit the loop.

Title: Check python var if int

Body:
I am trying to get python to check if a certain variable is an int

    numbergames = input("Number of Games to Analyze: ")
valuenumber = True
while valuenumber == True:
    if numbergames == int:
        valuenumber = False
    if numbergames != int:
        numbergames = input("Please type a valid number: ")
print("Thanks")

The code is getting stuck and is not getting out of the loop even thought the number typed is an int.

Body:
In general, it is discouraged to use type() as identifying if an input is int, float, etc. This is because it does not register a subclass of int as an int.

Instead, use isinstance('var', (int, long)) which will give the right result expected. So your code will take the form of:

numberGames = input("Number of Games to Analyze: ")

while True:
    if isinstance( numberGames, (int, long) ):
        break
    else:
        numberGames = input("Please type a valid number: ")
print("Thanks")

You don't need the valueNumber variable because its only use is as a flag for the while loop. Instead, it could continue running indefinitely with True until it reaches break because the statement tells the program to exit the loop.


问:
Why isn't Adobe Phonegap Build not including my plugin in the built apk?
I wrote a game using Intel XDK with Phaser framework. To get low latency audio playback I used cordova-plugin-nativeaudio. I checked the plugin folder and also config.xml, the plugin is included. But when I upload the zip build file to Adobe Phonegap, the core cordova plugins are included in the apk but not the one mentioned above. I checked the build log and even installed the apk on my phone but there was no audio. I have tried all three methods of Intel XDK for installing plugins namely npm, local and git repo. But all methods have the same result. Intel XDK installs  but Phonegap Build doesn't include it during build process. Also I can't build on my machine currently because I having some issues with Android Studio. I also checked the pricing plan & my plan does have the option of third party plugins. Any suggestions as to what might be causing the problem ?</p>

答: Problem solved. My app's name contained a special character, an '&'. Had to replace it in the name tag.</p>


问:
Input value equal/match to a any value in declared array with strings
I have this JS code, I need to compare the input value with the array, if the input value match with some value in the array then show the related message, but I can't get the array values and compare them with my input value.</p>

```<code>var invalidkeyreservation = ['ABCDEF','GHIJK','LMNOP'];

    if ($("input.reservationkey").val() === invalidkeyreservation) {
        BootstrapDialog.show(return $content;}

    } else{
        window.location.href = "/branches/Cancelaciones/Seleccion.html";
    }
</code>```

答:
This is what .indexOf() is for.

var invalidkeyreservation = ['ABCDEF','GHIJK','LMNOP'];

if (invalidkeyreservation.indexOf($("input.reservationkey").val()) > -1) {
  BootstrapDialog.show(return $content;}
} else{
  window.location.href = "/branches/Cancelaciones/Seleccion.html";
}```

Body:
I have this JS code, I need to compare the input value with the array, if the input value match with some value in the array then show the related message, but I can't get the array values and compare them with my input value.

var invalidkeyreservation = ['ABCDEF','GHIJK','LMNOP'];

    if ($("input.reservationkey").val() === invalidkeyreservation) {
        BootstrapDialog.show(return $content;}

    } else{
        window.location.href = "/branches/Cancelaciones/Seleccion.html";
    }


问:
Fastest way to find index of elements in a list
I have a set of samples (say X) with some features (say Y) on which I need to run some machine learning algorithms (say PCA). One way is to generate the matrix (sample, feature). My approach to constructing the matrix involves 2 steps:

Get all the feature values for the entire dataset. Let's call it a pool.

For a sample, for each value in the sample, find the value's index in the pool. The index's where the value is present is 1 and absent is 0.

Ex: Consider the below example

```<code>sample1 = A, B, D
sample2 = A, C, E
sample3 = A, C, D
</code>```

Generated pool = A, B, C, D, E

Generated matrix

sample 1 => 1, 1, 0, 1, 0

sample 2 => 1, 0, 1, 0, 1

sample 3 => 1, 0, 0, 1, 0

The challenge in generating this matrix is that, the data is very huge. The number of rows are 465337 and the number of columns are 35526155.

Generating the pool took around 20 minutes and even though this is slow, I am fine with it. But when generating the vector (i.e. row) of the matrix, I have to get for all the values of the sample under consideration the index of that value in the pool.

This is taking a huge time. Is there a better approach to find the index of elements? If the procedure itself is not optimal, please let me know of a better way to generate the matrix.

Also, I am just storing the indices and constructing a CSR matrix out of it instead of a dense matrix.

答:
You can achieve this type of Encoding using scikit-learn's Count Vectorizer. See here for an example usecase. Because you mention machine learning and are using Python, I assume you are familiar with sklearn in general.

However, since CountVectorizer is intended for text tokenizing, using it for your problem is a bit hacky.

For example, if you have your input data in this format:

```<code>samples = [['A', 'B', 'D'],
           ['A', 'C', 'E'],
           ['A', 'C', 'D']]
</code>```

You should first transform the inner lists to strings:

```<code>samples_s = ["".join(l) for l in samples]
</code>```

which gives

```<code>['ABD', 'ACE', 'ACD']
</code>```

Now you can fit an instance of CountVectorizer. You just have to define what constitutes a token. Here I used a simple regex to define any single character (e.g. "A", "B" or "C") as a token. You can also provide a static vocabulary.

```<code>vec = CountVectorizer(token_pattern='.')
X = vec.fit_transform(samples_s)
</code>```

Calling X.toarray() returns

```<code>array([[1, 1, 0, 1, 0],
       [1, 0, 1, 0, 1],
       [1, 0, 1, 1, 0]], dtype=int64)
</code>```

Using sklearn's implementation should be much faster than doing the encoding yourself.

Body:
I have a set of samples (say X) with some features (say Y) on which I need to run some machine learning algorithms (say PCA). One way is to generate the matrix (sample, feature). My approach to constructing the matrix involves 2 steps:

Get all the feature values for the entire dataset. Let's call it a pool.

For a sample, for each value in the sample, find the value's index in the pool. The index's where the value is present is 1 and absent is 0.

Ex: Consider the below example

sample1 = A, B, D
sample2 = A, C, E
sample3 = A, C, D

Generated pool = A, B, C, D, E

Generated matrix

sample 1 => 1, 1, 0, 1, 0

sample 2 => 1, 0, 1, 0, 1

sample 3 => 1, 0, 0, 1, 0

The challenge in generating this matrix is that, the data is very huge. The number of rows are 465337 and the number of columns are 35526155.

Generating the pool took around 20 minutes and even though this is slow, I am fine with it. But when generating the vector (i.e. row) of the matrix, I have to get for all the values of the sample under consideration the index of that value in the pool.

This is taking a huge time. Is there a better approach to find the index of elements? If the procedure itself is not optimal, please let me know of a better way to generate the matrix.

Also, I am just storing the indices and constructing a CSR matrix out of it instead of a dense matrix.

Body:
You can achieve this type of Encoding using scikit-learn's Count Vectorizer. See here for an example usecase. Because you mention machine learning and are using Python, I assume you are familiar with sklearn in general.

However, since CountVectorizer is intended for text tokenizing, using it for your problem is a bit hacky.

For example, if you have your input data in this format:

samples = [['A', 'B', 'D'],
           ['A', 'C', 'E'],
           ['A', 'C', 'D']]

You should first transform the inner lists to strings:

samples_s = ["".join(l) for l in samples]

which gives

['ABD', 'ACE', 'ACD']

Now you can fit an instance of CountVectorizer. You just have to define what constitutes a token. Here I used a simple regex to define any single character (e.g. "A", "B" or "C") as a token. You can also provide a static vocabulary.

vec = CountVectorizer(token_pattern='.')
X = vec.fit_transform(samples_s)

Calling X.toarray() returns

array([[1, 1, 0, 1, 0],
       [1, 0, 1, 0, 1],
       [1, 0, 1, 1, 0]], dtype=int64)

Using sklearn's implementation should be much faster than doing the encoding yourself.


问:
Get country from latitude longitude
I would like to know how I can get the country name from latitude & longitude using JavaScript. I am open to use of Google Maps’ JavaScript API. Can I also get city and zip?

Edit: My aim is to fill up the address field automatically, not to display it on a map.

答:
I don't know if it works with google maps, but there is a web service that returns a country code and takes as parameters the lat and long.

Here is an example:

http://api.geonames.org/countryCodeJSON?lat=49.03&lng=10.2&username=demo

Returns a JSON data:
{"languages":"de","distance":"0","countryCode":"DE","countryName":"Germany"}

I also found a little description:

The iso country code of any given point.

Webservice Type: REST

Url: ws.geonames.org/countryCode?

Parameters: lat, lng, type, lang, radius (buffer in km for closest country in coastal areas)

Result: returns the iso country code for the given latitude/longitude

With the parameter type=xml this service returns an xml document with iso country code and country name. The optional parameter lang can be used to specify the language the country name should be in. JSON output is produced with type=JSON

See the docs

Edit: Please note that demo is just a demonstration user and you should create a user account at http://www.geonames.org/login in order to use the service.

ContentLicense: CC BY-SA 4.0

Title: Get country from latitude longitude


答:
Maybe you want to use includes:

```<code>var invalidkeyreservation = ['ABCDEF','GHIJK','LMNOP'];

if (invalidkeyreservation.includes($("input.reservationkey").val())) {
    BootstrapDialog.show(return $content;}
} else{
    window.location.href = "/branches/Cancelaciones/Seleccion.html";
}
</code>```

Obs: If you are targeting to old browsers, there is polyfill available, or just use indexOf, as shown in the other answer.

Title: Input value equal/match to a any value in declared array with strings

Body:
Maybe you want to use includes:

var invalidkeyreservation = ['ABCDEF','GHIJK','LMNOP'];

if (invalidkeyreservation.includes($("input.reservationkey").val())) {
    BootstrapDialog.show(return $content;}
} else{
    window.location.href = "/branches/Cancelaciones/Seleccion.html";
}

Obs: If you are targeting to old browsers, there is polyfill available, or just use indexOf, as shown in the other answer.


问:
Read and Write Image Block into DDR using Vivado IP Block
We are working on project where we need to do some image processing on FPGA. For that purpose we are using ZedBoard with linaro (Ubuntu Version) running on it.
What we have already done is we have stored the image in binary form pixel by pixel in DDR using python script on Processing System of Zedboard.

Now our task is to read the content of DDR memory, process it and send back the processed output to DDR Memory again. We are using vivado xilinx tool for FPGA part. We tried to use AXI-DMA with AXI-Interconnect to read and write data from DDR.
My question is, Do We need to use SDK and some sort of C coding to read and write DDR Memory on Programmable Logic side? As we want to make our module start reading the data from DDR with a control signal and then start actual processing of Image data. Once we read specific block of data, process it and store the result back to DDR memory on the fly. We are not sure which IP Block do we need in our block design for vivado. Also do we need Block Ram Memory at the end before sending the date to DDR.

Can anyone who already done this sort of project or have any knowledge ? Any help from your side will be appreciated !

Thanks

答:
The zynq FPGA provide an AMBA AXI interconnect for that purpose.

This is the interconnect on the right.


问:
Triggering Events on Siblings Vuejs
I have a form and in that from I do a foreach over each field and pass the fields into their own components. I would like to trigger an event that propagates to all sibling fields triggered from a field component.

I know that I can do this from the field component
this.dispatch('activeField', this.field);

And then form the Form component
this.broadcast('activeField', this.field);

It seems like there should be a way of doing this without the overhead of involving the parent. I'm using Vue 1.0 and this example is just to demonstrate an issue I'm running into.
This is pseudo code so there very well could be typos.

答:
The "full-blown" methodology is to use Vuex or another shared state flux provider.  However, that isn't absolutely necessary.

You can also utilize a standalone Vue instance as an event bus to emit a message from the field component and receive it in the form component.

eventBusWrapper.js

```<code>import Vue from 'vue'

const EventBus = new Vue()
export default {
    EventBus
}
</code>```

Field Component

```<code>import EventBus from './eventBusWrapper'
EventBus.$emit('activeField', this.field)
</code>```

Form Component

```<code>import EventBus from './eventBusWrapper'
EventBus.$on('activeField', (field) => {
    console.log(field)
});
</code>```

Title: Triggering Events on Siblings Vuejs

Body:
The "full-blown" methodology is to use Vuex or another shared state flux provider.  However, that isn't absolutely necessary.

You can also utilize a standalone Vue instance as an event bus to emit a message from the field component and receive it in the form component.

eventBusWrapper.js

import Vue from 'vue'

const EventBus = new Vue()
export default {
    EventBus
}

Field Component

import EventBus from './eventBusWrapper'
EventBus.$emit('activeField', this.field)

Form Component

import EventBus from './eventBusWrapper'
EventBus.$on('activeField', (field) => {
    console.log(field)
});


问:
2 rows of images (odd numbers of images)
I want to make 2 rows of images like this (from 5 images):

     Image Image

  Image Image Image

But how can I center the first row?

My result looks like this:

Image Image

  Image Image Image

figure img {
  -webkit-transform: scale(1);
  transform: scale(1);
  -webkit-transition: .3s ease-in-out;
  transition: .3s ease-in-out;
}

figure:hover img {
  -webkit-transform: scale(1.05);
  transform: scale(1.05);
  position: relative;
  height: auto;
  display: block;
  z-index: 999;
  border: 1px solid #ffffff;
  background-color: #ffffff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table border="0">

  <tr>

    <td>
      <figure style="margin: 0;">
        <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
      </figure>
    </td>

    <td>
      <figure style="margin:0">
        <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
      </figure>
    </td>

  </tr>

  <tr>

    <td>
      <figure style="margin: 0;">
        <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
      </figure>
    </td>

    <td>
      <figure style="margin:0">
        <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
      </figure>
    </td>

    <td>
      <figure style="margin: 0">
        <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
      </figure>
    </td>

  </tr>

</table></code>```

View on JSFiddle

答:
.row {
  display: table;
  margin: 10px auto;
}

.row img {
  display:inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
  <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
</div>

<div class="row">
  <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
  <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
  <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
</div></code>```

Body:
I want to make 2 rows of images like this (from 5 images):

     Image Image

  Image Image Image

But how can I center the first row?

My result looks like this:

Image Image

  Image Image Image

figure img {
  -webkit-transform: scale(1);
  transform: scale(1);
  -webkit-transition: .3s ease-in-out;
  transition: .3s ease-in-out;
}

figure:hover img {
  -webkit-transform: scale(1.05);
  transform: scale(1.05);
  position: relative;
  height: auto;
  display: block;
  z-index: 999;
  border: 1px solid #ffffff;
  background-color: #ffffff;
}

View on JSFiddle

Body:
.row {
  display: table;
  margin: 10px auto;
}

.row img {
  display:inline-block;
}

<div class="row">
  <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
  <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
</div>

<div class="row">
  <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
  <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
  <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
</div>


问:
HQl equivalent of sql query
```<code>String SQL_QUERY = "SELECT count(*) FROM (SELECT * FROM Url as U where U.pageType=" + 1 + " group  by U.pageId having count(U.pageId) = 1)";
query = session.createQuery(SQL_QUERY);
</code>```

I am getting an error

org.hibernate.hql.ast.QuerySyntaxException: unexpected token: ( near line 1, column 23 [ SELECT count() FROM (SELECT * FROM Url as U where U.pageType = 2 group by U.pageId having count(U.pageId) = 1)]

答:
Your query seems to be ok as HQL code. Pay attention to the Capital letters for the entities: for example url in your bean class could be Url.

Anyway there's the method createSQLQuery(queryString) to run a query in SQL language.

ContentLicense: CC BY-SA 2.5

Title: HQl equivalent of sql query

Body:
String SQL_QUERY = "SELECT count(*) FROM (SELECT * FROM Url as U where U.pageType=" + 1 + " group  by U.pageId having count(U.pageId) = 1)";
query = session.createQuery(SQL_QUERY);

I am getting an error

org.hibernate.hql.ast.QuerySyntaxException: unexpected token: ( near line 1, column 23 [ SELECT count() FROM (SELECT * FROM Url as U where U.pageType = 2 group by U.pageId having count(U.pageId) = 1)]


问:
Delete line from text file if line contains one of few specified strings Python
I presently have code that deletes all lines from a text file that contain one specific string. Here it is:

```<code>import os
with open(r"oldfile") as f, open(r"workfile", "w") as working:
    for line in f:
       if "string1" not in line:
           working.write(line)
os.remove(r"oldfile")
os.rename(r"workfile", r"oldfile")
</code>```

My question is: how can I include other strings? In other words, I want to tell the script that if a line contains "string1" or some other string "string2", then delete that line. I know I could just repeat the code I put above for every such string, but I'm certain there's some shorter and more efficient way to write that.

Many thanks in advance!

答:
Just abstract it out into a function and use that?</p>

```<code>def should_remove_line(line, stop_words):
    return any([word in line for word in stop_words])

stop_words = ["string1", "string2"]
with open(r"oldfile") as f, open(r"workfile", "w") as working:
for line in f:
   if not should_remove_line(line, stop_words):
       working.write(line)
</code>```

Body:
I presently have code that deletes all lines from a text file that contain one specific string. Here it is:

import os
with open(r"oldfile") as f, open(r"workfile", "w") as working:
    for line in f:
       if "string1" not in line:
           working.write(line)
os.remove(r"oldfile")
os.rename(r"workfile", r"oldfile")

My question is: how can I include other strings? In other words, I want to tell the script that if a line contains "string1" or some other string "string2", then delete that line. I know I could just repeat the code I put above for every such string, but I'm certain there's some shorter and more efficient way to write that.

Many thanks in advance!

Body:
Just abstract it out into a function and use that?

def should_remove_line(line, stop_words):
    return any([word in line for word in stop_words])

stop_words = ["string1", "string2"]
with open(r"oldfile") as f, open(r"workfile", "w") as working:
for line in f:
   if not should_remove_line(line, stop_words):
       working.write(line)


问:
d3.js x axis length too short
Here is my script:

```<code><script type="text/javascript">
</code>```

Is there a way to extend the x axis a little bit so it touches the y axis?
I tried playing around with certain values but it would change something in the rest of the chart, which I do not want.

答:
I think you already forced it to translate 20 pixels in X on this part of your code:</p>

```<code>svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(20," + height + ")") /* <-- here! make it 0 , height */
    .call(xAxis);
</code>```

Title: d3.js x axis length too short

Body: Here is my script:

Body:
I think you already forced it to translate 20 pixels in X on this part of your code:

svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(20," + height + ")") /* <-- here! make it 0 , height */
    .call(xAxis);


问:
Matching a result in c#
I have the following string

```<code>background-image: url('https://s3-eu-west-1.amazonaws.com/files.domain.com/uploads/image/file/168726/carousel_IMG_6455.jpg')
</code>```

and I just want to get the image URL.

My code is:

```<code>image = image.Replace(@"'", "\"");
Match match = Regex.Match(image, @"'([^']*)");
</code>```

Match.Success returns nothing, so I can not get the image URL.

Is there something missing? This used to work but not now.

答:
The following pattern achieves your result, without the usage of string.replace.

```<code>var pattern = @"'(?<url>.*)'";
Match match = Regex.Match(image, pattern);
Console.WriteLine($"Math: {match.Groups["url"].Value}");
</code>```

If you want the " surrounding the string, add this:

```<code>var result = $"\"{match.Groups["url"].Value}\""
</code>```

Title: Matching a result in c#

Body:
I have the following string

background-image: url('https://s3-eu-west-1.amazonaws.com/files.domain.com/uploads/image/file/168726/carousel_IMG_6455.jpg')

and I just want to get the image URL.

My code is:

image = image.Replace(@"'", "\"");
Match match = Regex.Match(image, @"'([^']*)");

Match.Success returns nothing, so I can not get the image URL.

Is there something missing? This used to work but not now.

Body:
The following pattern achieves your result, without the usage of string.replace.

var pattern = @"&#39;(?<url>.*)&#39;";
Match match = Regex.Match(image, pattern);
Console.WriteLine($"Math: {match.Groups["url"].Value}");

If you want the " surrounding the string, add this:

var result = $"\"{match.Groups["url"].Value}\""


问:
Python3 tkinter set image size
I have looked everywhere to find a way to set the size of an image. The image is set to a url. I have found other questions on the site but none of them have worked.

```<code>import urllib.request, base64

u = urllib.request.urlopen(currentWeatherIconURL)
raw_data = u.read()
u.close()

b64_data = base64.encodestring(raw_data)
image = PhotoImage(data=b64_data)

label = Label(image=image, bg="White")
label.pack()
</code>```

That is the code that creates the image, how would I set the size of the image

答:
You can add this one line if a simple zoom is acceptable :

```<code>image = PhotoImage(data=b64_data)
image = image.subsample(4, 4) # divide by 4
# image = image.zoom(2, 2)    # zoom x 2
label = Label(image=image, bg="White")
</code>```

Otherwise you should use the PIL lib which provide more accurate tools.

Title: Python3 tkinter set image size

Body:
I have looked everywhere to find a way to set the size of an image. The image is set to a url. I have found other questions on the site but none of them have worked.

import urllib.request, base64

u = urllib.request.urlopen(currentWeatherIconURL)
raw_data = u.read()
u.close()

b64_data = base64.encodestring(raw_data)
image = PhotoImage(data=b64_data)

label = Label(image=image, bg="White")
label.pack()

That is the code that creates the image, how would I set the size of the image

Body:
You can add this one line if a simple zoom is acceptable :

image = PhotoImage(data=b64_data)
image = image.subsample(4, 4) # divide by 4
# image = image.zoom(2, 2)    # zoom x 2
label = Label(image=image, bg="White")

Otherwise you should use the PIL lib which provide more accurate tools.


问:
Magento 2 - 'Choose an option...' text
I have found similar questions to this for Magento 1. However haven't come across the question for Magento 2.

I'm looking to change the default text for configurable products with select boxes.
By default, the drop-down box for configurable products displays 'Choose an option...'.
I'd like to change this to 'Select {attribute default label}'.
Any help would be appreciated.

答:
You can change this in two ways. 1. By translating in csv. 2. By overriding module-configurable-product from vendor folder.

1) Open en_US.csv file from the below path

```<code>vendor\magento\module-configurable-product\i18n\
</code>```

Find the "Choose an Option..." text in first column. Replace your text in the second column and save it. Clean the cache and check it.

or

2) Override the configurable.phtml from below link

```<code>vendor\magento\module-configurable-product\view\frontend\templates\product\view\type\options\
</code>```

Change the below in this file. Find the code:

```<code><option value=""><?php /* @escapeNotVerified */ echo __('Choose an Option...') ?></option>
</code>```

Change from:

```<code><option value=""><?php /* @escapeNotVerified */ echo __('Choose an Option...') ?></option>
</code>```

To:

```<code><option value=""><?php /* @escapeNotVerified */ echo __('Select ').strtolower($block->escapeHtml($_attribute->getProductAttribute()->getStoreLabel())) ?></option>
</code>```

Title: Magento 2 - 'Choose an option...' text

Body:
You can change this in two ways. 1. By translating in csv. 2. By overriding module-configurable-product from vendor folder.

1) Open en_US.csv file from the below path

vendor\magento\module-configurable-product\i18n\

Find the "Choose an Option..." text in first column. Replace your text in the second column and save it. Clean the cache and check it.

or

2) Override the configurable.phtml from below link

vendor\magento\module-configurable-product\view\frontend\templates\product\view\type\options\

Change the below in this file. Find the code:

<option value=""><?php /* @escapeNotVerified */ echo __('Choose an Option...') ?></option>

Change from:

<option value=""><?php /* @escapeNotVerified */ echo __('Choose an Option...') ?></option>

To:

<option value=""><?php /* @escapeNotVerified */ echo __('Select ').strtolower($block->escapeHtml($_attribute->getProductAttribute()->getStoreLabel())) ?></option>


问:
Extract the IP address and port number from a environment variable using windows batch command
I have an environment variable in windows which has a value as follows

```<code>"https://xx.xx.xx.xx:yyyy/xxxx        (login: xxx, password: xxxxx)"
</code>```

My task is to extract the IP address and port number from the environment variable. I was able to do this in a Linux environment. The commands are as follows

```<code>echo "$env_variable" | cut -d '/' -f 3 | cut -d ':' -f 1 - for the IP Address
echo "$env_variable" | cut -d '/' -f 3 | cut -d ':' -f 2 - for the port number
</code>```

Can somebody help me to do same using the windows batch command on windows system?

EDIT

Here xx.xx.xx.xx is the IP Address and yyyy is the port number.

答:
```<code>@echo off
set var="https://xx.xx.xx.xx:yyyy/xxxx        (login: xxx, password: xxxxx)"
for /f "tokens=2,3 delims=/:" %%a in (%var%) do (
   set ip=%%a
   set port=%%b
)
echo %ip%, %port%
</code>```

Body:
I have an environment variable in windows which has a value as follows

"https://xx.xx.xx.xx:yyyy/xxxx        (login: xxx, password: xxxxx)"

My task is to extract the IP address and port number from the environment variable. I was able to do this in a Linux environment. The commands are as follows

echo "$env_variable" | cut -d '/' -f 3 | cut -d ':' -f 1 - for the IP Address
echo "$env_variable" | cut -d '/' -f 3 | cut -d ':' -f 2 - for the port number

Can somebody help me to do same using the windows batch command on windows system?

EDIT

Here xx.xx.xx.xx is the IP Address and yyyy is the port number.


问:
Onscreen keyboard on Android does not send correct keycodes for second language
I have the application with NativeActivity.

I wish to show onscreen keyboard and to listen to keys pressed. Everything works fine when I am typing in english, but when I switch keyboard to russian I receive only zeroes for keycode, metastate etc.

To show keyboard I use this code:

```<code>InputMethodManager imm = (InputMethodManager) activity.getSystemService( Context.INPUT_METHOD_SERVICE );
View view = activity.getWindow( ).getDecorView( );
imm.showSoftInput( view, 0 );
</code>```

I am receiving keyboard events in onInputEvent function in NativeActivity:

```<code>int32_t eventType = AInputEvent_getType( event );
if( eventType == AINPUT_EVENT_TYPE_KEY )
{
    int32_t keyAction = AKeyEvent_getAction( event );
    int32_t keyCode = AKeyEvent_getKeyCode( event );
    int32_t repeatCount = AKeyEvent_getRepeatCount( event );
    int32_t keyFlags = AKeyEvent_getFlags( event );
    int32_t keyScanCode = AKeyEvent_getScanCode( event );
    int32_t keyMetaState = AKeyEvent_getMetaState( event );

    LOGW( "EventType = AINPUT_EVENT_TYPE_KEY, keyAction = %d, keyCode = %d, repeatCount = %d, keyFlags = %d, keyScan = %d, keyMeta = %d", keyAction, keyCode, repeatCount, keyFlags, keyScanCode, keyMetaState );
}
</code>```

And I am getting all event params as zeroes.

How can I solve this?

答:
This is the answer (the key is to override dispatchKeyEvent):
https://stackoverflow.com/a/43871301/674548

Body:
I have the application with NativeActivity.

I wish to show onscreen keyboard and to listen to keys pressed. Everything works fine when I am typing in english, but when I switch keyboard to russian I receive only zeroes for keycode, metastate etc.

To show keyboard I use this code:

InputMethodManager imm = (InputMethodManager) activity.getSystemService( Context.INPUT_METHOD_SERVICE );
View view = activity.getWindow( ).getDecorView( );
imm.showSoftInput( view, 0 );

I am receiving keyboard events in onInputEvent function in NativeActivity:

int32_t eventType = AInputEvent_getType( event );
if( eventType == AINPUT_EVENT_TYPE_KEY )
{
    int32_t keyAction = AKeyEvent_getAction( event );
    int32_t keyCode = AKeyEvent_getKeyCode( event );
    int32_t repeatCount = AKeyEvent_getRepeatCount( event );
    int32_t keyFlags = AKeyEvent_getFlags( event );
    int32_t keyScanCode = AKeyEvent_getScanCode( event );
    int32_t keyMetaState = AKeyEvent_getMetaState( event );

    LOGW( "EventType = AINPUT_EVENT_TYPE_KEY, keyAction = %d, keyCode = %d, repeatCount = %d, keyFlags = %d, keyScan = %d, keyMeta = %d", keyAction, keyCode, repeatCount, keyFlags, keyScanCode, keyMetaState );
}

And I am getting all event params as zeroes.

How can I solve this?


答:
try like

```<code>var toCheck = $("input.reservationkey").val().trim().toUpperCase();
if (invalidkeyreservation.includes(toCheck )) {
 //your code with the condition
}
</code>```

Hope, it helps

Body:
I have this JS code, I need to compare the input value with the array, if the input value match with some value in the array then show the related message, but I can't get the array values and compare them with my input value.

var invalidkeyreservation = ['ABCDEF','GHIJK','LMNOP'];

    if ($("input.reservationkey").val() === invalidkeyreservation) {
        BootstrapDialog.show(return $content;}

    } else{
        window.location.href = "/branches/Cancelaciones/Seleccion.html";
    }

Body:
try like

var toCheck = $("input.reservationkey").val().trim().toUpperCase();
if (invalidkeyreservation.includes(toCheck )) {
 //your code with the condition
}

Hope, it helps


问:
Sinatra + Bundler?
I'm wondering how one can use Bundler with Sinatra. The idea is to use the gems that Bundler downloads inside the .gems folder.</p>

答:
+1 for the guide on the bundler website, but if you have a simple app and use Sinatra's dsl at the top level, then you need to do the following:

in your Gemfile (tell bundler not require sinatra):

```<code>gem 'sinatra', :require => false
</code>```

and in the app's file (explicitly require sinatra):

```<code>require 'rubygems'
require 'bundler'
Bundler.require
require 'sinatra'

get '/' do
  'hello world'
end
</code>```

Title: Sinatra + Bundler?

Body:
+1 for the guide on the bundler website, but if you have a simple app and use Sinatra's dsl at the top level, then you need to do the following:

in your Gemfile (tell bundler not require sinatra):

gem 'sinatra', :require => false

and in the app's file (explicitly require sinatra):

require 'rubygems'
require 'bundler'
Bundler.require
require 'sinatra'

get '/' do
  'hello world'
end


问:
Join images with data frames in r
This is probably a very basic question, but I am not familiar with images in R.

I want a PDF file with two joined imported images and a data frame as the image exemplifies:

This is the code that I am using but is not working.

```<code>library(grid)
library(useful)
library(magick)

# Read external images
imageA <- image_read("imageA.jpg")
imageB <- image_read("imageB.jpg")

# Create data frame
df <- data.frame(1:3)

# Create PDF
pdf("/Mydocument.pdf", width = 10, height = 20)
grid.newpage()

# Create matrix layout
pushViewport(viewport(layout = grid.layout(1, 3)))

# Place elements inside grid
print(imageA, vp = vplayout(1, 1))
print(imageB, vp = vplayout(1, 2))
print(df, vp = vplayout(1, 3))

dev.off()
</code>```

答:
This code achieves what you want:

```<code>require('magick')

# Read external images
frink = image_read("https://jeroen.github.io/images/frink.png")
logo = image_read("https://www.r-project.org/logo/Rlogo.png")
imgs = c(frink, logo)

# concatenate them left-to-right (use 'stack=T' to do it top-to-bottom)
side_by_side = image_append(imgs, stack=F)

# save the pdf
image_write(side_by_side, path = "just_a_test.pdf", format = "pdf")
</code>```

which gives this image:

You may want to scale the images vertically with image_scale(imgs, "x960") - changing 960 with whatever height you want, in pixels.

The vignette of magick explains this and much more: it is an incredibly valuable resource to work on images with R.

A note: if you are using R for the sole purpose of concatenating images, you are doing it wrong: use directly the convert img1.png img2.gif +append new_combined.pdf syntax of the convert commandline tool. It ships with the Image Magick library, the R magick package is a wrapper to it.

But if you have further treatments to do with R, then you can simply convert the image as a raster and continue working with it: as.raster(side_by_side)

Title: Join images with data frames in r

Body:
This is probably a very basic question, but I am not familiar with images in R.

I want a PDF file with two joined imported images and a data frame as the image exemplifies:

This is the code that I am using but is not working.

library(grid)
library(useful)
library(magick)

# Read external images
imageA <- image_read("imageA.jpg")
imageB <- image_read("imageB.jpg")

# Create data frame
df <- data.frame(1:3)

# Create PDF
pdf("/Mydocument.pdf", width = 10, height = 20)
grid.newpage()

# Create matrix layout
pushViewport(viewport(layout = grid.layout(1, 3)))

# Place elements inside grid
print(imageA, vp = vplayout(1, 1))
print(imageB, vp = vplayout(1, 2))
print(df, vp = vplayout(1, 3))

dev.off()

Body:
This code achieves what you want:

require('magick')

# Read external images
frink = image_read("https://jeroen.github.io/images/frink.png")
logo = image_read("https://www.r-project.org/logo/Rlogo.png")
imgs = c(frink, logo)

# concatenate them left-to-right (use 'stack=T' to do it top-to-bottom)
side_by_side = image_append(imgs, stack=F)

# save the pdf
image_write(side_by_side, path = "just_a_test.pdf", format = "pdf")

which gives this image:

You may want to scale the images vertically with image_scale(imgs, "x960") - changing 960 with whatever height you want, in pixels.

The vignette of magick explains this and much more: it is an incredibly valuable resource to work on images with R.

A note: if you are using R for the sole purpose of concatenating images, you are doing it wrong: use directly the convert img1.png img2.gif +append new_combined.pdf syntax of the convert commandline tool. It ships with the Image Magick library, the R magick package is a wrapper to it.

But if you have further treatments to do with R, then you can simply convert the image as a raster and continue working with it: as.raster(side_by_side)


问:
Catching Java SQLExceptions
I do not have a lot of experience in Java and would appreciate if you bring a light on the question.

I have the following piece of code (method) to establish the JDBC connection with a PostgreSQL database :

```<code>public void establishDBConnection() throws SQLException {

    try (Connection connection = DriverManager.getConnection(
                "jdbc:postgresql://" + dbServer + ":" + dbPort + "/" +
                dbDatabase, dbUser, dbPassword))
    catch (SQLException e) {
        logger.error("Connection to Postgres Database Failed: " +
        e.printStackTrace();
    }
 }
</code>```

I expect that the SQLException would be caught by the catch block as soon as the method can't establish connection with the database (server is down). The catch block puts the exception on the console but I see that the same exception is displayed earlier right after the getConnection method execution. Thus, I have 2 quite the same exceptions on the console. See below.

The question is what is the reason for this and how to force the application to display only the exception generated by the catch block.

Logs:

```<code>Jul 07, 2017 9:11:53 PM org.postgresql.Driver connect
SEVERE: Connection error:
**org.postgresql.util.PSQLException: Connection to localhost:5433 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.**
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:265)
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
    at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:194)
    at org.postgresql.Driver.makeConnection(Driver.java:431)
    at org.postgresql.Driver.connect(Driver.java:247)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)
    at excel2db.service.impl.DBConnectionPostgresImpl.establishDBConnection(DBConnectionPostgresImpl.java:38)
    at excel2db.excel2db.main(excel2db.java:86)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at org.postgresql.core.PGStream.<init>(PGStream.java:62)
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:144)
    ... 13 more

21:11:53.465 [main] ERROR e.s.impl.DBConnectionPostgresImpl - **Connection to Postgres Database Failed: Connection to localhost:5433 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.**
</code>```

答:
There is only one exception being printed in your example: the SQLException being caught. What you think is a second exception is only (as the text shows) the cause of the SQLException: Postgres throws a SQLException, which is itself being thrown because there was a network ConnectException when Portgres tried to connect.

This chain of exceptions is very handy when you need to diagnose a failure. It allows going back to the original, low-level source of a problem. Just like, for example, it can be useful to know that you didn't got your mail (NoMailException) because the post office is on strike (OnStrikeException), because the government decided to lower the wages (WagesTooLowException). If you just had the original NoMailException, you wouldn't be able to know the reason why you got no mail, know that it's probably temporary, etc.

In this particular case, you can deduce that it was impossible to connect to the server, and not for example, that the password was incorrect.

Chaining exceptions is simply achieved by calling one of the exception constructors that take another exception as argument (most exceptions do). See https://docs.oracle.com/javase/8/docs/api/java/lang/Exception.html#Exception-java.lang.String-java.lang.Throwable-.

Title: Catching Java SQLExceptions

Body:
I do not have a lot of experience in Java and would appreciate if you bring a light on the question.

I have the following piece of code (method) to establish the JDBC connection with a PostgreSQL database :

public void establishDBConnection() throws SQLException {

    try (Connection connection = DriverManager.getConnection(
                "jdbc:postgresql://" + dbServer + ":" + dbPort + "/" +
                dbDatabase, dbUser, dbPassword))
    catch (SQLException e) {
        logger.error("Connection to Postgres Database Failed: " +
        e.printStackTrace();
    }
 }

I expect that the SQLException would be caught by the catch block as soon as the method can't establish connection with the database (server is down). The catch block puts the exception on the console but I see that the same exception is displayed earlier right after the getConnection method execution. Thus, I have 2 quite the same exceptions on the console. See below.

The question is what is the reason for this and how to force the application to display only the exception generated by the catch block.

Logs:

Jul 07, 2017 9:11:53 PM org.postgresql.Driver connect
SEVERE: Connection error:
**org.postgresql.util.PSQLException: Connection to localhost:5433 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.**
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:265)
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
    at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:194)
    at org.postgresql.Driver.makeConnection(Driver.java:431)
    at org.postgresql.Driver.connect(Driver.java:247)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)
    at excel2db.service.impl.DBConnectionPostgresImpl.establishDBConnection(DBConnectionPostgresImpl.java:38)
    at excel2db.excel2db.main(excel2db.java:86)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at org.postgresql.core.PGStream.<init>(PGStream.java:62)
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:144)
    ... 13 more

21:11:53.465 [main] ERROR e.s.impl.DBConnectionPostgresImpl - **Connection to Postgres Database Failed: Connection to localhost:5433 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.**


答:
You can loop through a list of your blacklisted strings while keeping track of if one of the blacklisted strings was present like this:</p>

```<code>import os
blacklist = ["string1", "string2"]
with open(r"oldfile") as f, open(r"workfile", "w") as working:
    for line in f:
        write = True
        for string in blacklist:
           if string in line:
               write = False
               break
        if write:
               working.write(line)
os.remove(r"oldfile")
os.rename(r"workfile", r"oldfile")
</code>```

Title: Delete line from text file if line contains one of few specified strings Python

Body:
You can loop through a list of your blacklisted strings while keeping track of if one of the blacklisted strings was present like this:

import os
blacklist = ["string1", "string2"]
with open(r"oldfile") as f, open(r"workfile", "w") as working:
    for line in f:
        write = True
        for string in blacklist:
           if string in line:
               write = False
               break
        if write:
               working.write(line)
os.remove(r"oldfile")
os.rename(r"workfile", r"oldfile")


问:
Fix absolutely positioned element to top of viewport on scroll
I'm trying to combine the best of both worlds and accomplish what fixed positioning does when you set top: 0 (appends to top of viewport) while keeping the element absolutely positioned so it scrolls horizontally with its parent element (doing this with fixed is problematic).

The catch is this is a table header so trying to hack my way through this with nested divs set to different positioning methods won't work here.

What I currently tried was keeping the table header with a position of absolute while calculating the distance of the top of the table from the top of the viewport within a scroll event listener:

```<code>const distanceToTop = this.headerElement.getBoundingClientRect().top;
this.stickyHeaderElement.style.top = `${Math.abs(distanceToTop)}px`;
</code>```

this.headerElement is the original table header that you can scroll past (does nothing) while the stickyHeader instance is where the smoke & mirrors occurs.

This current method is doing what I want it to... however, it's incredibly hacky because as you scroll past the original table header and the sticky instance appends, the sticky header shakes due to all the DOM manipulation happening every time the event listener fires.

Since it's recalculating with the logic above.

Question: Can I have an absolutely positioned table header element also append to the top of the viewport like fixed positioning allows? Is there a more efficient solution out there?

答:
Is this what you are going for?

let fixed = document.getElementById('fixed');

window.addEventListener("scroll", e => window.requestAnimationFrame( () => {
  fixed.style.marginLeft = -1 * window.scrollX + "px";
}));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#fixed {
  position: fixed;
  background-color: white;
}

#unfixed {
  color: white;
}</code>```

<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet"/>

        foo
        bar
        baz
        fibble
        meow
        meow
        meow
        meow
        meow
        meow
        meow
        meow
        meow
        meow
        meow
        meow
        meow
        meow
        meow
        meow
        meow
        meow
        meow
        meow
        ffft

        foo
        bar
        baz
        fibble
        meow
        meow
        meow
        meow
        meow
        meow
        meow
        meow
        meow
        meow
        meow
        meow
        meow
        meow
        meow
        meow
        meow
        meow
        meow
        meow
        ffft

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        1
        2
        3
        4
        5

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        1
        2
        3
        4
        5

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        1
        2
        3
        4
        5

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        1
        2
        3
        4
        5

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        1
        2
        3
        4
        5

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        1
        2
        3
        4
        5

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        1
        2
        3
        4
        5

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        1
        2
        3
        4
        5

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        1
        2
        3
        4
        5

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        1
        2
        3
        4
        5

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        1
        2
        3
        4
        5

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        1
        2
        3
        4
        5

```

Body:
I'm trying to combine the best of both worlds and accomplish what fixed positioning does when you set top: 0 (appends to top of viewport) while keeping the element absolutely positioned so it scrolls horizontally with its parent element (doing this with fixed is problematic).

The catch is this is a table header so trying to hack my way through this with nested divs set to different positioning methods won't work here.

What I currently tried was keeping the table header with a position of absolute while calculating the distance of the top of the table from the top of the viewport within a scroll event listener:

const distanceToTop = this.headerElement.getBoundingClientRect().top;
this.stickyHeaderElement.style.top = `${Math.abs(distanceToTop)}px`;

this.headerElement is the original table header that you can scroll past (does nothing) while the stickyHeader instance is where the smoke & mirrors occurs.

This current method is doing what I want it to... however, it's incredibly hacky because as you scroll past the original table header and the sticky instance appends, the sticky header shakes due to all the DOM manipulation happening every time the event listener fires.

Since it's recalculating with the logic above.

Question: Can I have an absolutely positioned table header element also append to the top of the viewport like fixed positioning allows? Is there a more efficient solution out there?

Body:
Is this what you are going for?

let fixed = document.getElementById('fixed');

window.addEventListener("scroll", e => window.requestAnimationFrame( () => {
  fixed.style.marginLeft = -1 * window.scrollX + "px";
}));

#fixed {
  position: fixed;
  background-color: white;
}

#unfixed {
  color: white;
}

<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet"/>
<div>
  <table>
    <thead>
      <tr id="fixed">
        <td>foo</td>
        <td>bar</td>
        <td>baz</td>
        <td>fibble</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>ffft</td>
      </tr>
      <tr id="unfixed">
        <td>foo</td>
        <td>bar</td>
        <td>baz</td>
        <td>fibble</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>meow</td>
        <td>ffft</td>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>10</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>10</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
      </tr>
      <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>10</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>10</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
      </tr>
      <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>10</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>10</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
      </tr>
      <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>10</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>10</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
      </tr>
      <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>10</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>10</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
      </tr>
      <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>10</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>10</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
      </tr>
      <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>10</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>10</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
      </tr>
      <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>10</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>10</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
      </tr>
      <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>10</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>10</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
      </tr>
      <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>10</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>10</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
      </tr>
      <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>10</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>10</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
      </tr>
      <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>10</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>10</td>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
      </tr>
    </tbody>
  </table>


问:
Tkinter Python listbox
I am a new python user. I'm used to programing on matlab.
I've trying to make a simple GUI with Tkinter pack, but I'm having some problems with that. I had already read and searched what i want but I couldn't develop it.

What I'm trying to do is to make a listbox and when I choose one (or more) options the index be returned (and stored) as a variable (array or vector) that could be used to indexing another array.

The best result I got was a listbox where the index were printed, but not stored as a variable (at least it hasn't been shows in the variables list)

I'm using spyder (anaconda).

I tryied a lot of codes and I don't have this anymore.

Sorry for the dumb question. I guess I still thinking in a Matlab way to write

答:
To keep this application simple, your best option is to get the listbox selection when you want to do something with it:

```<code>from tkinter import Tk, Listbox, MULTIPLE, END, Button

def doStuff():
    selected = lb.curselection()
    if selected: # only do stuff if user made a selection
        print(selected)
        for index in selected:
            print(lb.get(index)) # how you get the value of the selection from a listbox

def clear(lb):
    lb.select_clear(0, END) # unselect all

root = Tk()

lb = Listbox(root, selectmode=MULTIPLE) # create Listbox
for n in range(5): lb.insert(END, n) # put nums 0-4 in listbox
lb.pack() # put listbox on window

# notice no parentheses on the function name doStuff
doStuffBtn = Button(root, text='Do Stuff', command=doStuff)
doStuffBtn.pack()

# if you need to add parameters to a function call in the button, use lambda like this
clearBtn = Button(root, text='Clear', command=lambda: clear(lb))
clearBtn.pack()

root.mainloop()
</code>```

I've also added a button to clear the listbox selection because you cannot unselect items by default.

Title: Tkinter Python listbox

Body:
To keep this application simple, your best option is to get the listbox selection when you want to do something with it:

from tkinter import Tk, Listbox, MULTIPLE, END, Button

def doStuff():
    selected = lb.curselection()
    if selected: # only do stuff if user made a selection
        print(selected)
        for index in selected:
            print(lb.get(index)) # how you get the value of the selection from a listbox

def clear(lb):
    lb.select_clear(0, END) # unselect all

root = Tk()

lb = Listbox(root, selectmode=MULTIPLE) # create Listbox
for n in range(5): lb.insert(END, n) # put nums 0-4 in listbox
lb.pack() # put listbox on window

# notice no parentheses on the function name doStuff
doStuffBtn = Button(root, text='Do Stuff', command=doStuff)
doStuffBtn.pack()

# if you need to add parameters to a function call in the button, use lambda like this
clearBtn = Button(root, text='Clear', command=lambda: clear(lb))
clearBtn.pack()

root.mainloop()

I've also added a button to clear the listbox selection because you cannot unselect items by default.


问:
Send Mouse Coordinates Over Tcp Issues
I am working on program in which I want to move cursor of remote pc from my pc but here is a little problem receiving mouse coordinates on remote pc the data receive by tcp server on remote machine due to delay not pushing immediately on some places here is the code and output coordinates which i saved in a file for both client send and server receive.

Client Code to Send Coordinates.

```<code>private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    if (isconnected)
    {
        try
        {
            NetworkStream serverStream = clientSocket.GetStream();
            this.Cursor = new Cursor(Cursor.Current.Handle);
            int pX = Cursor.Position.X;
            int pY = Cursor.Position.Y;
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes($"{pX}#{pY}");
            System.IO.File.AppendAllText(@"F:\DOWNLOAD\client.txt", $"{pX}#{pY}" + Environment.NewLine);
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();
        }
        catch (Exception ex)
        {
        }
    }
}
</code>```

Server Code to Receive Coordinates

```<code>while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
    try
    {
        // Translate data bytes to a ASCII string.
        // Receive mouse coordinates here
        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);

        string Coordinates = data.ToString();
        string X = Coordinates.Substring(0, Coordinates.IndexOf('#'));
        string Y = Coordinates.Substring(Coordinates.IndexOf('#') + 1);
        coordvalue.Invoke((MethodInvoker)(() => coordvalue.Text = ""));

        coordvalue.Invoke((MethodInvoker)(() => coordvalue.Text = $"{X} and {Y}"));
        coordvalue.Invoke((MethodInvoker)(() => coordvalue.Update()));

        // Change coordinates
        System.Windows.Forms.Cursor.Position = new Point(Convert.ToInt32(X), Convert.ToInt32(Y));
        Cursor.Clip = new Rectangle(this.Location, this.Size);
        System.IO.File.AppendAllText(@"F:\DOWNLOAD\server.txt", $"{X} and {Y}" + Environment.NewLine);

    }
    catch (Exception E)
    {
        //  MessageBox.Show(E.ToString());
    }
}
</code>```

Send Coordinates from client

653#492
659#490
669#489
677#486
684#483
693#476
699#470
709#460
715#453
720#444
724#437

Receive Coordinates on Server
653 and 492
659 and 490
669 and 489
677 and 486
684 and 483
693 and 476
699 and 470
709 and 460715#453720#444
724 and 437

Here problem is with709 and 460715#453720#444 because old coordinates were not pushed forward and appending with new which is not suitable for mouse position Please help.

答: while you have a delimiter between x and y, you don't pass a delimiter between messages and instead rely on timing, which as you've discovered isn't reliable. Add a delimiter or an "end of message" marker after the y value and parse for it on the server to ensure you didn't get two messages at the same time.</p>

Title: Send Mouse Coordinates Over Tcp Issues

Body:
I am working on program in which I want to move cursor of remote pc from my pc but here is a little problem receiving mouse coordinates on remote pc the data receive by tcp server on remote machine due to delay not pushing immediately on some places here is the code and output coordinates which i saved in a file for both client send and server receive.

Client Code to Send Coordinates.

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    if (isconnected)
    {
        try
        {
            NetworkStream serverStream = clientSocket.GetStream();
            this.Cursor = new Cursor(Cursor.Current.Handle);
            int pX = Cursor.Position.X;
            int pY = Cursor.Position.Y;
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes($"{pX}#{pY}");
            System.IO.File.AppendAllText(@"F:\DOWNLOAD\client.txt", $"{pX}#{pY}" + Environment.NewLine);
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();
        }
        catch (Exception ex)
        {
        }
    }
}

Server Code to Receive Coordinates

while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
    try
    {
        // Translate data bytes to a ASCII string.
        // Receive mouse coordinates here
        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);

        string Coordinates = data.ToString();
        string X = Coordinates.Substring(0, Coordinates.IndexOf('#'));
        string Y = Coordinates.Substring(Coordinates.IndexOf('#') + 1);
        coordvalue.Invoke((MethodInvoker)(() => coordvalue.Text = ""));

        coordvalue.Invoke((MethodInvoker)(() => coordvalue.Text = $"{X} and {Y}"));
        coordvalue.Invoke((MethodInvoker)(() => coordvalue.Update()));

        // Change coordinates
        System.Windows.Forms.Cursor.Position = new Point(Convert.ToInt32(X), Convert.ToInt32(Y));
        Cursor.Clip = new Rectangle(this.Location, this.Size);
        System.IO.File.AppendAllText(@"F:\DOWNLOAD\server.txt", $"{X} and {Y}" + Environment.NewLine);

    }
    catch (Exception E)
    {
        //  MessageBox.Show(E.ToString());
    }
}

Send Coordinates from client

653#492
659#490
669#489
677#486
684#483
693#476
699#470
709#460
715#453
720#444
724#437

Receive Coordinates on Server
653 and 492
659 and 490
669 and 489
677 and 486
684 and 483
693 and 476
699 and 470
709 and 460715#453720#444
724 and 437

Here problem is with709 and 460715#453720#444 because old coordinates were not pushed forward and appending with new which is not suitable for mouse position Please help.


答:
With your existing markup, you can change the display of your tr's to flex and use justify-content: center;

figure img {
  -webkit-transform: scale(1);
  transform: scale(1);
  -webkit-transition: .3s ease-in-out;
  transition: .3s ease-in-out;
}

figure:hover img {
  -webkit-transform: scale(1.05);
  transform: scale(1.05);
  position: relative;
  height: auto;
  display: block;
  z-index: 999;
  border: 1px solid #ffffff;
  background-color: #ffffff;
}

tr {
  display: flex;
  justify-content: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><center>

  <table border="0">

    <tr>

      <td>
        <figure style="margin: 0;">
          <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
        </figure>
      </td>

      <td>
        <figure style="margin:0">
          <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
        </figure>
      </td>

    </tr>

    <tr>

      <td>
        <figure style="margin: 0;">
          <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
        </figure>
      </td>
      <td>
        <figure style="margin:0">
          <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
        </figure>
      </td>
      <td>
        <figure style="margin: 0">
          <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
        </figure>
      </td>
    </tr>
  </table>
</center></code>```

Title: 2 rows of images (odd numbers of images)

Body:
I want to make 2 rows of images like this (from 5 images):

     Image Image

  Image Image Image

But how can I center the first row?

My result looks like this:

Image Image

  Image Image Image

figure img {
  -webkit-transform: scale(1);
  transform: scale(1);
  -webkit-transition: .3s ease-in-out;
  transition: .3s ease-in-out;
}

figure:hover img {
  -webkit-transform: scale(1.05);
  transform: scale(1.05);
  position: relative;
  height: auto;
  display: block;
  z-index: 999;
  border: 1px solid #ffffff;
  background-color: #ffffff;
}

View on JSFiddle

Body:
With your existing markup, you can change the display of your tr's to flex and use justify-content: center;

figure img {
  -webkit-transform: scale(1);
  transform: scale(1);
  -webkit-transition: .3s ease-in-out;
  transition: .3s ease-in-out;
}

figure:hover img {
  -webkit-transform: scale(1.05);
  transform: scale(1.05);
  position: relative;
  height: auto;
  display: block;
  z-index: 999;
  border: 1px solid #ffffff;
  background-color: #ffffff;
}

tr {
  display: flex;
  justify-content: center;
}

<center>

  <table border="0">

    <tr>

      <td>
        <figure style="margin: 0;">
          <a target="_blank" href="#"><img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100"></a>
        </figure>
      </td>

      <td>
        <figure style="margin:0">
          <a target="_blank" href="#"><img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100"></a>
        </figure>
      </td>

    </tr>

    <tr>

      <td>
        <figure style="margin: 0;">
          <a target="_blank" href="#"><img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100"></a>
        </figure>
      </td>
      <td>
        <figure style="margin:0">
          <a target="_blank" href="#"><img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100"></a>
        </figure>
      </td>
      <td>
        <figure style="margin: 0">
          <a target="_blank" href="#"><img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100"></a>
        </figure>
      </td>
    </tr>
  </table>
</center>


问:
How to make Hibernate @Lock annotation work for Oracle DB?
I stumbled upon a problem with locking row in Oracle DB. The purpose of the lock is to prevent more than one transaction reading data from the DB because this data influences the generation of new data and is changed in terms of a transaction.

In order to make the lock, I've put the @Lock annotation over SpringData find method which retrieves data that participates in the transaction.

```<code>@Lock(LockModeType.PESSIMISTIC_WRITE)
User findUserById(@Param("id") String operatorId);
</code>```

After this code is implemented I get log message

```<code>org.hibernate.loader.Loader - HHH000444: Encountered request for locking however dialect reports that database prefers locking be done in a separate select (follow-on locking); results will be locked after initial query executes
</code>```

Besides, it has no effect and causes

```<code>org.springframework.dao.DataIntegrityViolationException: could not execute batch; SQL [insert into ...]
</code>```

The issue can be solved when rewriting the lock using entity manager

```<code>entityManager.lock(userByIdWithLockOnReadWrite, LockModeType.PESSIMISTIC_WRITE);
</code>```

or

```<code>entityManager.unwrap(Session.class).lock(userByIdWithLockOnReadWrite, LockMode.PESSIMISTIC_WRITE);
</code>```

The issue doesn't appear on MariaDB (MySQL).

Maybe there are some special rules of using the annotation?

答: Is there any option to make a Transaction(TxB) to wait for some time (without throwing Lock Acquisition Exception) for another Transaction(TxA) to release the Lock.  </p>

Body:
I stumbled upon a problem with locking row in Oracle DB. The purpose of the lock is to prevent more than one transaction reading data from the DB because this data influences the generation of new data and is changed in terms of a transaction.

In order to make the lock, I've put the @Lock annotation over SpringData find method which retrieves data that participates in the transaction.

@Lock(LockModeType.PESSIMISTIC_WRITE)
User findUserById(@Param("id") String operatorId);

After this code is implemented I get log message

org.hibernate.loader.Loader - HHH000444: Encountered request for locking however dialect reports that database prefers locking be done in a separate select (follow-on locking); results will be locked after initial query executes

Besides, it has no effect and causes

org.springframework.dao.DataIntegrityViolationException: could not execute batch; SQL [insert into ...]

The issue can be solved when rewriting the lock using entity manager

entityManager.lock(userByIdWithLockOnReadWrite, LockModeType.PESSIMISTIC_WRITE);

or

entityManager.unwrap(Session.class).lock(userByIdWithLockOnReadWrite, LockMode.PESSIMISTIC_WRITE);

The issue doesn't appear on MariaDB (MySQL).

Maybe there are some special rules of using the annotation?


问:
ioArgs in Dojo 1.10, dojox DialogSimple
Got myself a bit of a problem (only occurring in Tomcat 8.5, but I'll need to handle it)...

I'm trying to open up a dojox.widget.DialogSimple, using an href, that has a long url/data string.  Setting the HREF on instantiation causes it to fail as a malformed URL, because it's too long.  So, I want to be able to do it as an xhrPost. Is there a way to set this up using the ioArgs property? I haven't been able to find any documentation giving examples of this.

答:
You are correct.  An over-long URL string for an HTTP "GET" can cause problems: Web Services: maximum length of HTTP GET request?.  In general, the solution is to do a "POST" instead.

Would this solution work for you?

Dojo - how to submit data using a Dialog form

```<code><div dojotype="dijit.Dialog" id="subscription" title="subscription form" execute="alert('Transmitted');">
  <form action="PATH_TO_PHP_PAGE" method="POST">
      <!--input widgets-->
      <!--submit button widgets-->
  </form>
</div>
</code>```

Title: ioArgs in Dojo 1.10, dojox DialogSimple

Body:
You are correct.  An over-long URL string for an HTTP "GET" can cause problems: Web Services: maximum length of HTTP GET request?.  In general, the solution is to do a "POST" instead.

Would this solution work for you?

Dojo - how to submit data using a Dialog form

<div dojotype="dijit.Dialog" id="subscription" title="subscription form" execute="alert('Transmitted');">
  <form action="PATH_TO_PHP_PAGE" method="POST">
      <!--input widgets-->
      <!--submit button widgets-->
  </form>
</div>


问:
How to display slides vertically on mobile devices?
I have the following HTML. Please note that the second section has a view slides which display horizontally on desktops.

```<code><section class="section" data-anchor="firstPage">
    <h1>Section 1 - intro</h1>
</section>

<section class="section periods" data-anchor="secondPage">
    <div class="slide" data-label="secondPage">
        <h1>Section 2 - Intro</h1>
    </div>
    <div class="slide" data-label="1770"><h1>1770</h1></div>
    <div class="slide" data-label="1870"><h1>1870</h1></div>
    <div class="slide" data-label="1970"><h1>1970</h1></div>
</section>
</code>```

On a mobile device (smaller than 767px in width), I would like to show slides vertically without scrolling. How can I do this? Can I do this by configuring fullPage parameters?

答: It seems I have to buy a fullPage extension to get it work.</p>

Body:
I have the following HTML. Please note that the second section has a view slides which display horizontally on desktops.

Section 1 - intro

Section 2 - Intro

1770

1870

1970

On a mobile device (smaller than 767px in width), I would like to show slides vertically without scrolling. How can I do this? Can I do this by configuring fullPage parameters?


问:
Exporting an oracle table dynamically to a flat file
I am trying to build a C++ program using occi libraries that will take a select statement or a table name as an input and turn it into a delimited file. However, looking at the documentation, I can't find a way to export all columns of a query result into a file. Almost all examples I found were along the following lines

```<code>string query = "SELECT col1 FROM table1";

stmt = con->createStatement(query);
res = stmt->executeQuery();

while (res->next())
{
    outfile<<res->getInt(1)<<endl;
}
</code>```

What i want to do is: Do a select * and then export the full row to the file in one go without specifying the type for each column, but I haven't been able to find something that does this.

I know that row-by-row exports are not really efficient for large sets, but I want to make this work before optimizing it.

Does anyone have any ideas around how to do this efficiently?

答:
I found that there is no way to do this without iterating over the metadata object at least once. Since I only need to do this once per query execution I ended up writing the attribute types and column positions to a map and using that map within the result set loop to read data. Here's the code I used:</p>

```<code>    res = stmt->executeQuery();
    vector<oracle::occi::MetaData> meta = res->getColumnListMetaData();
    map<int, int> mapper;

    for (int i=0; i < meta.size(); i++) {
            mapper[i] = meta[i].getInt(oracle::occi::MetaData::ATTR_DATA_TYPE);
    }
</code>```

Body:
I am trying to build a C++ program using occi libraries that will take a select statement or a table name as an input and turn it into a delimited file. However, looking at the documentation, I can't find a way to export all columns of a query result into a file. Almost all examples I found were along the following lines

string query = "SELECT col1 FROM table1";

stmt = con->createStatement(query);
res = stmt->executeQuery();

while (res->next())
{
    outfile<<res->getInt(1)<<endl;
}

What i want to do is: Do a select * and then export the full row to the file in one go without specifying the type for each column, but I haven't been able to find something that does this.

I know that row-by-row exports are not really efficient for large sets, but I want to make this work before optimizing it.

Does anyone have any ideas around how to do this efficiently?

Body:
I found that there is no way to do this without iterating over the metadata object at least once. Since I only need to do this once per query execution I ended up writing the attribute types and column positions to a map and using that map within the result set loop to read data. Here's the code I used:

    res = stmt->executeQuery();
    vector<oracle::occi::MetaData> meta = res->getColumnListMetaData();
    map<int, int> mapper;

    for (int i=0; i < meta.size(); i++) {
            mapper[i] = meta[i].getInt(oracle::occi::MetaData::ATTR_DATA_TYPE);
    }


问:
How does rancher schedule services to specific hosts?
How does rancher decide which host to schedule a certain service to? Does it consider available memory and CPU? Rancher is frequently overloading my hosts and is causing them to crash.  As far can I can tell, services are being scheduled to hosts with the least number of services running on them. Is there a way to change this? I'm using cattle as my environment.</p>

答: The default is by number of containers on the host, as we have no useful information on how much resource each container should be expected to take.  You can define the resource usage of each service and resource limits of each host and then they will be taken into account:  http://rancher.com/docs/rancher/v1.6/en/rancher-services/scheduler/#resource-constraints</p>


问:
PrimeNg Menubar Custom Content not displayed
I've followed the instructions in the docs in:
https://www.primefaces.org/primeng/#/menubar

In my module file i've imported the correct lib:

```<code>import {MenubarModule,MenuItem} from 'primeng/primeng';
</code>```

Then in my template I've defined:

```<code><p-menubar [model]="items">
  <button pButton label="Logout" icon="fa-sign-out"></button>
</p-menubar>
</code>```

However, the button is not rendered in html result. Have I messed somewhere?

Best Regards.

```<code> imports: [
BrowserModule,
HttpModule,
DataTableModule,
SharedModule,
ButtonModule,
MenubarModule,
RouterModule.forRoot([
  {
    path: 'home',
    component: HomeComponent
  },
  {
    path: 'login',
    component: LoginComponent
  }, {
    path: '',
    redirectTo: '/login',
    pathMatch: 'full'
  },
])
</code>```

],

答:
The documentation is refering to the 4.1 RC3 version, was using RC2 at the time:

https://forum.primefaces.org/viewtopic.php?f=35&t=51618

Body:
I've followed the instructions in the docs in:
https://www.primefaces.org/primeng/#/menubar

In my module file i've imported the correct lib:

import {MenubarModule,MenuItem} from 'primeng/primeng';

Then in my template I've defined:

  <button pButton label="Logout" icon="fa-sign-out"></button>

However, the button is not rendered in html result. Have I messed somewhere?

Best Regards.

 imports: [
BrowserModule,
HttpModule,
DataTableModule,
SharedModule,
ButtonModule,
MenubarModule,
RouterModule.forRoot([
  {
    path: 'home',
    component: HomeComponent
  },
  {
    path: 'login',
    component: LoginComponent
  }, {
    path: '',
    redirectTo: '/login',
    pathMatch: 'full'
  },
])

],


问:
Value cannot be null. Parameter name: userContext in Visual Studio 2017
I am facing a strange issue that, getting a message as "Value can not be null. Parameter name is userContext" while clicking on Extensions and updates under tools menu.

Please do let me know what is the workaround for this issue. Thank you.

答:
I had the exact same issue.  I uninstalled KB4022714 from Start > Windows Update >  Advanced Options > View your Update History. The problem went away, but came back after the next Windows Update.

I had to update Windows 10 to build 14393 to actually fix the problem for good.