问:
Extra height pixels in simple div with img
I am having difficulty determining where the extra pixels of height are coming from for the div in this simple layout. My expectation would be that the image would determine the height of the div but instead it appears to be a few pixels larger. The pixels I am trying to get rid of are shown in blue. Any ideas?

Oh, I have added a button to explicitly set the height of the image parent div properly using javascript - my question is really where is it getting that extra height from in the first place, or how can I do this without javascript?

function change() {
  var image = document.getElementById('image1ID');
  var width = image.naturalWidth;
  var height = image.naturalHeight;
  var imageDIV = document.getElementById('image1DIV');

  imageDIV.style.height = (100 * height / width) + "px";

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="image1DIV" style="background-color:#00f;">
  <img id="image1ID" style="width:100px;" src="http://www.imageno.com/thumbs/20170330/73dlz3sr4pfy.jpg">
</div>

<button onclick="change()">change height of parent div</button></code>```

答:
the img tag height is not explicitly set to occupy 100% height of its parent. What you are seeing are parts of background color styled on the parent

```<code>.flexrow img{
      height:100%;
    }
</code>```

Snippet below

.flexrow {
  display: flex;
  flex-direction: row;
  flex-wrap: none;
}

.flexcolumn {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.textblock {
  width: 170px;
}

.flexrow img {
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flexcolumn">

  <div class="flexrow">
    <div style="background-color:#00f;">
      <img style="width:100px;" src="http://www.imageno.com/thumbs/20170330/73dlz3sr4pfy.jpg">
    </div>
    <div class="flexcolumn textblock" style="background-color:#eee;">
      <div style="background-color:#e0e;">Title is here</div>
      <div style="background-color:#0ee;">Description is here</div>
    </div>
  </div>

  <div class="flexrow">
    <div style="background-color:#0f0;">
      <img style="width:100px;" src="http://www.imageno.com/thumbs/20170330/73dlz3sr4pfy.jpg">
    </div>
    <div class="flexcolumn textblock" style="background-color:#ee0;">
      <div style="background-color:#e0e;">Title is here</div>
      <div style="background-color:#0ee;">Description is here</div>
    </div>
  </div>

</div></code>```

Body:
I am having difficulty determining where the extra pixels of height are coming from for the div in this simple layout. My expectation would be that the image would determine the height of the div but instead it appears to be a few pixels larger. The pixels I am trying to get rid of are shown in blue. Any ideas?

Oh, I have added a button to explicitly set the height of the image parent div properly using javascript - my question is really where is it getting that extra height from in the first place, or how can I do this without javascript?

function change() {
  var image = document.getElementById('image1ID');
  var width = image.naturalWidth;
  var height = image.naturalHeight;
  var imageDIV = document.getElementById('image1DIV');

  imageDIV.style.height = (100 * height / width) + "px";

}

<button onclick="change()">change height of parent div</button>

Body:
the img tag height is not explicitly set to occupy 100% height of its parent. What you are seeing are parts of background color styled on the parent

.flexrow img{
      height:100%;
    }

Snippet below

.flexrow {
  display: flex;
  flex-direction: row;
  flex-wrap: none;
}

.flexcolumn {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.textblock {
  width: 170px;
}

.flexrow img {
  height: 100%;
}

<div class="flexcolumn">

  <div class="flexrow">
    <div style="background-color:#00f;">
      <img style="width:100px;" src="http://www.imageno.com/thumbs/20170330/73dlz3sr4pfy.jpg">
    </div>
    <div class="flexcolumn textblock" style="background-color:#eee;">
      <div style="background-color:#e0e;">Title is here</div>
      <div style="background-color:#0ee;">Description is here</div>
    </div>
  </div>

  <div class="flexrow">
    <div style="background-color:#0f0;">
      <img style="width:100px;" src="http://www.imageno.com/thumbs/20170330/73dlz3sr4pfy.jpg">
    </div>
    <div class="flexcolumn textblock" style="background-color:#ee0;">
      <div style="background-color:#e0e;">Title is here</div>
      <div style="background-color:#0ee;">Description is here</div>
    </div>
  </div>

</div>


来源: stackexchange

问:
Spliting on every character except for preserved substring
Given the string

```<code>word = "These"
</code>```

that contains the tuple

```<code>pair = ("h", "e")
</code>```

the aim is to replace the word such that it splits on all character except for the pair tuple, i.e. output:

```<code>('T', 'he', 's', 'e')
</code>```

I've tried:

```<code>word = 'These'
pair = ('h', 'e')
first, second = pair
pair_str = ''.join(pair)
pair_str = pair_str.replace('\\','\\\\')
pattern = re.compile(r'(?<!\S)' + re.escape(first + ' ' + second) + r'(?!\S)')
new_word = ' '.join(word)
new_word = pattern.sub(pair_str, new_word)
result = tuple(new_word.split())
</code>```

Note that sometimes the pair tuple can contain slashes, backslashes or any other escape characters, thus the replace and escape in the above regex.

Is there a simpler way to achieve the same string replacement?

EDITED

Specifics from comments:

And is there a distinction between when both characters in the pair are unique and when they aren't?

Nope, they should be treated the same way.

答:
You can do it without using regular expressions:</p>

```<code>import functools

word = 'These here when she'
pair = ('h', 'e')
digram = ''.join(pair)
parts = map(list, word.split(digram))
lex = lambda pre,post: post if pre is None else pre+[digram]+post

print(functools.reduce(lex, parts, None))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Given the string

word = "These"

that contains the tuple

pair = ("h", "e")

the aim is to replace the word such that it splits on all character except for the pair tuple, i.e. output:

('T', 'he', 's', 'e')

I've tried:

word = 'These'
pair = ('h', 'e')
first, second = pair
pair_str = ''.join(pair)
pair_str = pair_str.replace('\\','\\\\')
pattern = re.compile(r'(?<!\S)' + re.escape(first + ' ' + second) + r'(?!\S)')
new_word = ' '.join(word)
new_word = pattern.sub(pair_str, new_word)
result = tuple(new_word.split())

Note that sometimes the pair tuple can contain slashes, backslashes or any other escape characters, thus the replace and escape in the above regex.

Is there a simpler way to achieve the same string replacement?

EDITED

Specifics from comments:

And is there a distinction between when both characters in the pair are unique and when they aren't?

Nope, they should be treated the same way.

Body:
You can do it without using regular expressions:

import functools

word = 'These here when she'
pair = ('h', 'e')
digram = ''.join(pair)
parts = map(list, word.split(digram))
lex = lambda pre,post: post if pre is None else pre+[digram]+post

print(functools.reduce(lex, parts, None))


问:
MySQL regular expression to select the last integer in the string
I have a MySQL database table that contains column run that is an integer and another column filename that is a varchar with typical values like RUN0001.FTS or 3DS0231.FTS or 3RUN0010.FTS

I need to check the values in the run and filename columns. The prescription is I extract the last integer (without leading zeroes) before the dot character (.) in the filename column, and compare it to the value of the run column. How do I write a select statement to do this comparison to return the rows that will not have the matching integers?

For example, a regular expression I am trying to build would extract 1 from RUN0001.FTS, or 231 from 3DS0231.FTS, or 10 from 3RUN0010.FTS and then compare it to the value in the run column, and return the primary key if the two don't match.

In Python I would manipulate the variable filename = '3RUN0010.FTS' like so:

```<code>import re
filename = '3RUN0010.FTS'
fileRunNumber = re.findall('\d+', filename)
runNumber = int(fileRunNumber[-1])
print "The integer I want is", runNumber
</code>```

How do I do this in as a MySQL statement?

Thanks,
Aina.

答:
You can try the following query:

```<code>SELECT CAST(SUBSTRING(col, INSTR(col, '.') - 4, 4) AS UNSIGNED) AS theNumber
FROM yourTable
</code>```

Data:

```<code>CREATE TABLE yourTable (col varchar(55));
INSERT INTO yourTable (col)
VALUES
    ('RUN0001.FTS'),
    ('3DS0231.FTS'),
    ('3RUN0010.FTS');
</code>```

Output:

Demo here:

Rextester

Body:
I have a MySQL database table that contains column run that is an integer and another column filename that is a varchar with typical values like RUN0001.FTS or 3DS0231.FTS or 3RUN0010.FTS

I need to check the values in the run and filename columns. The prescription is I extract the last integer (without leading zeroes) before the dot character (.) in the filename column, and compare it to the value of the run column. How do I write a select statement to do this comparison to return the rows that will not have the matching integers?

For example, a regular expression I am trying to build would extract 1 from RUN0001.FTS, or 231 from 3DS0231.FTS, or 10 from 3RUN0010.FTS and then compare it to the value in the run column, and return the primary key if the two don't match.

In Python I would manipulate the variable filename = '3RUN0010.FTS' like so:

import re
filename = '3RUN0010.FTS'
fileRunNumber = re.findall('\d+', filename)
runNumber = int(fileRunNumber[-1])
print "The integer I want is", runNumber

How do I do this in as a MySQL statement?

Thanks,
Aina.

Body:
You can try the following query:

SELECT CAST(SUBSTRING(col, INSTR(col, '.') - 4, 4) AS UNSIGNED) AS theNumber
FROM yourTable

Data:

CREATE TABLE yourTable (col varchar(55));
INSERT INTO yourTable (col)
VALUES
    ('RUN0001.FTS'),
    ('3DS0231.FTS'),
    ('3RUN0010.FTS');

Output:

Demo here:

Rextester


问:
Firewall (iptables) settings after changing Azure Ubuntu-based VM size
I use Azure virtual machines, and recently scaled up the VM size to DS14. My question is: during this scale up, the VM was restarted. Would my firewall set up in iptables from the previous machine have carried over to the new machine? I unfortunately didn't keep a backup of that, so need to be sure either way. Thanks!

答:
Would my firewall set up in iptables from the previous machine have
  carried over to the new machine?

Resize your VM to a larger or smaller size will not change your VM's configuration.  Resize VM only changes the size of your VM based on the needs for CPU, Network or disk performance. More information please refer to this link.

So, the iptables will carry over to the new machine.

Notes: You should save your iptables rule to /etc/iptables.rules. If you don't save them, when you restart your VM, the rules will lose. However, it is no related with resizing VM size.


问:
Azure CLI 2: how to provide parameters in az group deployment create command?
I am using Azure CLI 2.0 on a windows machine and I am trying to create a Docker VM using this Microsoft documentation:

```<code>az group deployment create --resource-group myResourceGroup \
  --parameters '{"newStorageAccountName": {"value": "mystorageaccount"},
    "adminUsername": {"value": "azureuser"},
    "adminPassword": {"value": "P@ssw0rd!"},
    "dnsNameForPublicIP": {"value": "mypublicdns"}}' \
--template-uri https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/docker-simple-on-ubuntu/azuredeploy.json
</code>```

Putting everything in one line results in an "unrecognized arguments" error. Replacing the parameter single quotes by double quotes results in an "Expecting property name enclosed in double quotes" error and removing the parameters option gives an expected "Deployment template validation failed" error. What is the correct way to provide the parameter value?

答:
Please try this script:

```<code>az group deployment create --resource-group jason --parameters "{\"newStorageAccountName\": {\"value\": \"jasondisks321\"},\"adminUsername\": {\"value\": \"jason\"},\"adminPassword\": {\"value\": \"122130869@qq\"},\"dnsNameForPublicIP\": {\"value\": \"jasontest321\"}}" --template-uri https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/docker-simple-on-ubuntu/azuredeploy.json
</code>```

It works for me.

In cli 2.0, we can use --help to find the command help:

```<code>C:\windows\system32>az group deployment create --help

Examples
    Create a deployment from a remote template file.
        az group deployment create -g MyResourceGroup --template-uri
        https://myresource/azuredeploy.json --parameters @myparameters.json

    Create a deployment from a local template file and use parameter values in a string.
        az group deployment create -g MyResourceGroup --template-file azuredeploy.json --parameters
        "{\"location\": {\"value\": \"westus\"}}"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using Azure CLI 2.0 on a windows machine and I am trying to create a Docker VM using this Microsoft documentation:

az group deployment create --resource-group myResourceGroup \
  --parameters '{"newStorageAccountName": {"value": "mystorageaccount"},
    "adminUsername": {"value": "azureuser"},
    "adminPassword": {"value": "P@ssw0rd!"},
    "dnsNameForPublicIP": {"value": "mypublicdns"}}' \
--template-uri https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/docker-simple-on-ubuntu/azuredeploy.json

Putting everything in one line results in an "unrecognized arguments" error. Replacing the parameter single quotes by double quotes results in an "Expecting property name enclosed in double quotes" error and removing the parameters option gives an expected "Deployment template validation failed" error. What is the correct way to provide the parameter value?

Body:
Please try this script:

az group deployment create --resource-group jason --parameters "{\"newStorageAccountName\": {\"value\": \"jasondisks321\"},\"adminUsername\": {\"value\": \"jason\"},\"adminPassword\": {\"value\": \"122130869@qq\"},\"dnsNameForPublicIP\": {\"value\": \"jasontest321\"}}" --template-uri https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/docker-simple-on-ubuntu/azuredeploy.json

It works for me.

In cli 2.0, we can use --help to find the command help:

C:\windows\system32>az group deployment create --help

Examples
    Create a deployment from a remote template file.
        az group deployment create -g MyResourceGroup --template-uri
        https://myresource/azuredeploy.json --parameters @myparameters.json

    Create a deployment from a local template file and use parameter values in a string.
        az group deployment create -g MyResourceGroup --template-file azuredeploy.json --parameters
        "{\"location\": {\"value\": \"westus\"}}"


问:
Increment and Decrement through array using modulus operator or Js
I was able to figure out the how to increment through my array reading through another question. Now I cant seem to figure out how to deincrement since my value is being set back to 0. I am trying to avoid a loop.

The order I am looking to acheive is:

Increment ---- "/", "/about", "/list" <-- list is the end. Decrement is just rewinding. Decrement is just going a 1 step back each time.

```<code>let i = 0;
let stuff =["/", "about","list"];

next() {
    this.props.dispatch(increaseCounter())
    i = (i+1)%stuff.length;
  }
  prev() {
    this.props.dispatch(decreaseCounter())
    i = (i-1)%stuff.length; <------This gets wonky once I reach the end of my array.
  }
</code>```

答:
The problem with % is that it is a remainder operator with truncated division, not a modulo one with floored division. When the divisor (i-1) becomes negative, so does the result. You can use

```<code>if (--i < 0) i = stuff.length - 1;
</code>```

or

```<code>i = (i + stuff.length - 1) % stuff.length;
</code>```

instead (which only work for input values of i in the expected range, though)

Body:
I was able to figure out the how to increment through my array reading through another question. Now I cant seem to figure out how to deincrement since my value is being set back to 0. I am trying to avoid a loop.

The order I am looking to acheive is:

Increment ---- "/", "/about", "/list" <-- list is the end. Decrement is just rewinding. Decrement is just going a 1 step back each time.

let i = 0;
let stuff =["/", "about","list"];

next() {
    this.props.dispatch(increaseCounter())
    i = (i+1)%stuff.length;
  }
  prev() {
    this.props.dispatch(decreaseCounter())
    i = (i-1)%stuff.length; <------This gets wonky once I reach the end of my array.
  }

Body:
The problem with % is that it is a remainder operator with truncated division, not a modulo one with floored division. When the divisor (i-1) becomes negative, so does the result. You can use

if (--i < 0) i = stuff.length - 1;

or

i = (i + stuff.length - 1) % stuff.length;

instead (which only work for input values of i in the expected range, though)


问:
Pandas Dataframe Groupby Apply Lambda Function With Multiple Column Returns
I couldn't find anything on SO on this. What I'm trying to do is generate 4 new columns on my existing dataframe, by applying a separate function with 4 specific columns as inputs and return 4 output columns that are not the 4 initial columns. However, the function requires me to slice the dataframe by conditions before usage. I have been using for loops and appending, but it is extremely slow. I was hoping that there was a way to do a MapReduce-esque operation, where it would take my DataFrame, do a groupby and apply a function I separately wrote.

The function has multiple outputs, so just imagine a function like this:

```<code>    def func(a,b,c,d):
        return f(a),g(b),h(c),i(d)
</code>```

where f,g,h,i are different functions performed on the inputs. I am trying to do something like:

```<code>    import pandas as pd

    df = pd.DataFrame({'a': range(10),
                       'b': range(10),
                       'c': range(10),
                       'd':range(10},
                       'e': [0,0,0,0,0,1,1,1,1,1])

    df.groupby('e').apply(lambda df['x1'],df['x2'],df['x3'],df['x4'] =
                          func(df['a'],df['b'],df['c'],df['d']))
</code>```

Wondering if this is possible. If there are other functions out there in the library/ more efficient ways to go about this, please do advise. Thanks.

EDIT: Here's a sample output

```<code>   a  b  c  d  e  f  g  h  i
   --------------------------
   0  0  0  0  0  f1 g1 h1 i1
   1  1  1  1  1  f2 g2 h2 i2
    ... and so on
</code>```

The reason why I'd like this orientation of operations is due to the function's operations being reliant on structures within the data (hence the groupby) before performing the function. Previously, I obtained the unique values and iterated over them while slicing the dataframe up, before appending it to a new dataframe. Runs in quadratic time.

答:
You could do something like this:</p>

```<code>def f(data):
    data['a2']=data['a']*2 #or whatever function/calculation you want
    data['b2']=data['b']*3 #etc etc
    #e.g. data['g']=g(data['b'])
    return data

df.groupby('e').apply(f)
</code>```

Body:
I couldn't find anything on SO on this. What I'm trying to do is generate 4 new columns on my existing dataframe, by applying a separate function with 4 specific columns as inputs and return 4 output columns that are not the 4 initial columns. However, the function requires me to slice the dataframe by conditions before usage. I have been using for loops and appending, but it is extremely slow. I was hoping that there was a way to do a MapReduce-esque operation, where it would take my DataFrame, do a groupby and apply a function I separately wrote.

The function has multiple outputs, so just imagine a function like this:

    def func(a,b,c,d):
        return f(a),g(b),h(c),i(d)

where f,g,h,i are different functions performed on the inputs. I am trying to do something like:

    import pandas as pd

    df = pd.DataFrame({'a': range(10),
                       'b': range(10),
                       'c': range(10),
                       'd':range(10},
                       'e': [0,0,0,0,0,1,1,1,1,1])

    df.groupby('e').apply(lambda df['x1'],df['x2'],df['x3'],df['x4'] =
                          func(df['a'],df['b'],df['c'],df['d']))

Wondering if this is possible. If there are other functions out there in the library/ more efficient ways to go about this, please do advise. Thanks.

EDIT: Here's a sample output

   a  b  c  d  e  f  g  h  i
   --------------------------
   0  0  0  0  0  f1 g1 h1 i1
   1  1  1  1  1  f2 g2 h2 i2
    ... and so on

The reason why I'd like this orientation of operations is due to the function's operations being reliant on structures within the data (hence the groupby) before performing the function. Previously, I obtained the unique values and iterated over them while slicing the dataframe up, before appending it to a new dataframe. Runs in quadratic time.

Body:
You could do something like this:

def f(data):
    data['a2']=data['a']*2 #or whatever function/calculation you want
    data['b2']=data['b']*3 #etc etc
    #e.g. data['g']=g(data['b'])
    return data

df.groupby('e').apply(f)


问:
app.config file is not giving connection properly
I am on a desktop application and retrieving the list of databases on a local server
by this function

```<code>/// <summary>
/// This function populates the databases list in the drop down after the user is connected.
/// </summary>
public void BindDBDropDown()

        {

        //Create the connection object
        SqlConnection sConnection = new SqlConnection("Server=192.168.10.3;DataBase=GoalPlanNew;User Id=gp;Password=gp");

        //To Open the connection.
        sConnection.Open();

        //Query to select the list of databases.
        string selectDatabaseNames = @"SELECT
                                            NAME
                                        FROM
                                            MASTER..SYSDATABASES";

        //Create the command object
        SqlCommand sCommand = new SqlCommand(selectDatabaseNames, sConnection);

        try
            {
            //Create the data set
            DataSet sDataset = new DataSet("master..sysdatabases");

            //Create the dataadapter object
            SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectDatabaseNames, sConnection);
            sDataAdapter.TableMappings.Add("Table", "master..sysdatabases");

            //Fill the dataset
            sDataAdapter.Fill(sDataset);

            //Bind the database names in combobox
            DataViewManager dsv = sDataset.DefaultViewManager;

            //Provides the master mapping between the sourcr table and system.data.datatable
            cmbDatabases.DataSource = sDataset.Tables["master..sysdatabases"];
            cmbDatabases.DisplayMember = "NAME";
            cmbDatabases.ValueMember = ("NAME");
            }
        catch(Exception ex)
            {
            //All the exceptions are handled and written in the EventLog.
            EventLog logException = new EventLog("Application");
            logException.Source = "MFDBAnalyser";
            logException.WriteEntry(ex.Message);
            }
        finally
            {
            //If connection is not closed then close the connection
            if(sConnection.State != ConnectionState.Closed)
                {
                sConnection.Close();
                }
            }
        }
</code>```

This function is working fine if I am letting it to be hardcoded but when I tried to use the connection string declared in the app.config file as

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="ConnectionString" value="Server=192.168.10.3;DataBase=GoalPlanNew;User Id=gp;Password=gp"/>
  </appSettings>
</configuration>
</code>```

Then it is not working...

What I need to do??

答:
r  u trying soemthing like below

```<code>if (!String.IsNullOrEmpty(ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString))
            {

            }
</code>```

if yes then there should not be any problem

ContentLicense: CC BY-SA 2.5

Body:
I am on a desktop application and retrieving the list of databases on a local server
by this function

///
/// This function populates the databases list in the drop down after the user is connected.
///
public void BindDBDropDown()

        {

        //Create the connection object
        SqlConnection sConnection = new SqlConnection("Server=192.168.10.3;DataBase=GoalPlanNew;User Id=gp;Password=gp");

        //To Open the connection.
        sConnection.Open();

        //Query to select the list of databases.
        string selectDatabaseNames = @"SELECT
                                            NAME
                                        FROM
                                            MASTER..SYSDATABASES";

        //Create the command object
        SqlCommand sCommand = new SqlCommand(selectDatabaseNames, sConnection);

        try
            {
            //Create the data set
            DataSet sDataset = new DataSet("master..sysdatabases");

            //Create the dataadapter object
            SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectDatabaseNames, sConnection);
            sDataAdapter.TableMappings.Add("Table", "master..sysdatabases");

            //Fill the dataset
            sDataAdapter.Fill(sDataset);

            //Bind the database names in combobox
            DataViewManager dsv = sDataset.DefaultViewManager;

            //Provides the master mapping between the sourcr table and system.data.datatable
            cmbDatabases.DataSource = sDataset.Tables["master..sysdatabases"];
            cmbDatabases.DisplayMember = "NAME";
            cmbDatabases.ValueMember = ("NAME");
            }
        catch(Exception ex)
            {
            //All the exceptions are handled and written in the EventLog.
            EventLog logException = new EventLog("Application");
            logException.Source = "MFDBAnalyser";
            logException.WriteEntry(ex.Message);
            }
        finally
            {
            //If connection is not closed then close the connection
            if(sConnection.State != ConnectionState.Closed)
                {
                sConnection.Close();
                }
            }
        }

This function is working fine if I am letting it to be hardcoded but when I tried to use the connection string declared in the app.config file as

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="ConnectionString" value="Server=192.168.10.3;DataBase=GoalPlanNew;User Id=gp;Password=gp"/>
  </appSettings>
</configuration>

Then it is not working...

What I need to do??

Body:
r  u trying soemthing like below

if (!String.IsNullOrEmpty(ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString))
            {

            }

if yes then there should not be any problem


问:
ASP.Net MVC return Json as IActionResult modifies the object key names
I have a class BasketItem:

```<code>public class BasketItem
{
    public long FoodId;
    public int Count;
}
</code>```

I have a AddToBasket controller which adds items to basket and then returns the json value of BasketItem[]:

I'm using return Json(items); which items is of type BasketItem[].

The returned json is like:

```<code>[{"foodId":6,"count":1},{"foodId":5,"count":1},{"foodId":4,"count":1}]
</code>```

while it Should be like:

```<code>[{"FoodId":6,"Count":1},{"FoodId":5,"Count":1},{"FoodId":4,"Count":1}]
</code>```

How to prevent return Json from renaming the key names?

答:
I solved the problem by using the overload of the Json(object, JsonSerializerSettings):

```<code>   var serializerSettings = new JsonSerializerSettings
        {
            ContractResolver = new DefaultContractResolver(),
        };
        return Json(items, serializerSettings);
</code>```

Body:
I have a class BasketItem:

public class BasketItem
{
    public long FoodId;
    public int Count;
}

I have a AddToBasket controller which adds items to basket and then returns the json value of BasketItem[]:

I'm using return Json(items); which items is of type BasketItem[].

The returned json is like:

[{"foodId":6,"count":1},{"foodId":5,"count":1},{"foodId":4,"count":1}]

while it Should be like:

[{"FoodId":6,"Count":1},{"FoodId":5,"Count":1},{"FoodId":4,"Count":1}]

How to prevent return Json from renaming the key names?

Body:
I solved the problem by using the overload of the Json(object, JsonSerializerSettings):

   var serializerSettings = new JsonSerializerSettings
        {
            ContractResolver = new DefaultContractResolver(),
        };
        return Json(items, serializerSettings);


问:
‘Cordova/CDV.h’ file not found in Xcode 8.2.1
I have one hybrid Cordova project, which is running fine Xcode 5.1.1, but when I am trying to Archive the project in Xcode 8.2.1 with ‘Generic iOS Device’ I am getting the error ‘Cordova/CDV.h’ is not found.

I read many articles about this problem, but none could solve my problem. Most answers are telling to follow the below steps:

"Add this line to your Build Settings -> Header Search Paths:
$(OBJROOT)/UninstalledProducts/$(PLATFORM_NAME)/include
"

I have did this but problem not solved, getting another error ‘ld: library not found for -lcrt1.3.1.o
clang: error: linker command failed with exit code 1 (use -v to see invocation)’

Also I have changed the bitcode YES to NO in target Build Settings, but no fruitful result.

Project cordova version 3.4.0 where installed cordova version in machine 6.4.0

Has anybody experience with this kind of problem?
Please, can anyone help? I've been working on this for days.

答:
I got it work by following below steps

In your Xcode project settings select TARGETS

Within TARGETS select the Build Settings tab

In the sub-options under the Build Settings tab be sure to select All

Scroll down to the Search Paths section

Locate Header Search Paths

Add the following configuration to the Release option (as a new value on its own line): $(OBJROOT)/UninstalledProducts/$(PLATFORM_NAME)/include

Clean the project: Command + Shift + K

Restart Xcode


问:
FloatingActionButton with BottomNavigationView
I cant position my FAB. It should be bottom right, but on top of the BottonNavigationView.

1) Can i achieve this without RelativeLayout inside coordinateLayout?

2) Show me how

3) Should i use FrameLayout as a container for fragments?

```<code><android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay">

    </android.support.v7.widget.Toolbar>

</android.support.design.widget.AppBarLayout>

<FrameLayout
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

</FrameLayout>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab_electricity"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="@dimen/fab_margin"
    app:layout_anchorGravity="bottom|right|end"
    app:srcCompat="@drawable/ic_add_electro" />

<android.support.design.widget.BottomNavigationView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_gravity="bottom">

</android.support.design.widget.BottomNavigationView>

</android.support.design.widget.CoordinatorLayout>
</code>```

答:
A quick search to FloatingActionButton.Behavior tells us the following thing.

@Override
public void onAttachedToLayoutParams(@NonNull CoordinatorLayout.LayoutParams lp) {
    if (lp.dodgeInsetEdges == Gravity.NO_GRAVITY) {
        // If the developer hasn't set dodgeInsetEdges, lets set it to BOTTOM so that
        // we dodge any Snackbars
        lp.dodgeInsetEdges = Gravity.BOTTOM;
    }
}
```

<p>Since <code>BottomNavigationView</code> also resides at the bottom of the layout. Add following element to your <code>BottomNavigationView</code> and <code>CoordinatorLayout</code> will handle the inset and dodging for you automatically.</p>

<pre class="lang-xml prettyprint-override"><code>app:layout_insetEdge="bottom"
</code>```

Body:
I cant position my FAB. It should be bottom right, but on top of the BottonNavigationView.

1) Can i achieve this without RelativeLayout inside coordinateLayout?

2) Show me how

3) Should i use FrameLayout as a container for fragments?

<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay">

    </android.support.v7.widget.Toolbar>

</android.support.design.widget.AppBarLayout>

<FrameLayout
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

</FrameLayout>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab_electricity"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="@dimen/fab_margin"
    app:layout_anchorGravity="bottom|right|end"
    app:srcCompat="@drawable/ic_add_electro" />

<android.support.design.widget.BottomNavigationView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_gravity="bottom">

</android.support.design.widget.BottomNavigationView>

</android.support.design.widget.CoordinatorLayout>

Body:
A quick search to FloatingActionButton.Behavior tells us the following thing.

@Override
public void onAttachedToLayoutParams(@NonNull CoordinatorLayout.LayoutParams lp) {
    if (lp.dodgeInsetEdges == Gravity.NO_GRAVITY) {
        // If the developer hasn't set dodgeInsetEdges, lets set it to BOTTOM so that
        // we dodge any Snackbars
        lp.dodgeInsetEdges = Gravity.BOTTOM;
    }
}

Since BottomNavigationView also resides at the bottom of the layout. Add following element to your BottomNavigationView and CoordinatorLayout will handle the inset and dodging for you automatically.

app:layout_insetEdge="bottom"


问:
Which method is better when I want to search the min and max result in oracle?
I have a table called student,I want to get the max and min score,so I write the sql in first way:

```<code>select max(score),min(score) from student;
</code>```

and the second way:

```<code>select max(score) from student;
select min(score) from student;
</code>```

I search from the internet and they say that the second way is better because the oracle can not scan the index in the same time.But the second way can not ensure the same datasoure because it do twice searching.How to fix it?

答:
Combine the two queries from the second method into a single query:

```<code>select
    (select max(score) from student),
    (select min(score) from student)
from dual;
</code>```

That solution uses two fast index scans.  It should run faster than option 1 or 2 and will also be consistent.

Why doesn't the simplest solution work?

It certainly seems like Oracle should have a way to run this optimally:

```<code>select max(score),min(score) from student;
</code>```

I've seen this query before, seen people discuss it, and Oracle even has special access paths for getting the max and min: INDEX FULL SCAN (MIN/MAX).  But it just can't seem to do both the min and the max at the same time and I'm not sure why.

It's hard to prove Oracle can't do something.  Maybe someone will come in later and prove me wrong.  My answer is based on this article by Richard Foote, who is perhaps the world's top Oracle index expert.  And I've included some simple tests below.  The sample schema looks like an ideal case for Oracle to automatically use the INDEX FULL SCAN (MIN/MAX) twice in one query, but it doesn't.  My results were generated using the latest version, 12.2.

Sample Schema

```<code>--Create STUDENT table with 1.6 million rows, an index on score, and fresh statistics.
--drop table student;
create table student(name varchar2(100), score number not null);
insert into student select lpad('A', 20, 'A'), level from dual connect by level <= 100000;
insert into student select * from student;
insert into student select * from student;
insert into student select * from student;
insert into student select * from student;
begin
    dbms_stats.gather_table_stats(user, 'STUDENT');
end;
/
create index student_idx on student(score);
</code>```

Option 1: Simplest query with both min and max - doesn't work

The simplest query uses an INDEX FAST FULL SCAN.  Which is probably better than a full table scan, but can still be expensive for large indexes.

```<code>explain plan for select max(score),min(score) from student;
select * from table(dbms_xplan.display);

Plan hash value: 4052181173

-------------------------------------------------------------------------------------
| Id  | Operation             | Name        | Rows  | Bytes | Cost (%CPU)| Time     |
-------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT      |             |     1 |     5 |   972   (2)| 00:00:01 |
|   1 |  SORT AGGREGATE       |             |     1 |     5 |            |          |
|   2 |   INDEX FAST FULL SCAN| STUDENT_IDX |  1600K|  7812K|   972   (2)| 00:00:01 |
-------------------------------------------------------------------------------------
</code>```

Option 2 - Only MIN or MAX in one query

Running one-at-a-time results in an optimal plan with a super-low cost of 3.  It has the INDEX FULL SCAN (MIN/MAX) operation.  This is probably as fast as it gets, although it only returns half the answer.  Using MIN instead of MAX returns the same plan.

```<code>--MIN works the same way
explain plan for select max(score) from student;
select * from table(dbms_xplan.display);

Plan hash value: 3501948619

------------------------------------------------------------------------------------------
| Id  | Operation                  | Name        | Rows  | Bytes | Cost (%CPU)| Time     |
------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT           |             |     1 |     5 |     3   (0)| 00:00:01 |
|   1 |  SORT AGGREGATE            |             |     1 |     5 |            |          |
|   2 |   INDEX FULL SCAN (MIN/MAX)| STUDENT_IDX |     1 |     5 |     3   (0)| 00:00:01 |
------------------------------------------------------------------------------------------
</code>```

Option 3 - Combining MIN and MAX with subqueries

Combining the two with subqueries takes a bit more code but the result will be much faster than the simpler query in option 1.  The cost looks a little higher than twice the cost of option 2, but when you factor in the extra round-trip to the database, option 3 will be the fastest.

There are other ways to do this in one query, such as using a UNION ALL.

```<code>explain plan for
select
    (select max(score) from student),
    (select min(score) from student)
from dual;

select * from table(dbms_xplan.display);

Plan hash value: 661746414

------------------------------------------------------------------------------------------
| Id  | Operation                  | Name        | Rows  | Bytes | Cost (%CPU)| Time     |
------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT           |             |     1 |       |     8   (0)| 00:00:01 |
|   1 |  SORT AGGREGATE            |             |     1 |     5 |            |          |
|   2 |   INDEX FULL SCAN (MIN/MAX)| STUDENT_IDX |     1 |     5 |     3   (0)| 00:00:01 |
|   3 |  SORT AGGREGATE            |             |     1 |     5 |            |          |
|   4 |   INDEX FULL SCAN (MIN/MAX)| STUDENT_IDX |     1 |     5 |     3   (0)| 00:00:01 |
|   5 |  FAST DUAL                 |             |     1 |       |     2   (0)| 00:00:01 |
------------------------------------------------------------------------------------------
</code>```

Body:
I have a table called student,I want to get the max and min score,so I write the sql in first way:

select max(score),min(score) from student;

and the second way:

select max(score) from student;
select min(score) from student;

I search from the internet and they say that the second way is better because the oracle can not scan the index in the same time.But the second way can not ensure the same datasoure because it do twice searching.How to fix it?

Body:
Combine the two queries from the second method into a single query:

select
    (select max(score) from student),
    (select min(score) from student)
from dual;

That solution uses two fast index scans.  It should run faster than option 1 or 2 and will also be consistent.

Why doesn't the simplest solution work?

It certainly seems like Oracle should have a way to run this optimally:

select max(score),min(score) from student;

I've seen this query before, seen people discuss it, and Oracle even has special access paths for getting the max and min: INDEX FULL SCAN (MIN/MAX).  But it just can't seem to do both the min and the max at the same time and I'm not sure why.

It's hard to prove Oracle can't do something.  Maybe someone will come in later and prove me wrong.  My answer is based on this article by Richard Foote, who is perhaps the world's top Oracle index expert.  And I've included some simple tests below.  The sample schema looks like an ideal case for Oracle to automatically use the INDEX FULL SCAN (MIN/MAX) twice in one query, but it doesn't.  My results were generated using the latest version, 12.2.

Sample Schema

--Create STUDENT table with 1.6 million rows, an index on score, and fresh statistics.
--drop table student;
create table student(name varchar2(100), score number not null);
insert into student select lpad('A', 20, 'A'), level from dual connect by level <= 100000;
insert into student select * from student;
insert into student select * from student;
insert into student select * from student;
insert into student select * from student;
begin
    dbms_stats.gather_table_stats(user, 'STUDENT');
end;
/
create index student_idx on student(score);

Option 1: Simplest query with both min and max - doesn't work

The simplest query uses an INDEX FAST FULL SCAN.  Which is probably better than a full table scan, but can still be expensive for large indexes.

explain plan for select max(score),min(score) from student;
select * from table(dbms_xplan.display);

Plan hash value: 4052181173

-------------------------------------------------------------------------------------
| Id  | Operation             | Name        | Rows  | Bytes | Cost (%CPU)| Time     |
-------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT      |             |     1 |     5 |   972   (2)| 00:00:01 |
|   1 |  SORT AGGREGATE       |             |     1 |     5 |            |          |
|   2 |   INDEX FAST FULL SCAN| STUDENT_IDX |  1600K|  7812K|   972   (2)| 00:00:01 |
-------------------------------------------------------------------------------------

Option 2 - Only MIN or MAX in one query

Running one-at-a-time results in an optimal plan with a super-low cost of 3.  It has the INDEX FULL SCAN (MIN/MAX) operation.  This is probably as fast as it gets, although it only returns half the answer.  Using MIN instead of MAX returns the same plan.

--MIN works the same way
explain plan for select max(score) from student;
select * from table(dbms_xplan.display);

Plan hash value: 3501948619

------------------------------------------------------------------------------------------
| Id  | Operation                  | Name        | Rows  | Bytes | Cost (%CPU)| Time     |
------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT           |             |     1 |     5 |     3   (0)| 00:00:01 |
|   1 |  SORT AGGREGATE            |             |     1 |     5 |            |          |
|   2 |   INDEX FULL SCAN (MIN/MAX)| STUDENT_IDX |     1 |     5 |     3   (0)| 00:00:01 |
------------------------------------------------------------------------------------------

Option 3 - Combining MIN and MAX with subqueries

Combining the two with subqueries takes a bit more code but the result will be much faster than the simpler query in option 1.  The cost looks a little higher than twice the cost of option 2, but when you factor in the extra round-trip to the database, option 3 will be the fastest.

There are other ways to do this in one query, such as using a UNION ALL.

explain plan for
select
    (select max(score) from student),
    (select min(score) from student)
from dual;

select * from table(dbms_xplan.display);

Plan hash value: 661746414

------------------------------------------------------------------------------------------
| Id  | Operation                  | Name        | Rows  | Bytes | Cost (%CPU)| Time     |
------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT           |             |     1 |       |     8   (0)| 00:00:01 |
|   1 |  SORT AGGREGATE            |             |     1 |     5 |            |          |
|   2 |   INDEX FULL SCAN (MIN/MAX)| STUDENT_IDX |     1 |     5 |     3   (0)| 00:00:01 |
|   3 |  SORT AGGREGATE            |             |     1 |     5 |            |          |
|   4 |   INDEX FULL SCAN (MIN/MAX)| STUDENT_IDX |     1 |     5 |     3   (0)| 00:00:01 |
|   5 |  FAST DUAL                 |             |     1 |       |     2   (0)| 00:00:01 |
------------------------------------------------------------------------------------------


问:
CSS: display a long string line-line with checkbox
I have a string with 255 characters (no space) and want to display it inline with a checkbox, not under. I have tried inline; inline-block; ... but it doesn't work. Anyone help?</p>

```<code><div class="item">
    <input type="checkbox" id="a">
    <label for="a">a</label>
</div>
<div class="item">
   <input type="checkbox" id="b">
<!-- 255 characters string here -->
    <label for="b">eyDlDLuT8A8AMTeyHSBXj4BeiWefQc1KWilxVWe7m7Vja1m9eEDc8iJ778jvaR2pCN2PcPcIWexrHehXSPJGqWaiSWfqSZL3AuZfOB0U3hlOCQMFWmqHWsERpWrF5YynmiJnn5mZoUP9TDPjW379O38BuBH9Q5zYlIRWgxAskcFT4DJAejiiIeu78jt1jsUU90RqV499IigZSqluOaJY3sptm0qADxE5M1JmnfEB9a8v7yihlrDq3Yy1MVMofBF</label>
</div>
<div class="item">
    <input type="checkbox" id="c">
    <label for="c">c</label>
</div>
</code>```

答: You can use the CSS property white-space: nowrap in a span that contains both the checkbox and the string. See here on Fiddle: https://fiddle.jshell.net/aa8j1tu5/</p>

Body:
I have a string with 255 characters (no space) and want to display it inline with a checkbox, not under. I have tried inline; inline-block; ... but it doesn't work. Anyone help?

    <input type="checkbox" id="a">
    a

   <input type="checkbox" id="b">

    eyDlDLuT8A8AMTeyHSBXj4BeiWefQc1KWilxVWe7m7Vja1m9eEDc8iJ778jvaR2pCN2PcPcIWexrHehXSPJGqWaiSWfqSZL3AuZfOB0U3hlOCQMFWmqHWsERpWrF5YynmiJnn5mZoUP9TDPjW379O38BuBH9Q5zYlIRWgxAskcFT4DJAejiiIeu78jt1jsUU90RqV499IigZSqluOaJY3sptm0qADxE5M1JmnfEB9a8v7yihlrDq3Yy1MVMofBF

    <input type="checkbox" id="c">
    c


问:
Modern symbolic execution techniques
What is the best technique of symbolic execution?
Would you please help me to find pure symbolic execution and pure concolic testing tool (I mean, e.g. it is not including model checking,etc.) with its source?</p>

答:
Concolic Testing Tools:

CREST for C[Open Source]

CATG for JAVA

Jalangi for javascript [Open Source]

Microsoft PEX for .Net framework [power tool in Visual Studio]

CutEr for Erlang functional programming [Open Source]

For Symbolic Execution, several tools are listed on the link below(Some tools are common, because they have option for both):

https://en.wikipedia.org/wiki/Symbolic_execution

Title: Modern symbolic execution techniques


问:
Azure App Service Architecture understanding: IP-based SSL
Regarding this MSDN article; https://msdn.microsoft.com/en-us/magazine/mt793270

Scale Unit Network Configuration sections has below sentences;

In the case of IP-based SSL, a given application is allocated a dedicated IP address for only inbound traffic, which is associated with the Cloud Service deployment. Please note: Front ends terminate SSL connection for all HTTPS requests for all applications and any type of certificate. The front end then forwards the request to the designated worker for a given application.

But, when Please note: Front ends terminate SSL connection for all HTTPS requests for all applications and any type of certificate happens?

Is this happened right after that we configure IP-based SSL?

or, is this happened to all traffics always under IP-based SSL?

or else?

答: It happens for all traffics. All https traffic irrespective of whether you are using a ip-based SSL, SSL cert from external CA's or using internal Azure SSL (azurewebsites.net) the SSL traffic is terminated at the front-end each scale unit has and from front-end to worker will always be http traffic. In return the same is encrypted back at front-end before traffic goes out using the SSL uploaded for specific domain/azure provided SSL cert.</p>


问:
Constructor expecting missing call to other constructor / candidate expects 1 argument, 0 provided?
You may have seen my post yesterday about the issues I had been having with my text-based adventure game. I got all of that fixed up and added some functionality, but in adding some inventory arrays of custom Slot objects my Character object decided to stop recognizing their initialization.

Here's the basic code:

Character Class

```<code>class Character {
    InvSlot inventory[30];
    FoodSlot foodInv[10];
    //Declaring armor slots, class, race, stats, etc

public:
    //All of the function declarations
</code>```

Character Constructor

```<code>Character::Character() :
    //Initializing armor slots, class, race, stats, etc to default values
{
    InvSlot inventory[30] = {emptyInv,...,emptyInv}; //The other 28 values are omitted here.
    FoodSlot foodInv[10] = {emptyFood,...,emptyFood}; //The other 8 values are omitted here.
}
</code>```

InvSlot and FoodSlot Structs w/ Basic Empty Slots

```<code>struct InvSlot {
    bool isUsed;
    Item item;
    InvSlot(Item i);
};

struct FoodSlot {
    bool isUsed;
    Item item;
    FoodSlot(Food f);
};

InvSlot::InvSlot(Item i) : isUsed(false), item(i){}
InvSlot emptyInv = InvSlot(NoItem); //NoItem is a basic object of type Item which works

FoodSlot::FoodSlot(Food f) : isUsed(false, food(f), quantity(0){}
FoodSlot emptyFood = FoodSlot(NoFood); //Same deal with NoFood
</code>```

The Errors

First of all, the struct declarations and constructor definitions for InvSlot and FoodSlot are giving me the issue of candidate expects 1 argument, 0 provided. Second of all, the actual errors are on the final initializer in the Character constructor (before the curly braces): no matching function for call to 'FoodSlot::FoodSlot()' and no matching function for call to 'InvSlot::InvSlot()'. The thing is, I have already initialized the arrays in the curly braces and they aren't returning any errors themselves. On top of this, these two are the only two parameters for the character class which even use the InvSlot or FoodSlot objects. Can anybody help figure out what's going on, and how to fix it? I already checked other similar questions but they didn't help. Let me know if I need to add anything or if I missed something when typing up this post.

Thanks in advance!

答:
The error message you get is basically that the default constructor can't be found, which is obviously the case. When you write

```<code>InvSlot inventory[30];
FoodSlot foodInv[10];
</code>```

the default constructor is called to initialize your arrays. What you can do is to write a default constructor for InvSlot and FoodSlot which basically return an empty InvSlot and FoodSlot. With empty I mean the semantically equivalent of the objects you used in your initializer list (emptyInv, emptyFood).

Body:
You may have seen my post yesterday about the issues I had been having with my text-based adventure game. I got all of that fixed up and added some functionality, but in adding some inventory arrays of custom Slot objects my Character object decided to stop recognizing their initialization.

Here's the basic code:

Character Class

class Character {
    InvSlot inventory[30];
    FoodSlot foodInv[10];
    //Declaring armor slots, class, race, stats, etc

public:
    //All of the function declarations

Character Constructor

Character::Character() :
    //Initializing armor slots, class, race, stats, etc to default values
{
    InvSlot inventory[30] = {emptyInv,...,emptyInv}; //The other 28 values are omitted here.
    FoodSlot foodInv[10] = {emptyFood,...,emptyFood}; //The other 8 values are omitted here.
}

InvSlot and FoodSlot Structs w/ Basic Empty Slots

struct InvSlot {
    bool isUsed;
    Item item;
    InvSlot(Item i);
};

struct FoodSlot {
    bool isUsed;
    Item item;
    FoodSlot(Food f);
};

InvSlot::InvSlot(Item i) : isUsed(false), item(i){}
InvSlot emptyInv = InvSlot(NoItem); //NoItem is a basic object of type Item which works

FoodSlot::FoodSlot(Food f) : isUsed(false, food(f), quantity(0){}
FoodSlot emptyFood = FoodSlot(NoFood); //Same deal with NoFood

The Errors

First of all, the struct declarations and constructor definitions for InvSlot and FoodSlot are giving me the issue of candidate expects 1 argument, 0 provided. Second of all, the actual errors are on the final initializer in the Character constructor (before the curly braces): no matching function for call to 'FoodSlot::FoodSlot()' and no matching function for call to 'InvSlot::InvSlot()'. The thing is, I have already initialized the arrays in the curly braces and they aren't returning any errors themselves. On top of this, these two are the only two parameters for the character class which even use the InvSlot or FoodSlot objects. Can anybody help figure out what's going on, and how to fix it? I already checked other similar questions but they didn't help. Let me know if I need to add anything or if I missed something when typing up this post.

Thanks in advance!

Body:
The error message you get is basically that the default constructor can't be found, which is obviously the case. When you write

InvSlot inventory[30];
FoodSlot foodInv[10];

the default constructor is called to initialize your arrays. What you can do is to write a default constructor for InvSlot and FoodSlot which basically return an empty InvSlot and FoodSlot. With empty I mean the semantically equivalent of the objects you used in your initializer list (emptyInv, emptyFood).


问:
Xamarin Android PCL Web Request Hangs
I am trying to make a PCL that can make web requests for a Xamarin Android project.

My AndoridManifest.xml looks like as follows

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="JJJ.Mobile.Android" android:installLocation="auto">
    <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="23" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <application android:allowBackup="true" android:label="@string/app_name" android:theme="@style/MyTheme"></application>
</manifest>
</code>```

The code in the Android main activity button click just calls this PCL Create method directly.

I have breakpoints on the lines where it does SendAsync and where returns null, the SendAsync breakpoint gets hit and when you step over it VS hangs for a second then the Emulator is displayed and the app is hanging - Android displays soon after a message about not responding to wait or not - the exception breakpoint never gets hit. No exception is shown in the console

```<code>public async Task<HttpResponseMessage> Create()
        {
            try
            {
                var uri = new Uri("http://rxnav.nlm.nih.gov/REST/RxTerms/rxcui/198440/allinfo");

                var httpClient = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri);

                var response = await httpClient.SendAsync(request);
                return response;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
</code>```

The console output after button clicked, not sure if it's helpful or not

```<code>Thread started:  #6
03-30 19:31:17.669 D/Mono    ( 2556): Assembly Ref addref System.Net.Http[0x9d63d4e0] -> System.Core[0x9e0abbe0]: 10
Thread started: <Thread Pool> #7
03-30 19:31:18.392 D/Mono    ( 2556): [0x9d7bf930] hill climbing, change max number of threads 3
Thread started: <Thread Pool> #8
03-30 19:31:18.490 D/Mono    ( 2556): [0x9adbf930] worker starting
03-30 19:31:18.538 D/Mono    ( 2556): Unloading image System.dll [0x9ae04f00].
03-30 19:31:18.539 D/Mono    ( 2556): Image addref System[0xaed95740] -> System.dll[0xaadd4900]: 5
03-30 19:31:18.539 D/Mono    ( 2556): Config attempting to parse: 'System.dll.config'.
03-30 19:31:18.539 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System/System.config'.
03-30 19:31:18.540 D/Mono    ( 2556): Unloading image System.dll [0x9ae04f00].
03-30 19:31:18.540 D/Mono    ( 2556): Image addref System[0xaed95920] -> System.dll[0xaadd4900]: 6
03-30 19:31:18.541 D/Mono    ( 2556): Config attempting to parse: 'System.dll.config'.
03-30 19:31:18.541 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System/System.config'.
03-30 19:31:18.543 D/Mono    ( 2556): Unloading image System.dll [0x9ae04f00].
03-30 19:31:18.543 D/Mono    ( 2556): Image addref System[0xaed95920] -> System.dll[0xaadd4900]: 7
03-30 19:31:18.543 D/Mono    ( 2556): Config attempting to parse: 'System.dll.config'.
03-30 19:31:18.543 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System/System.config'.
03-30 19:31:18.545 D/Mono    ( 2556): Unloading image System.dll [0x9ae04f00].
03-30 19:31:18.545 D/Mono    ( 2556): Image addref System[0xaed95920] -> System.dll[0xaadd4900]: 8
03-30 19:31:18.545 D/Mono    ( 2556): Config attempting to parse: 'System.dll.config'.
03-30 19:31:18.545 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System/System.config'.
03-30 19:31:18.573 D/Mono    ( 2556): DllImport searching in: '__Internal' ('(null)').
03-30 19:31:18.573 D/Mono    ( 2556): Searching for 'java_interop_jnienv_is_assignable_from'.
03-30 19:31:18.573 D/Mono    ( 2556): Probing 'java_interop_jnienv_is_assignable_from'.
03-30 19:31:18.573 D/Mono    ( 2556): Found as 'java_interop_jnienv_is_assignable_from'.
03-30 19:31:18.574 D/Mono    ( 2556): DllImport searching in: '__Internal' ('(null)').
03-30 19:31:18.574 D/Mono    ( 2556): Searching for 'java_interop_jnienv_get_byte_array_region'.
03-30 19:31:18.574 D/Mono    ( 2556): Probing 'java_interop_jnienv_get_byte_array_region'.
03-30 19:31:18.574 D/Mono    ( 2556): Found as 'java_interop_jnienv_get_byte_array_region'.
03-30 19:31:18.575 D/Mono    ( 2556): DllImport searching in: '__Internal' ('(null)').
03-30 19:31:18.575 D/Mono    ( 2556): Searching for 'java_interop_jnienv_set_byte_array_region'.
03-30 19:31:18.575 D/Mono    ( 2556): Probing 'java_interop_jnienv_set_byte_array_region'.
03-30 19:31:18.575 D/Mono    ( 2556): Found as 'java_interop_jnienv_set_byte_array_region'.
03-30 19:31:18.632 W/Mono    ( 2556): The request to load the assembly System.Core v4.0.0.0 was remapped to v2.0.5.0
03-30 19:31:18.632 D/Mono    ( 2556): Unloading image System.Core.dll [0x9ae06d00].
03-30 19:31:18.632 D/Mono    ( 2556): Image addref System.Core[0xaed96460] -> System.Core.dll[0xaadd6700]: 5
03-30 19:31:18.632 D/Mono    ( 2556): Config attempting to parse: 'System.Core.dll.config'.
03-30 19:31:18.632 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System.Core/System.Core.config'.
03-30 19:31:18.640 W/Mono    ( 2556): The request to load the assembly System.Core v4.0.0.0 was remapped to v2.0.5.0
03-30 19:31:18.641 D/Mono    ( 2556): Unloading image System.Core.dll [0x9ae05e00].
03-30 19:31:18.641 D/Mono    ( 2556): Image addref System.Core[0xaed96460] -> System.Core.dll[0xaadd6700]: 6
03-30 19:31:18.641 D/Mono    ( 2556): Config attempting to parse: 'System.Core.dll.config'.
03-30 19:31:18.641 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System.Core/System.Core.config'.
03-30 19:31:18.895 D/Mono    ( 2556): [0x9d7bf930] hill climbing, change max number of threads 2
03-30 19:31:24.114 D/Mono    ( 2556): [0x9adbf930] worker finishing
Thread finished: <Thread Pool> #8
The thread 'Unknown' (0x8) has exited with code 0 (0x0).
</code>```

The emulator is running Android 6, I've checked the internet by using the built in browser and it works. I am really confused about this, any help would be greatly appreciated!

答:
Not sure what is causing that. However, I am able to do GET request to my web service. I am using WebRequest instead. I will provide the code below and you could try that.

```<code>public async Task<WebResponse> Create()
{
    var uri = "http://rxnav.nlm.nih.gov/REST/RxTerms/rxcui/198440/allinfo";
    WebRequest request = WebRequest.CreateHttp(uri);
    string responseValue = null;
    try
    {
        using (var response = await request.GetResponseAsync())
        {
            using (var stream = response.GetResponseStream())
            {
                if (stream != null)
                {
                    using (var reader = new StreamReader(stream))
                    {
                        responseValue = await reader.ReadToEndAsync();
                    }
                }
            }
        }
        return responseValue;
    }
    catch (Exception ex)
    {
        return null;
    }
}
</code>```

Hope this could help.

Title: Xamarin Android PCL Web Request Hangs

Body:
I am trying to make a PCL that can make web requests for a Xamarin Android project.

My AndoridManifest.xml looks like as follows

<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="JJJ.Mobile.Android" android:installLocation="auto">
    <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="23" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <application android:allowBackup="true" android:label="@string/app_name" android:theme="@style/MyTheme"></application>
</manifest>

The code in the Android main activity button click just calls this PCL Create method directly.

I have breakpoints on the lines where it does SendAsync and where returns null, the SendAsync breakpoint gets hit and when you step over it VS hangs for a second then the Emulator is displayed and the app is hanging - Android displays soon after a message about not responding to wait or not - the exception breakpoint never gets hit. No exception is shown in the console

public async Task<HttpResponseMessage> Create()
        {
            try
            {
                var uri = new Uri("http://rxnav.nlm.nih.gov/REST/RxTerms/rxcui/198440/allinfo");

                var httpClient = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri);

                var response = await httpClient.SendAsync(request);
                return response;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

The console output after button clicked, not sure if it's helpful or not

Thread started:  #6
03-30 19:31:17.669 D/Mono    ( 2556): Assembly Ref addref System.Net.Http[0x9d63d4e0] -> System.Core[0x9e0abbe0]: 10
Thread started: <Thread Pool> #7
03-30 19:31:18.392 D/Mono    ( 2556): [0x9d7bf930] hill climbing, change max number of threads 3
Thread started: <Thread Pool> #8
03-30 19:31:18.490 D/Mono    ( 2556): [0x9adbf930] worker starting
03-30 19:31:18.538 D/Mono    ( 2556): Unloading image System.dll [0x9ae04f00].
03-30 19:31:18.539 D/Mono    ( 2556): Image addref System[0xaed95740] -> System.dll[0xaadd4900]: 5
03-30 19:31:18.539 D/Mono    ( 2556): Config attempting to parse: 'System.dll.config'.
03-30 19:31:18.539 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System/System.config'.
03-30 19:31:18.540 D/Mono    ( 2556): Unloading image System.dll [0x9ae04f00].
03-30 19:31:18.540 D/Mono    ( 2556): Image addref System[0xaed95920] -> System.dll[0xaadd4900]: 6
03-30 19:31:18.541 D/Mono    ( 2556): Config attempting to parse: 'System.dll.config'.
03-30 19:31:18.541 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System/System.config'.
03-30 19:31:18.543 D/Mono    ( 2556): Unloading image System.dll [0x9ae04f00].
03-30 19:31:18.543 D/Mono    ( 2556): Image addref System[0xaed95920] -> System.dll[0xaadd4900]: 7
03-30 19:31:18.543 D/Mono    ( 2556): Config attempting to parse: 'System.dll.config'.
03-30 19:31:18.543 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System/System.config'.
03-30 19:31:18.545 D/Mono    ( 2556): Unloading image System.dll [0x9ae04f00].
03-30 19:31:18.545 D/Mono    ( 2556): Image addref System[0xaed95920] -> System.dll[0xaadd4900]: 8
03-30 19:31:18.545 D/Mono    ( 2556): Config attempting to parse: 'System.dll.config'.
03-30 19:31:18.545 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System/System.config'.
03-30 19:31:18.573 D/Mono    ( 2556): DllImport searching in: '__Internal' ('(null)').
03-30 19:31:18.573 D/Mono    ( 2556): Searching for 'java_interop_jnienv_is_assignable_from'.
03-30 19:31:18.573 D/Mono    ( 2556): Probing 'java_interop_jnienv_is_assignable_from'.
03-30 19:31:18.573 D/Mono    ( 2556): Found as 'java_interop_jnienv_is_assignable_from'.
03-30 19:31:18.574 D/Mono    ( 2556): DllImport searching in: '__Internal' ('(null)').
03-30 19:31:18.574 D/Mono    ( 2556): Searching for 'java_interop_jnienv_get_byte_array_region'.
03-30 19:31:18.574 D/Mono    ( 2556): Probing 'java_interop_jnienv_get_byte_array_region'.
03-30 19:31:18.574 D/Mono    ( 2556): Found as 'java_interop_jnienv_get_byte_array_region'.
03-30 19:31:18.575 D/Mono    ( 2556): DllImport searching in: '__Internal' ('(null)').
03-30 19:31:18.575 D/Mono    ( 2556): Searching for 'java_interop_jnienv_set_byte_array_region'.
03-30 19:31:18.575 D/Mono    ( 2556): Probing 'java_interop_jnienv_set_byte_array_region'.
03-30 19:31:18.575 D/Mono    ( 2556): Found as 'java_interop_jnienv_set_byte_array_region'.
03-30 19:31:18.632 W/Mono    ( 2556): The request to load the assembly System.Core v4.0.0.0 was remapped to v2.0.5.0
03-30 19:31:18.632 D/Mono    ( 2556): Unloading image System.Core.dll [0x9ae06d00].
03-30 19:31:18.632 D/Mono    ( 2556): Image addref System.Core[0xaed96460] -> System.Core.dll[0xaadd6700]: 5
03-30 19:31:18.632 D/Mono    ( 2556): Config attempting to parse: 'System.Core.dll.config'.
03-30 19:31:18.632 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System.Core/System.Core.config'.
03-30 19:31:18.640 W/Mono    ( 2556): The request to load the assembly System.Core v4.0.0.0 was remapped to v2.0.5.0
03-30 19:31:18.641 D/Mono    ( 2556): Unloading image System.Core.dll [0x9ae05e00].
03-30 19:31:18.641 D/Mono    ( 2556): Image addref System.Core[0xaed96460] -> System.Core.dll[0xaadd6700]: 6
03-30 19:31:18.641 D/Mono    ( 2556): Config attempting to parse: 'System.Core.dll.config'.
03-30 19:31:18.641 D/Mono    ( 2556): Config attempting to parse: '/Users/builder/data/lanes/4009/3a62f1ea/source/monodroid/builds/install/mono-x86/etc/mono/assemblies/System.Core/System.Core.config'.
03-30 19:31:18.895 D/Mono    ( 2556): [0x9d7bf930] hill climbing, change max number of threads 2
03-30 19:31:24.114 D/Mono    ( 2556): [0x9adbf930] worker finishing
Thread finished: <Thread Pool> #8
The thread 'Unknown' (0x8) has exited with code 0 (0x0).

The emulator is running Android 6, I've checked the internet by using the built in browser and it works. I am really confused about this, any help would be greatly appreciated!

Body:
Not sure what is causing that. However, I am able to do GET request to my web service. I am using WebRequest instead. I will provide the code below and you could try that.

public async Task<WebResponse> Create()
{
    var uri = "http://rxnav.nlm.nih.gov/REST/RxTerms/rxcui/198440/allinfo";
    WebRequest request = WebRequest.CreateHttp(uri);
    string responseValue = null;
    try
    {
        using (var response = await request.GetResponseAsync())
        {
            using (var stream = response.GetResponseStream())
            {
                if (stream != null)
                {
                    using (var reader = new StreamReader(stream))
                    {
                        responseValue = await reader.ReadToEndAsync();
                    }
                }
            }
        }
        return responseValue;
    }
    catch (Exception ex)
    {
        return null;
    }
}

Hope this could help.


问:
java.lang.Long cannot be cast to java.lang.String
I need to iterate a List<myClass> in a jsp. This is how I obtain the list:

(when I commented it, the page loaded just fine).

```<code> <%
      List<myClass> pjList = null;
      StringBuffer ejbQuery = new StringBuffer();

      EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPersistence");
      EntityManager em = emf.createEntityManager();

      ejbQuery.append("SELECT e ");
      ejbQuery.append("FROM myClass e ");
      pjList = em.createQuery(ejbQuery.toString()).getResultList();

for(myClass pj : pjList)
{
    %>
    <br />
    <%= pj.getSomeField()%>
    <br />
    <%
}
%>
</code>```

This is the error I get when running it in google appengine. locally it runs fine.

```<code>Uncaught exception from servlet
java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.String
 at org.datanucleus.store.appengine.DatastoreFieldManager.fetchStringField(DatastoreFieldManager.java:188)
 at org.datanucleus.state.AbstractStateManager.replacingStringField(AbstractStateManager.java:1180)
 at ar.edu.kennedy.proveedores.entities.ProEnteEy.jdoReplaceField(ProEnteEy.java)
 at ar.edu.kennedy.proveedores.entities.ProPersonaJuridicaEy.jdoReplaceField(ProPersonaJuridicaEy.java)
 at ar.edu.kennedy.proveedores.entities.ProEnteEy.jdoReplaceFields(ProEnteEy.java)
 at org.datanucleus.state.JDOStateManagerImpl.replaceFields(JDOStateManagerImpl.java:2772)
 at org.datanucleus.state.JDOStateManagerImpl.replaceFields(JDOStateManagerImpl.java:2791)
 at org.datanucleus.store.appengine.DatastorePersistenceHandler.fetchObject(DatastorePersistenceHandler.java:443)
 at org.datanucleus.store.appengine.query.DatastoreQuery.entityToPojo(DatastoreQuery.java:433)
 at org.datanucleus.store.appengine.query.DatastoreQuery.entityToPojo(DatastoreQuery.java:391)
 at org.datanucleus.store.appengine.query.DatastoreQuery.access$800(DatastoreQuery.java:97)
 at org.datanucleus.store.appengine.query.DatastoreQuery$5.apply(DatastoreQuery.java:515)
 at org.datanucleus.store.appengine.query.DatastoreQuery$5.apply(DatastoreQuery.java:507)
 at org.datanucleus.store.appengine.query.StreamingQueryResult.resolveNext(StreamingQueryResult.java:137)
 at org.datanucleus.store.appengine.query.StreamingQueryResult$1.computeNext(StreamingQueryResult.java:163)
 at org.datanucleus.store.appengine.query.AbstractIterator.tryToComputeNext(AbstractIterator.java:132)
 at org.datanucleus.store.appengine.query.AbstractIterator.hasNext(AbstractIterator.java:127)
 at org.datanucleus.store.appengine.query.StreamingQueryResult$AbstractListIterator.hasNext(StreamingQueryResult.java:229)
 at org.apache.jsp.busqueda_jsp._jspService(busqueda_jsp.java:138)
</code>```

If I use a ListIterator and call hasNext() I get the same error. Help me understand what is happening, how to solve this?

答:
```<code>criteria.add(Expression.like("status", 115));
</code>```

Error:java.lang.classCastException: java.lang.Integer cannot cast to java.lang.String

Do like this:

```<code>criteria.add(Expression.like("status", new String("115")));
</code>```

Body:
I need to iterate a List<myClass> in a jsp. This is how I obtain the list:

(when I commented it, the page loaded just fine).

 <%
      List<myClass> pjList = null;
      StringBuffer ejbQuery = new StringBuffer();

      EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPersistence");
      EntityManager em = emf.createEntityManager();

      ejbQuery.append("SELECT e ");
      ejbQuery.append("FROM myClass e ");
      pjList = em.createQuery(ejbQuery.toString()).getResultList();

for(myClass pj : pjList)
{
    %>

    <%= pj.getSomeField()%>

    <%
}
%>

This is the error I get when running it in google appengine. locally it runs fine.

Uncaught exception from servlet
java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.String
 at org.datanucleus.store.appengine.DatastoreFieldManager.fetchStringField(DatastoreFieldManager.java:188)
 at org.datanucleus.state.AbstractStateManager.replacingStringField(AbstractStateManager.java:1180)
 at ar.edu.kennedy.proveedores.entities.ProEnteEy.jdoReplaceField(ProEnteEy.java)
 at ar.edu.kennedy.proveedores.entities.ProPersonaJuridicaEy.jdoReplaceField(ProPersonaJuridicaEy.java)
 at ar.edu.kennedy.proveedores.entities.ProEnteEy.jdoReplaceFields(ProEnteEy.java)
 at org.datanucleus.state.JDOStateManagerImpl.replaceFields(JDOStateManagerImpl.java:2772)
 at org.datanucleus.state.JDOStateManagerImpl.replaceFields(JDOStateManagerImpl.java:2791)
 at org.datanucleus.store.appengine.DatastorePersistenceHandler.fetchObject(DatastorePersistenceHandler.java:443)
 at org.datanucleus.store.appengine.query.DatastoreQuery.entityToPojo(DatastoreQuery.java:433)
 at org.datanucleus.store.appengine.query.DatastoreQuery.entityToPojo(DatastoreQuery.java:391)
 at org.datanucleus.store.appengine.query.DatastoreQuery.access$800(DatastoreQuery.java:97)
 at org.datanucleus.store.appengine.query.DatastoreQuery$5.apply(DatastoreQuery.java:515)
 at org.datanucleus.store.appengine.query.DatastoreQuery$5.apply(DatastoreQuery.java:507)
 at org.datanucleus.store.appengine.query.StreamingQueryResult.resolveNext(StreamingQueryResult.java:137)
 at org.datanucleus.store.appengine.query.StreamingQueryResult$1.computeNext(StreamingQueryResult.java:163)
 at org.datanucleus.store.appengine.query.AbstractIterator.tryToComputeNext(AbstractIterator.java:132)
 at org.datanucleus.store.appengine.query.AbstractIterator.hasNext(AbstractIterator.java:127)
 at org.datanucleus.store.appengine.query.StreamingQueryResult$AbstractListIterator.hasNext(StreamingQueryResult.java:229)
 at org.apache.jsp.busqueda_jsp._jspService(busqueda_jsp.java:138)

If I use a ListIterator and call hasNext() I get the same error. Help me understand what is happening, how to solve this?

Body:
criteria.add(Expression.like("status", 115));

Error:java.lang.classCastException: java.lang.Integer cannot cast to java.lang.String

Do like this:

criteria.add(Expression.like("status", new String("115")));


问:
How to read complicated spring configuration from map?
I have the following property application.properties file:

```<code>mapper.url1=C:\\Program Files\\Java\\jdk1.8.0_111\\bin\\java.exe
mapper.url2=C:\\Program Files\\Java\\jdk1.8.0_111\\bin\\javaw.exe
</code>```

and following bean, which reflection in java code:

```<code>@Component
@EnableConfigurationProperties
@ConfigurationProperties
public class ApplicationProperties {
    private Map<String, String> mapper;
    //get and set methods
    ....
</code>```

Now I want to extend this format and add  timeout to the key.

I expect that the most readable(I do not insist, you can suggest another) format would be:

```<code>mapper.url1=C:\\Program Files\\Java\\jdk1.8.0_111\\bin\\java.exe
mapper.url1.timeOut=1000
</code>```

How to extend my configuration to read this(or another with same power) format?

Where does correct place to validate it?

I want to validate property file format. Each key should contain both: path and timeout. Otherwise application should not be started

答:
Use a nested class to represent the properties.

For example:

@ConfigurationProperties
public class DemoApplication {

    ...

    public static class UrlProperties {
        // use Path or File so it's type-safe
        private Path path;

        // use int for type-safety
        private int timeout;

        public Path getPath() {
            return path;
        }

        public void setPath(final Path path) {
            this.path = path;
        }

        public int getTimeout() {
            return timeout;
        }

        public void setTimeout(final int timeout) {
            this.timeout = timeout;
        }

        @Override
        public String toString() {
            return "UrlProperties{" + "path=" + path + ", timeout=" + timeout + '}';
        }
    }
}
```

<p>and then define your <code>Map</code> instance variable with a <code>String</code> key and a value as the nested class type:</p>

<p><code>private Map<String, UrlProperties> mapper;</code></p>

<p>and use the properties like this:</p>

```mapper.url1.path=C:\\Program Files\\Java\\jdk1.8.0_111\\bin\\java.exe
mapper.url1.timeout=1000

mapper.url2.path=C:\\Program Files\\Java\\jdk1.8.0_111\\bin\\javaw.exe
mapper.url2.timeout=5000
```

<p>You'll end up with objects that look like this:</p>

```{url2=UrlProperties{path=C:\Program Files\Java\jdk1.8.0_111\bin\javaw.exe, timeout=5000}, url1=UrlProperties{path=C:\Program Files\Java\jdk1.8.0_111\bin\java.exe, timeout=1000}}
```

Additionally, with Spring Boot 1.5, you can use JSR-303 annotations to validate your ConfigurationProperties. See here for more details.

Body:
I have the following property application.properties file:

mapper.url1=C:\\Program Files\\Java\\jdk1.8.0_111\\bin\\java.exe
mapper.url2=C:\\Program Files\\Java\\jdk1.8.0_111\\bin\\javaw.exe

and following bean, which reflection in java code:

@Component
@EnableConfigurationProperties
@ConfigurationProperties
public class ApplicationProperties {
    private Map<String, String> mapper;
    //get and set methods
    ....

Now I want to extend this format and add  timeout to the key.

I expect that the most readable(I do not insist, you can suggest another) format would be:

mapper.url1=C:\\Program Files\\Java\\jdk1.8.0_111\\bin\\java.exe
mapper.url1.timeOut=1000

How to extend my configuration to read this(or another with same power) format?

Where does correct place to validate it?

I want to validate property file format. Each key should contain both: path and timeout. Otherwise application should not be started

Body:
Use a nested class to represent the properties.

For example:

@ConfigurationProperties
public class DemoApplication {

    ...

    public static class UrlProperties {
        // use Path or File so it's type-safe
        private Path path;

        // use int for type-safety
        private int timeout;

        public Path getPath() {
            return path;
        }

        public void setPath(final Path path) {
            this.path = path;
        }

        public int getTimeout() {
            return timeout;
        }

        public void setTimeout(final int timeout) {
            this.timeout = timeout;
        }

        @Override
        public String toString() {
            return "UrlProperties{" + "path=" + path + ", timeout=" + timeout + '}';
        }
    }
}

and then define your Map instance variable with a String key and a value as the nested class type:

private Map<String, UrlProperties> mapper;

and use the properties like this:

mapper.url1.path=C:\\Program Files\\Java\\jdk1.8.0_111\\bin\\java.exe
mapper.url1.timeout=1000

mapper.url2.path=C:\\Program Files\\Java\\jdk1.8.0_111\\bin\\javaw.exe
mapper.url2.timeout=5000

You'll end up with objects that look like this:

{url2=UrlProperties{path=C:\Program Files\Java\jdk1.8.0_111\bin\javaw.exe, timeout=5000}, url1=UrlProperties{path=C:\Program Files\Java\jdk1.8.0_111\bin\java.exe, timeout=1000}}

Additionally, with Spring Boot 1.5, you can use JSR-303 annotations to validate your ConfigurationProperties. See here for more details.


问:
Failed to deploy project. For more information, query the operation_messages view for the operation identifier '20132'?
The Packages was deployed fine Initially , i have made few changes and try to deploy it again. i am receiving the following Error:

Failed to deploy project. For more information, query the operation_messages view for the operation identifier '20132'

When I query the SSIS DB with select * from catalog.operations_messages no rows are returned, just column headers are showing in the Data. Please help

答:
First, Refering to this Microsoft Link, This view requires one of the following permissions:

READ permission on the operation

Membership to the ssis_admin database role

Membership to the sysadmin server role

Check that you have the right permissions to access this view

Second, The SSISDB.catalog.operation_messages table stores the package execution log. If there is no package executed on this server, the SSISDB.catalog.operation_messages table will be empty.

And the package deployment log is stored in  [internal].[packages] table and [internal].[projects] table

You can use a similar query to read info from these tables:

```<code>select * from internal.packages a inner join internal.projects b on a.project_id = b.project_id
</code>```

Body:
First, Refering to this Microsoft Link, This view requires one of the following permissions:

READ permission on the operation

Membership to the ssis_admin database role

Membership to the sysadmin server role

Check that you have the right permissions to access this view

Second, The SSISDB.catalog.operation_messages table stores the package execution log. If there is no package executed on this server, the SSISDB.catalog.operation_messages table will be empty.

And the package deployment log is stored in  [internal].[packages] table and [internal].[projects] table

You can use a similar query to read info from these tables:

select * from internal.packages a inner join internal.projects b on a.project_id = b.project_id


问:
Unable to upload files with Flask on Heroku
I'm attempting to add a file addition button that uploads a file to a folder on my Flask Heroku app but I get an application error when I hit the submit button.

```<code>class PhotoForm(Form):
    photo = FileField('Your photo')
    submit = SubmitField('Submit')

@app.route('/upload', methods=('GET', 'POST'))
def upload():
    form = PhotoForm()
    if form.validate_on_submit():
        filename = secure_filename(form.photo.data.filename)
        form.photo.data.save("uploads/" + filename)
    else:
        filename = None
    return render_template('upload.html', form=form, filename=filename)
</code>```

Here is the upload.html:

```<code>{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block page_content %}
<form action="uploads/" method="POST" enctype="multipart/form-data">
    {{ wtf.quick_form(form)}}
</form>

{{filename}}
{% endblock %}
</code>```

Here is the error it throws:

```<code>2015-01-21T20:52:24.834249+00:00 heroku[router]: sock=backend at=error code=H18
desc="Request Interrupted" method=POST path="/uploads/" host=xxxx.h
erokuapp.com request_id=18dabdc3-400e-4c8b-ba8a-8d52d4cc1cb5 fwd="8.34.183.2" dy
no=web.1 connect=3ms service=6ms status=503 bytes=568
</code>```

答:
Heroku is interrupting the request to store data at uploads/ because  they prefer you use temporary storage at tmp/

Any tmp/ files will not be there when the dyno restarts because Heroku filesystems are ephemeral.

Following the 12-factor app principles, Heroku expects that if your app needs storage you'll use a storage service -- the popular solution is AWS S3 also available as an add-on.

Body:
I'm attempting to add a file addition button that uploads a file to a folder on my Flask Heroku app but I get an application error when I hit the submit button.

class PhotoForm(Form):
    photo = FileField('Your photo')
    submit = SubmitField('Submit')

@app.route('/upload', methods=('GET', 'POST'))
def upload():
    form = PhotoForm()
    if form.validate_on_submit():
        filename = secure_filename(form.photo.data.filename)
        form.photo.data.save("uploads/" + filename)
    else:
        filename = None
    return render_template('upload.html', form=form, filename=filename)

Here is the upload.html:

{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block page_content %}
<form action="uploads/" method="POST" enctype="multipart/form-data">
    {{ wtf.quick_form(form)}}
</form>

{{filename}}
{% endblock %}

Here is the error it throws:

2015-01-21T20:52:24.834249+00:00 heroku[router]: sock=backend at=error code=H18
desc="Request Interrupted" method=POST path="/uploads/" host=xxxx.h
erokuapp.com request_id=18dabdc3-400e-4c8b-ba8a-8d52d4cc1cb5 fwd="8.34.183.2" dy
no=web.1 connect=3ms service=6ms status=503 bytes=568


问:
functional rest api(node)test code coverage
I am trying to get code coverage for rest API endpoints written in node, but my functional(not unit) test cases calling these node end points are written in ruby and cucumber. Which approach should I use in this situation?
Thanks, appreciate your help!!</p>

答:
As long as you run an instrumented version of the classes, it shouldn't matter how they are executed. The coverage logging will still be executed.

My solution would be to

Make sure that the classes under test are properly instrumented using Cobertura or similar

Run the test suit

Collect all coverage files and generate a coverage report

This blog post describes a solution where a multi module Maven project is measured. It is somewhat related to your problem.


问:
pthread_join - multiple threads waiting
Using POSIX threads & C++, I have an "Insert operation" which can only be done safely one at a time.

If I have multiple threads waiting to insert using pthread_join then spawning a new thread
when it finishes. Will they all receive the "thread complete" signal at once and spawn multiple inserts or is it safe to assume that the thread that receives the "thread complete" signal first will spawn a new thread blocking the others from creating new threads.

```<code>/* --- GLOBAL --- */
pthread_t insertThread;

/* --- DIFFERENT THREADS --- */
// Wait for Current insert to finish
pthread_join(insertThread, NULL);

// Done start a new one
pthread_create(&insertThread, NULL, Insert, Data);
</code>```

Thank you for the replies

The program is basically a huge hash table which takes requests from clients through Sockets.

Each new client connection spawns a new thread from which it can then perform multiple operations, specifically lookups or inserts. lookups can be conducted in parallel. But inserts need to be "re-combined" into a single thread. You could say that lookup operations could be done without spawning a new thread for the client, however they can take a while causing the server to lock, dropping new requests. The design tries to minimize system calls and thread creation as much as possible.

But now that i know it's not safe the way i first thought I should be able to cobble something together

Thanks

答:
The only library which i found which supports inserts without locking new lookups - Sunrise DD (And i'm not sure whether it supports concurrent inserts)

However the switch from Google's Sparse Hash map more than doubles the memory usage. Lookups should happen fairly infrequently so rather than trying and write my own library
which combines the advantages of both i would rather just lock the table suspending lookups while changes are made safely.

Thanks again

Title: pthread_join - multiple threads waiting

Body:
Using POSIX threads & C++, I have an "Insert operation" which can only be done safely one at a time.

If I have multiple threads waiting to insert using pthread_join then spawning a new thread
when it finishes. Will they all receive the "thread complete" signal at once and spawn multiple inserts or is it safe to assume that the thread that receives the "thread complete" signal first will spawn a new thread blocking the others from creating new threads.

/* --- GLOBAL --- */
pthread_t insertThread;

/* --- DIFFERENT THREADS --- */
// Wait for Current insert to finish
pthread_join(insertThread, NULL);

// Done start a new one
pthread_create(&insertThread, NULL, Insert, Data);

Thank you for the replies

The program is basically a huge hash table which takes requests from clients through Sockets.

Each new client connection spawns a new thread from which it can then perform multiple operations, specifically lookups or inserts. lookups can be conducted in parallel. But inserts need to be "re-combined" into a single thread. You could say that lookup operations could be done without spawning a new thread for the client, however they can take a while causing the server to lock, dropping new requests. The design tries to minimize system calls and thread creation as much as possible.

But now that i know it's not safe the way i first thought I should be able to cobble something together

Thanks

LastEditorDisplayName: Hosam Aly


问:
MultiThreading Windows Application
Lets say i have a form with 2 textboxs

im in a different thread and i want to compine texts in those two textboxs i understand that i can invoke each one of them and get the value then concatenate them but

i was thinking of a way to invoke 2 controls at once without hanging the main thread.

, i tried invoking textboxes one by one  then get values but that hanged my main thread for some reasons

any idea of how to do that without hanging the main thread ?

Sample:

```<code>    txtFrom.Invoke(new MethodInvoker(() => strFrom = txtFrom.Text));
        txtTo.Invoke(new MethodInvoker(() => strTo = txtTo.Text));
        txtMessageBody.Invoke(new MethodInvoker(() => strMessageBody = txtMessageBody.Text));
        txtStartDate.Invoke(new MethodInvoker(() => strStartDate = txtStartDate.Text));
        txtEndDate.Invoke(new MethodInvoker(() => strEndDate = txtEndDate.Text));
        ddlStatus.Invoke(new MethodInvoker(() => intStatus = ddlStatus.SelectedIndex));
</code>```

thanks in advance

Enviroments:

Windows 7.
.Net 4
Windows Form
C#

答:
Can you use BeginInvoke instead? I always avoid Invoke because it has a habit of causing deadlocks, which will hang the application...

The reason for this is that Invoke makes your worker thread sit and wait until the UI thread is available. That can be a problem because there's a good chance that your UI thread was sitting waiting for your worker thread to do something. (For example, your worker thread may be in possession of locks, possibly ones you don't even know anything about because they are inside some library component. Implicit acquisition of locks or other unshareable resources can cause deadlocks even in single-thread code so it's best to be careful. It's almost always a terrible idea to make a worker thread wait for the UI thread to do something.)

As Peter Lillevold points out, ultimately you need to make sure you don't do anything slow on the UI thread. But it's not clear from your example code what's going on - I don't see anything obvious in your code that'll be slow, and from your description, it sounded like the application hangs completely, in which case it's more likely that you've got an Invoke-induced deadlock.

Title: MultiThreading Windows Application

Body:
Lets say i have a form with 2 textboxs

im in a different thread and i want to compine texts in those two textboxs i understand that i can invoke each one of them and get the value then concatenate them but

i was thinking of a way to invoke 2 controls at once without hanging the main thread.

, i tried invoking textboxes one by one  then get values but that hanged my main thread for some reasons

any idea of how to do that without hanging the main thread ?

Sample:

    txtFrom.Invoke(new MethodInvoker(() => strFrom = txtFrom.Text));
        txtTo.Invoke(new MethodInvoker(() => strTo = txtTo.Text));
        txtMessageBody.Invoke(new MethodInvoker(() => strMessageBody = txtMessageBody.Text));
        txtStartDate.Invoke(new MethodInvoker(() => strStartDate = txtStartDate.Text));
        txtEndDate.Invoke(new MethodInvoker(() => strEndDate = txtEndDate.Text));
        ddlStatus.Invoke(new MethodInvoker(() => intStatus = ddlStatus.SelectedIndex));

thanks in advance

Enviroments:

Windows 7.
.Net 4
Windows Form
C#


问:
Warning: A value is trying to be set on a copy of a slice from a DataFrame -- Using List of Columns
I am getting the following warning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

Here is my code that is getting the warning:

```<code>col_names = ['Column1', 'Column2']
features = X_train[col_names]
scaler = StandardScaler().fit(features.values)
features = scaler.transform(features.values)
X_train[col_names] = features
</code>```

I realize this is happening because I'm copying the dataframe. But what I am doing here is not like any of the answers I found googling, so I can't figure out how to apply their answers to my particular situation. It looks like the normal scenario where you get this warning is if you do something like this:
d2 = data[data['name'] == 'fred']

So .loc doesn't work. And .assign doesn't either because I have a list of columns instead of just a column I can assign. I'm just not quite sure how to handle this the way it wants me too.

It works fine the way it is, other than the warning. So the way I have it is correct.

答:
I think the warning is saying for you to do something like</p>

```<code>X_train.loc[:, col_names] = features
</code>```

Body:
I am getting the following warning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

Here is my code that is getting the warning:

col_names = ['Column1', 'Column2']
features = X_train[col_names]
scaler = StandardScaler().fit(features.values)
features = scaler.transform(features.values)
X_train[col_names] = features

I realize this is happening because I'm copying the dataframe. But what I am doing here is not like any of the answers I found googling, so I can't figure out how to apply their answers to my particular situation. It looks like the normal scenario where you get this warning is if you do something like this:
d2 = data[data['name'] == 'fred']

So .loc doesn't work. And .assign doesn't either because I have a list of columns instead of just a column I can assign. I'm just not quite sure how to handle this the way it wants me too.

It works fine the way it is, other than the warning. So the way I have it is correct.

Body:
I think the warning is saying for you to do something like

X_train.loc[:, col_names] = features