问:
Xcode 9 "could not build module ‘Foundation’"
When I archive an iPhone project, it returns a failure:

Could not build module "Foundation".

However, when I debug on the iPhone, it runs successfully.

I tried to set ‘Enable Modules’ to No and it seems normal, but another 3rd party library I'm using requires modules be turned on.

What do I do in that case? How do I import social now?

答: Set to YES target's Allow Non-modular Includes in Framework Modules in Build Settings.


来源: stackexchange

问:
Getting file name out of a string
I need to get the filename 'HomeModel' out of a string app\model\common\HomeModel. This is what I tried

First, replace '\' with '/' using the str_replace.

```<code>$model = 'app\model\common\HomeModel';
$file = str_replace("\\", '/', $model) . ".php";
echo $file;
</code>```

the result

```<code>app/model/common/HomeModel.php
</code>```

then I explode the result like so

```<code>$model = 'app\model\common\HomeModel';
$file = str_replace("\\", '/', $model) . ".php";
echo $file;

$result = explode("/", $file);
echo '<br>';
var_dump($result);
</code>```

and then this is what I have

```<code>array (size=4)
  0 => string 'app' (length=3)
  1 => string 'model' (length=5)
  2 => string 'common' (length=6)
  3 => string 'HomeModel.php' (length=18)
</code>```

Now, how do I get the last value 'HomeModel' out of this array for further use?, I need to assign the value 'HomeModel' to $class.

答:
While end() is the answer to this specific question, I would encourage other members to try a better approach regarding the case of breaking a path to its parts using the php function pathinfo().

```<code>$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');
echo $path_parts['basename']; // since PHP 5.2.0. Output: lib.inc.php
</code>```

In your example, just use the first str_replace so it would be a valid path and manually add the php extension to the string.

ContentLicense: CC BY-SA 3.0

Title: Getting file name out of a string

Body:
I need to get the filename 'HomeModel' out of a string app\model\common\HomeModel. This is what I tried

First, replace '\' with '/' using the str_replace.

$model = 'app\model\common\HomeModel';
$file = str_replace("\\", '/', $model) . ".php";
echo $file;

the result

app/model/common/HomeModel.php

then I explode the result like so

$model = 'app\model\common\HomeModel';
$file = str_replace("\\", '/', $model) . ".php";
echo $file;

$result = explode("/", $file);
echo '
';
var_dump($result);

and then this is what I have

array (size=4)
  0 => string 'app' (length=3)
  1 => string 'model' (length=5)
  2 => string 'common' (length=6)
  3 => string 'HomeModel.php' (length=18)

Now, how do I get the last value 'HomeModel' out of this array for further use?, I need to assign the value 'HomeModel' to $class.

Body:
While end() is the answer to this specific question, I would encourage other members to try a better approach regarding the case of breaking a path to its parts using the php function pathinfo().

$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');
echo $path_parts['basename']; // since PHP 5.2.0. Output: lib.inc.php

In your example, just use the first str_replace so it would be a valid path and manually add the php extension to the string.


问:
smarty not working on new server PHP Version 5.2.6
Warning: preg_match() [function.preg-match]: Compilation failed: repeated subpattern is too long at offset 18454 in /Smarty_Compiler.class.php on line 454

Fatal error: Smarty error: [in login.tpl line 1]: syntax error: unrecognized tag: php (Smarty_Compiler.class.php, line 455)

this message coming.. it was working perfect on dev server but on live server its not working.

Dev php version was  5.2.14
new server has PHP Version 5.2.6

is this the problem?

答:
What smarty version are you using?

This thread seems to imply it has to do with a combination of Smarty versions and php version:
http://www.smarty.net/forums/viewtopic.php?t=14563

For most users the sollution seems to be to downgrade Smarty from 2.6.21 to 2.6.20

It's kind of an old thread though, so check if it applies, but it seems akin to your problem.

ContentLicense: CC BY-SA 2.5


问:
SoapUI GroovyScript assertion within (+ or - ) 0.05 of expected values
I currently have the following assertion script to check the value of three fields.

```<code>import org.junit.Assert

def response = messageExchange.getResponseContent()
def xml = new XmlSlurper().parseText(response)
def nodelist = xml.'**'.findAll{ it.name() == 'premium' }
def assertions = [6.19, 6.47, 6.90]
def i=0

for (node in nodelist) assert node.toString().matches(assertions[i++].toString())
</code>```

I am trying to get it so that the assertion will pass in the actual value is within 0.05 either side of the expected value.

The following script works when there is one value, but I am struggling to implement it with the assertion above.

```<code>import org.junit.Assert
// get the xml response
def response = messageExchange.getResponseContent()
// parse it
def xml = new XmlSlurper().parseText(response)
// find your node by name
def node = xml.'**'.find { it.name() == 'premium' }
// assert
if(node.toDouble() != 0.0)
    Assert.assertEquals(0.00, node.toDouble(), 0.05)
</code>```

Edit

Sample Response:

```<code><b:quote-data>
    <b:quote-data>
      <b:premium>6.13</b:premium>
    </b:quote-data>
    <b:quote-data>
      <b:premium>6.45</b:premium>
    </b:quote-data>
    <b:quote-data>
      <b:premium>6.91</b:premium>
    </b:quote-data>
 </b:quote-data>
</code>```

答:
Here are couple of things for failure in your case.

When you define a list as below, it considers each value type as BigDecimal type.

The extracted values should be coerced to the same type before comparison.

Here is the sample to achieve the above:

```<code>def expectedPremiums = [6.19, 6.47, 6.90]
def xmlString = """<root xmlns:b="test">
 <b:quote-data>
       <b:premium>6.13</b:premium>
     </b:quote-data>
     <b:quote-data>
       <b:premium>6.45</b:premium>
     </b:quote-data>
     <b:quote-data>
       <b:premium>6.91</b:premium>
    </b:quote-data>
</root>"""
def xml = new XmlSlurper().parseText(xmlString)
def premiums = xml.'**'.findAll {it.name() == 'premium'}*.toBigDecimal()
println premiums
</code>```

Note that using sample fixed xml, you can use to for dynamic response like you are already doing.

If you also need the logic for validation with tolerance, then use below along with above script.

```<code>def tolerance = 0.05
def failurePremiums = [:]
expectedPremiums.eachWithIndex { expected, index ->
   if ((expected-tolerance) <= premiums[index] && premiums[index] <= (expected+tolerance)) {
     println "${premiums[index]} is in range"
   } else {
      println "${premiums[index]} is not falling in range, failed"
      failurePremiums[expected] = premiums[index]
   }
}
assert !failurePremiums, "Not matched data(expected vs actual) :  ${failurePremiums}"
</code>```

You can quickly try it online demo

EDIT: Another suggestion

When you are using script assertion, you can change below:

From:

```<code>def response = messageExchange.getResponseContent()
def xml = new XmlSlurper().parseText(response)
</code>```

To:

```<code>def xml = new XmlSlurper().parseText(context.response)
</code>```

Body:
I currently have the following assertion script to check the value of three fields.

import org.junit.Assert

def response = messageExchange.getResponseContent()
def xml = new XmlSlurper().parseText(response)
def nodelist = xml.'**'.findAll{ it.name() == 'premium' }
def assertions = [6.19, 6.47, 6.90]
def i=0

for (node in nodelist) assert node.toString().matches(assertions[i++].toString())

I am trying to get it so that the assertion will pass in the actual value is within 0.05 either side of the expected value.

The following script works when there is one value, but I am struggling to implement it with the assertion above.

import org.junit.Assert
// get the xml response
def response = messageExchange.getResponseContent()
// parse it
def xml = new XmlSlurper().parseText(response)
// find your node by name
def node = xml.'**'.find { it.name() == 'premium' }
// assert
if(node.toDouble() != 0.0)
    Assert.assertEquals(0.00, node.toDouble(), 0.05)

Edit

Sample Response:

      6.13

      6.45

      6.91

Body:
Here are couple of things for failure in your case.

When you define a list as below, it considers each value type as BigDecimal type.

The extracted values should be coerced to the same type before comparison.

Here is the sample to achieve the above:

def expectedPremiums = [6.19, 6.47, 6.90]
def xmlString = """<root xmlns:b="test">
 <b:quote-data>
       <b:premium>6.13</b:premium>
     </b:quote-data>
     <b:quote-data>
       <b:premium>6.45</b:premium>
     </b:quote-data>
     <b:quote-data>
       <b:premium>6.91</b:premium>
    </b:quote-data>
</root>"""
def xml = new XmlSlurper().parseText(xmlString)
def premiums = xml.'**'.findAll {it.name() == 'premium'}*.toBigDecimal()
println premiums

Note that using sample fixed xml, you can use to for dynamic response like you are already doing.

If you also need the logic for validation with tolerance, then use below along with above script.

def tolerance = 0.05
def failurePremiums = [:]
expectedPremiums.eachWithIndex { expected, index ->
   if ((expected-tolerance) <= premiums[index] && premiums[index] <= (expected+tolerance)) {
     println "${premiums[index]} is in range"
   } else {
      println "${premiums[index]} is not falling in range, failed"
      failurePremiums[expected] = premiums[index]
   }
}
assert !failurePremiums, "Not matched data(expected vs actual) :  ${failurePremiums}"

You can quickly try it online demo

EDIT: Another suggestion

When you are using script assertion, you can change below:

From:

def response = messageExchange.getResponseContent()
def xml = new XmlSlurper().parseText(response)

To:

def xml = new XmlSlurper().parseText(context.response)


答:
Try this one, </p>

```<code>$class = $result[count($result)-1];
</code>```

Title: Getting file name out of a string

Body:
Try this one,

$class = $result[count($result)-1];


问:
i have 3 div one after another in horizontal way. when resize it shows div3, div2, and div1
I have problem to achieve design. I have 3 divs: one after another in horizontal way say div1, div2 and div3. When it goes on small device it shows div3, div2, and div1. How can I achieve using HTML, CSS.

I have attached an image for reference.

答:
You can use flex for that.

* { box-sizing: border-box; margin: 0; padding: 0; }
.box {
  border: 1px solid black;
  display: flex;
}
.box > div {
  border: 1px solid red;
  width: 33%;
  height: 150px;
}

@media screen and (max-width: 400px)  {
  .box {
    flex-direction: column-reverse;
  }
  .box > div {
    width: 100%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <div class="div1">DIV 1</div>
  <div class="div2">DIV 2</div>
  <div class="div3">DIV 3</div>
</div></code>```

You can see a demo here: https://jsfiddle.net/75tsv8bp/

Make the result window smaller to see it working...

Body:
You can use flex for that.

* { box-sizing: border-box; margin: 0; padding: 0; }
.box {
  border: 1px solid black;
  display: flex;
}
.box > div {
  border: 1px solid red;
  width: 33%;
  height: 150px;
}

@media screen and (max-width: 400px)  {
  .box {
    flex-direction: column-reverse;
  }
  .box > div {
    width: 100%;
  }
}

<div class="box">
  <div class="div1">DIV 1</div>
  <div class="div2">DIV 2</div>
  <div class="div3">DIV 3</div>
</div>

You can see a demo here: https://jsfiddle.net/75tsv8bp/

Make the result window smaller to see it working...


问:
NServiceBus TimeOut Manager
I was developing  a sample application to test the timeout management in saga using NserviceBus.

I am tryin to achieve the following

When a saga started set it's timeout to 1 minute
Before the timeout happens if an update came to the nessage updates the timeout to 5 minutes
My code is like below

```<code>  public class OrderSaga : Saga<OrderSagaData>,
        IAmStartedByMessages<SampleMessage>,
        IHandleMessages<UpdateMessage>
    {
        public override void ConfigureHowToFindSaga()
        {
            ConfigureMapping<UpdateMessage>(s => s.PurchaseOrderNumber, m => m.Update);
        }

        public void Handle(SampleMessage message)
        {
            this.Data.PurchaseOrderNumber = message.Name;
            RequestTimeout(DateTime.Now.AddMinutes(1), message.Name);
        }

        private void Complete()
        {
            MarkAsComplete();
        }

        public override void Timeout(object state)
        {
            Complete();
        }

        #region IMessageHandler<UpdateMessage> Members

        public void Handle(UpdateMessage message)
        {
            this.Data.PurchaseOrderNumber = message.NewValue;
            RequestTimeout(DateTime.Now.AddMinutes(5), message.Update);
        }

        #endregion
    }
}
</code>```

But here the problem is the timeout is not getting updated to 5 minutes.The timeout still works for 1 minute.

Could you please let me know what is doing wrong here?

Thanks in advance,
Ajai

答:
Saga timeouts can't be updated. They will fire no matter what you do. In your case you will receive both timeouts and given that you call Complete in your timeout handler your saga will end after one minute. You need to add some logic in that takes this into account.

Something like this might do it:

```
if(!updateReceived or state == ThisTimeoutWasRequestedByMyUpdateHandler)
   Complete();
```

Hope this helps!

Title: NServiceBus TimeOut Manager

Body:
I was developing  a sample application to test the timeout management in saga using NserviceBus.

I am tryin to achieve the following

When a saga started set it's timeout to 1 minute
Before the timeout happens if an update came to the nessage updates the timeout to 5 minutes
My code is like below

  public class OrderSaga : Saga<OrderSagaData>,
        IAmStartedByMessages<SampleMessage>,
        IHandleMessages<UpdateMessage>
    {
        public override void ConfigureHowToFindSaga()
        {
            ConfigureMapping<UpdateMessage>(s => s.PurchaseOrderNumber, m => m.Update);
        }

        public void Handle(SampleMessage message)
        {
            this.Data.PurchaseOrderNumber = message.Name;
            RequestTimeout(DateTime.Now.AddMinutes(1), message.Name);
        }

        private void Complete()
        {
            MarkAsComplete();
        }

        public override void Timeout(object state)
        {
            Complete();
        }

        #region IMessageHandler<UpdateMessage> Members

        public void Handle(UpdateMessage message)
        {
            this.Data.PurchaseOrderNumber = message.NewValue;
            RequestTimeout(DateTime.Now.AddMinutes(5), message.Update);
        }

        #endregion
    }
}

But here the problem is the timeout is not getting updated to 5 minutes.The timeout still works for 1 minute.

Could you please let me know what is doing wrong here?

Thanks in advance,
Ajai

Body:
Saga timeouts can't be updated. They will fire no matter what you do. In your case you will receive both timeouts and given that you call Complete in your timeout handler your saga will end after one minute. You need to add some logic in that takes this into account.

Something like this might do it:

if(!updateReceived or state == ThisTimeoutWasRequestedByMyUpdateHandler)
   Complete();

Hope this helps!


问:
how to access dataTable variable outside ajax
I have this datatable that is created inside a function call. But if I want to create new rows based on event listeners like this, it gives an error that the table variable is undefined, which is understandable because it is inside a function call and not global. So how do I create a workaround for this and add event listeners under $(document).ready() section?

The structure of my JS file is very shabby, but it's intended to be in that way.

```<code>$(document).ready(function()
{
     var table=null;
     $('#button').click(function()
     {
         callfunction1();
     }
     callfunction1()
     {
         $.ajax({
              'success': function(response) //response contains the plain table
                         {
                             createDatatable(response)
                         }
         })
     }
     createDatatable(response)
     {
            $('#division').html(response); //creating the plain table
            table=$('#tableId').Datatable({}); //converting it to datatable
     }
     //I want to add event listeners here, because if I add
     //it anywhere else, it doesn't work, because basically
     //it's a function call.
}
</code>```

答:
You can create a instance of the table var in a wider scope, example:

```<code>//the table is now a window object variable window.table
var table = null;
$(document).ready(function()
{
     $('#button').click(function()
     {
         callfunction1();
     }
     callfunction1()
     {
         $.ajax({
              'success': createDatatable()
         })
     }
     createDatatable()
     {
            table=$('#tableId').Datatable({})
     }

     //the table is binded in the window scope so you can use in your event listeners
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have this datatable that is created inside a function call. But if I want to create new rows based on event listeners like this, it gives an error that the table variable is undefined, which is understandable because it is inside a function call and not global. So how do I create a workaround for this and add event listeners under $(document).ready() section?

The structure of my JS file is very shabby, but it's intended to be in that way.

$(document).ready(function()
{
     var table=null;
     $('#button').click(function()
     {
         callfunction1();
     }
     callfunction1()
     {
         $.ajax({
              'success': function(response) //response contains the plain table
                         {
                             createDatatable(response)
                         }
         })
     }
     createDatatable(response)
     {
            $('#division').html(response); //creating the plain table
            table=$('#tableId').Datatable({}); //converting it to datatable
     }
     //I want to add event listeners here, because if I add
     //it anywhere else, it doesn't work, because basically
     //it's a function call.
}

Body:
You can create a instance of the table var in a wider scope, example:

//the table is now a window object variable window.table
var table = null;
$(document).ready(function()
{
     $('#button').click(function()
     {
         callfunction1();
     }
     callfunction1()
     {
         $.ajax({
              'success': createDatatable()
         })
     }
     createDatatable()
     {
            table=$('#tableId').Datatable({})
     }

     //the table is binded in the window scope so you can use in your event listeners
}


问:
Keras ValueError: Error when checking model target: expected dense_18
I am all done, just stuck in training my NN model in KERAS.
Here is my situation.

I have a folder, i have 30 CSV files in there , all different name.

Now, I am doing classification.

Each CSV file (5000,3 after reading in an array dfs as shown below is a single training instance itself, ,so I have 30 training instances for 30 CSVs).

The filename is the label, I want to classify. Theses are 3 unique labels, use one hot encoding.

I am confused in the input shape and how to reshape my training data dfs in a correct shape.

Note: 30 observations which are CSV files themselves of 5000, 3 dim and filename is the label.

Here is my code and error.

```<code>import os
import glob
import pandas as pd
import numpy as np
from keras.preprocessing.text import one_hot
from keras.models import Sequential
from keras.layers import Dense

path = os.getcwd()
file_list = glob.glob(path + '/*.csv')
dfs=np.array([pd.read_csv(fp).values for fp in file_list])

dfs.shape
# (30, 5000, 3)

from sklearn.preprocessing import OneHotEncoder
# define class labels

labels = np.array([1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3])

onehot_encoder = OneHotEncoder(sparse=False)
integer_encoded = labels.reshape(len(labels), 1)
onehot_encoded = onehot_encoder.fit_transform(integer_encoded)

len(onehot_encoded)
print(onehot_encoded)
# 30
array([[ 1.,  0.,  0.],
       [ 1.,  0.,  0.],
       [ 1.,  0.,  0.],
       [ 1.,  0.,  0.],
       [ 1.,  0.,  0.],
       [ 1.,  0.,  0.],
       [ 1.,  0.,  0.],
       [ 1.,  0.,  0.],
       [ 1.,  0.,  0.],
       [ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.],
       [ 0.,  0.,  1.],
       [ 0.,  0.,  1.],
       [ 0.,  0.,  1.],
       [ 0.,  0.,  1.],
       [ 0.,  0.,  1.],
       [ 0.,  0.,  1.],
       [ 0.,  0.,  1.],
       [ 0.,  0.,  1.],
       [ 0.,  0.,  1.]])

model = Sequential()
model.add(Dense(24, input_shape=(5000,3), activation='relu'))
model.add(Dense(8))
model.add(Dense(3, activation='sigmoid'))
# compile the model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc'])

# summarize the model
print(model.summary())

# fit the model
model.fit(dfs, onehot_encoded, epochs=50, verbose=2)
</code>```

ERROR:
ValueError: Error when checking model target: expected dense_10 to have 3 dimensions, but got array with shape (30, 3)

答:
Your labels array is of shape (30,3), while your model is expecting it to be (None, 5000, 3). -- Always check the model.summary() to understand what is going on with shapes.

The Dense layers work only on the last dimension, leaving all other dimensions untouched. Since your input is (None, 5000, 3), all your Dense layers are transforming only the last dimension and leaving the 5000 untouched.

At some point in the model, you must get rid of the extra dimension so you can match your labels, which are (None, 3).

There are many possibilities, but the best option depends on how you want the model to interpret data.

Option 1:

If all the 5000 lines are completely independent and of different nature (and the model shouldn't learn any common behavioer between these lines), you can add a Flatten() layer at the beginning of the model, so it will immediately become (None, 15000).

```<code>model.add(Flatten(input_shape=(5000,3))) #first layer in the model
</code>```

Option 2:

Now, if the 5000 lines share something in common, and your model should treat them as if they were different samples of equal nature, put the Flatten() layer at the end, just before the last Dense.

Example:

```<code>model = Sequential()
model.add(Dense(24, input_shape=(5000,3), activation='relu'))
model.add(Dense(8))

#the flatten layer comes here:
model.add(Flatten())
model.add(Dense(3, activation='sigmoid'))
</code>```

Option 3:

If these lines are forming a sequence (time series), and you want somehow to learn how this sequence evolves, you're probably going to have better results changing your Dense layers by LSTM layers. All of them, except for the last one, should use return_sequences = True.

Example:

```<code>model = Sequential()
model.add(LSTM(24, return_sequences=True,input_shape=(5000,3)))
model.add(LSTM(8,return_sequences=True))

#here there are many possibilities as well, one of them being just another LSTM layer without return sequences:
model.add(LSTM(3,return_sequences=False))
model.add(Activation('sigmoid'))
</code>```

I used the activation in a separate layer because the LSTM's usually work better with their default activation, which is 'tanh'.

Body:
I am all done, just stuck in training my NN model in KERAS.
Here is my situation.

I have a folder, i have 30 CSV files in there , all different name.

Now, I am doing classification.

Each CSV file (5000,3 after reading in an array dfs as shown below is a single training instance itself, ,so I have 30 training instances for 30 CSVs).

The filename is the label, I want to classify. Theses are 3 unique labels, use one hot encoding.

I am confused in the input shape and how to reshape my training data dfs in a correct shape.

Note: 30 observations which are CSV files themselves of 5000, 3 dim and filename is the label.

Here is my code and error.

import os
import glob
import pandas as pd
import numpy as np
from keras.preprocessing.text import one_hot
from keras.models import Sequential
from keras.layers import Dense

path = os.getcwd()
file_list = glob.glob(path + '/*.csv')
dfs=np.array([pd.read_csv(fp).values for fp in file_list])

dfs.shape
# (30, 5000, 3)

from sklearn.preprocessing import OneHotEncoder
# define class labels

labels = np.array([1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3])

onehot_encoder = OneHotEncoder(sparse=False)
integer_encoded = labels.reshape(len(labels), 1)
onehot_encoded = onehot_encoder.fit_transform(integer_encoded)

len(onehot_encoded)
print(onehot_encoded)
# 30
array([[ 1.,  0.,  0.],
       [ 1.,  0.,  0.],
       [ 1.,  0.,  0.],
       [ 1.,  0.,  0.],
       [ 1.,  0.,  0.],
       [ 1.,  0.,  0.],
       [ 1.,  0.,  0.],
       [ 1.,  0.,  0.],
       [ 1.,  0.,  0.],
       [ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.],
       [ 0.,  0.,  1.],
       [ 0.,  0.,  1.],
       [ 0.,  0.,  1.],
       [ 0.,  0.,  1.],
       [ 0.,  0.,  1.],
       [ 0.,  0.,  1.],
       [ 0.,  0.,  1.],
       [ 0.,  0.,  1.],
       [ 0.,  0.,  1.]])

model = Sequential()
model.add(Dense(24, input_shape=(5000,3), activation='relu'))
model.add(Dense(8))
model.add(Dense(3, activation='sigmoid'))
# compile the model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc'])

# summarize the model
print(model.summary())

# fit the model
model.fit(dfs, onehot_encoded, epochs=50, verbose=2)

ERROR:
ValueError: Error when checking model target: expected dense_10 to have 3 dimensions, but got array with shape (30, 3)

Body:
Your labels array is of shape (30,3), while your model is expecting it to be (None, 5000, 3). -- Always check the model.summary() to understand what is going on with shapes.

The Dense layers work only on the last dimension, leaving all other dimensions untouched. Since your input is (None, 5000, 3), all your Dense layers are transforming only the last dimension and leaving the 5000 untouched.

At some point in the model, you must get rid of the extra dimension so you can match your labels, which are (None, 3).

There are many possibilities, but the best option depends on how you want the model to interpret data.

Option 1:

If all the 5000 lines are completely independent and of different nature (and the model shouldn't learn any common behavioer between these lines), you can add a Flatten() layer at the beginning of the model, so it will immediately become (None, 15000).

model.add(Flatten(input_shape=(5000,3))) #first layer in the model

Option 2:

Now, if the 5000 lines share something in common, and your model should treat them as if they were different samples of equal nature, put the Flatten() layer at the end, just before the last Dense.

Example:

model = Sequential()
model.add(Dense(24, input_shape=(5000,3), activation='relu'))
model.add(Dense(8))

#the flatten layer comes here:
model.add(Flatten())
model.add(Dense(3, activation='sigmoid'))

Option 3:

If these lines are forming a sequence (time series), and you want somehow to learn how this sequence evolves, you're probably going to have better results changing your Dense layers by LSTM layers. All of them, except for the last one, should use return_sequences = True.

Example:

model = Sequential()
model.add(LSTM(24, return_sequences=True,input_shape=(5000,3)))
model.add(LSTM(8,return_sequences=True))

#here there are many possibilities as well, one of them being just another LSTM layer without return sequences:
model.add(LSTM(3,return_sequences=False))
model.add(Activation('sigmoid'))

I used the activation in a separate layer because the LSTM's usually work better with their default activation, which is 'tanh'.


问:
Conversion of BitmapImage to Byte array
I want to convert a BitmapImage to ByteArray in a Windows Phone 7 Application. So I tried this but it throws the runtime Exception "Invalid Pointer Exception". Can anyone explain why what I'm trying to do throws an exception. And can you provide an alternative solution for this. </p>

<pre class="lang-cs prettyprint-override"><code>    public static byte[] ConvertToBytes(this BitmapImage bitmapImage)
    {
        byte[] data;
        // Get an Image Stream
        using (MemoryStream ms = new MemoryStream())
        {
            WriteableBitmap btmMap = new WriteableBitmap(bitmapImage);

            // write an image into the stream
            Extensions.SaveJpeg(btmMap, ms,
                bitmapImage.PixelWidth, bitmapImage.PixelHeight, 0, 100);

            // reset the stream pointer to the beginning
            ms.Seek(0, 0);
            //read the stream into a byte array
            data = new byte[ms.Length];
            ms.Read(data, 0, data.Length);
        }
        //data now holds the bytes of the image
        return data;
    }
</code>```

答:
Well I can make the code you've got considerably simpler:

```<code>public static byte[] ConvertToBytes(this BitmapImage bitmapImage)
{
    using (MemoryStream ms = new MemoryStream())
    {
        WriteableBitmap btmMap = new WriteableBitmap
            (bitmapImage.PixelWidth, bitmapImage.PixelHeight);

        // write an image into the stream
        Extensions.SaveJpeg(btmMap, ms,
            bitmapImage.PixelWidth, bitmapImage.PixelHeight, 0, 100);

        return ms.ToArray();
    }
}
</code>```

... but that probably won't solve the problem.

Another issue is that you're only ever using the size of bitmapImage - shouldn't you be copying that onto btmMap at some point?

Is there any reason you're not just using this:

```<code>WriteableBitmap btmMap = new WriteableBitmap(bitmapImage);
</code>```

Can you give us more information about where the error occurs?

Title: Conversion of BitmapImage to Byte array

Body:
I want to convert a BitmapImage to ByteArray in a Windows Phone 7 Application. So I tried this but it throws the runtime Exception "Invalid Pointer Exception". Can anyone explain why what I'm trying to do throws an exception. And can you provide an alternative solution for this.

    public static byte[] ConvertToBytes(this BitmapImage bitmapImage)
    {
        byte[] data;
        // Get an Image Stream
        using (MemoryStream ms = new MemoryStream())
        {
            WriteableBitmap btmMap = new WriteableBitmap(bitmapImage);

            // write an image into the stream
            Extensions.SaveJpeg(btmMap, ms,
                bitmapImage.PixelWidth, bitmapImage.PixelHeight, 0, 100);

            // reset the stream pointer to the beginning
            ms.Seek(0, 0);
            //read the stream into a byte array
            data = new byte[ms.Length];
            ms.Read(data, 0, data.Length);
        }
        //data now holds the bytes of the image
        return data;
    }

Body:
Well I can make the code you've got considerably simpler:

public static byte[] ConvertToBytes(this BitmapImage bitmapImage)
{
    using (MemoryStream ms = new MemoryStream())
    {
        WriteableBitmap btmMap = new WriteableBitmap
            (bitmapImage.PixelWidth, bitmapImage.PixelHeight);

        // write an image into the stream
        Extensions.SaveJpeg(btmMap, ms,
            bitmapImage.PixelWidth, bitmapImage.PixelHeight, 0, 100);

        return ms.ToArray();
    }
}

... but that probably won't solve the problem.

Another issue is that you're only ever using the size of bitmapImage - shouldn't you be copying that onto btmMap at some point?

Is there any reason you're not just using this:

WriteableBitmap btmMap = new WriteableBitmap(bitmapImage);

Can you give us more information about where the error occurs?


问:
Convert UTC to current locale time
I am downloading some JSON data from a webservice. In this JSON I've got some Date/Time values. Everything in UTC.
How can I parse this date string so the result Date object is in the current locale?

For example: the Server returned "2011-05-18 16:35:01" and my device should now display "2011-05-18 18:35:01" (GMT +2)

My current code:

```
<code>SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date myDate = simpleDateFormat.parse(rawQuestion.getString("AskDateTime"));</code>
```

答:
java.time

I should like to contribute the modern answer. Most of the other answers are correct and were fine answers in 2011. Today SimpleDateFormat is long outdated, and it always came with some surprises. And today we have so much better: java.time also known as JSR-310, the modern Java date and time API. This answer is for anyone who either accepts an external dependency (just until java.time comes to your Android device) or is already using Java 8 or later.

```<code>    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
    String dateTimeFromServer = "2011-05-18 16:35:01";
    String localTimeToDisplay = LocalDateTime.parse(dateTimeFromServer, formatter)
            .atOffset(ZoneOffset.UTC)
            .atZoneSameInstant(ZoneId.of("Europe/Zurich"))
            .format(formatter);
</code>```

The result of this code snippet is what was asked for:

```<code>2011-05-18 18:35:01
</code>```

Give explicit time zone if you can

I have given an explicit time zone of Europe/Zurich. Please substitute your desired local time zone. To rely on your device’s time zone setting, use ZoneId.systemDefault(). However, be aware that this is fragile because it takes the time zone setting from the JVM, and that setting could be changed under our feet by other parts of your program or other programs running in the same JVM.

Using java.time on Android

I promised you an external dependency. To use the above on Android you need the ThreeTenABP, the Android edition of ThreeTen Backport, the backport of JSR-310 to Java 6 and 7. How to go about it is nicely and thoroughly explained in this question: How to use ThreeTenABP in Android Project.

Title: Convert UTC to current locale time

Body:
I am downloading some JSON data from a webservice. In this JSON I've got some Date/Time values. Everything in UTC.
How can I parse this date string so the result Date object is in the current locale?

For example: the Server returned "2011-05-18 16:35:01" and my device should now display "2011-05-18 18:35:01" (GMT +2)

My current code:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date myDate = simpleDateFormat.parse(rawQuestion.getString("AskDateTime"));

Body:
java.time

I should like to contribute the modern answer. Most of the other answers are correct and were fine answers in 2011. Today SimpleDateFormat is long outdated, and it always came with some surprises. And today we have so much better: java.time also known as JSR-310, the modern Java date and time API. This answer is for anyone who either accepts an external dependency (just until java.time comes to your Android device) or is already using Java 8 or later.

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
    String dateTimeFromServer = "2011-05-18 16:35:01";
    String localTimeToDisplay = LocalDateTime.parse(dateTimeFromServer, formatter)
            .atOffset(ZoneOffset.UTC)
            .atZoneSameInstant(ZoneId.of("Europe/Zurich"))
            .format(formatter);

The result of this code snippet is what was asked for:

2011-05-18 18:35:01

Give explicit time zone if you can

I have given an explicit time zone of Europe/Zurich. Please substitute your desired local time zone. To rely on your device’s time zone setting, use ZoneId.systemDefault(). However, be aware that this is fragile because it takes the time zone setting from the JVM, and that setting could be changed under our feet by other parts of your program or other programs running in the same JVM.

Using java.time on Android

I promised you an external dependency. To use the above on Android you need the ThreeTenABP, the Android edition of ThreeTen Backport, the backport of JSR-310 to Java 6 and 7. How to go about it is nicely and thoroughly explained in this question: How to use ThreeTenABP in Android Project.


问:
Split elements of a list and retrieve only the first part from the split
I have a list say

```<code>List<string> someList = new List{"1-30","20-10","21-23","34-80"};
</code>```

I need to split the list so I have with following values

```<code> {"1","20","21","34"};
</code>```

I tried

```<code> someList
   .SelectMany(n => n.Split('-')[0])
   .ToList();
</code>```

But it is not giving me the desired result.

UPDATE:
Sorry everyone, Using Select solved my issue. One of those days, when you make silly mistakes

答:
You don't need to use selectMany since you don't need to flatten your list. Using Select will return each string in the list

{"1-30", "20-100"...etc}

. Using SelectMany will actually flatten the strings into a sequence of chars resulting in

{"1", "-", "3", "0" ...etc}

So your split will result in the wrong result.

.

You just select each item in your list, split the item on the '-' char and select the first result from the split. This should give you the correct result.

```<code>List<string> someList = new List<string> { "1-30", "20-100", "21-23", "34-80" };
var splitString = someList.Select(x => x.Split('-').First()).ToList();
</code>```

Body:
I have a list say

List<string> someList = new List{"1-30","20-10","21-23","34-80"};

I need to split the list so I have with following values

 {"1","20","21","34"};

I tried

 someList
   .SelectMany(n => n.Split('-')[0])
   .ToList();

But it is not giving me the desired result.

UPDATE:
Sorry everyone, Using Select solved my issue. One of those days, when you make silly mistakes

Body:
You don't need to use selectMany since you don't need to flatten your list. Using Select will return each string in the list

{"1-30", "20-100"...etc}

. Using SelectMany will actually flatten the strings into a sequence of chars resulting in

{"1", "-", "3", "0" ...etc}

So your split will result in the wrong result.

.

You just select each item in your list, split the item on the '-' char and select the first result from the split. This should give you the correct result.

List<string> someList = new List<string> { "1-30", "20-100", "21-23", "34-80" };
var splitString = someList.Select(x => x.Split('-').First()).ToList();


问:
adminer only displays one database
I download Adminer 4.2.5  from https://www.adminer.org/#download which is just one php file around 414 kB in size. I placed this in /localhost/ and was able to log in to database without any issues. But the only problem is that, I have about 24 databases, and adminer only shows tables and contents from 1 database.

This database also happens to be the first one indexed as it starts with letters ab.. so I am guessing it is only grabbing it, but this is not the database I want to fetch. Is there any solution for this?

答:
Adminer will only ever show one database at a time.

You can switch databases very simply, by using the standard links at the top of your screen (just to the left of your "logout" button). I.e.:

```<code>MySQL » Server » yourDatabaseName » Table: yourTableName
</code>```

In this example, clicking on "Server" will return a list of all of the databases to which you have access.

If you can not see a database which you know to exist, you may have a permission and/or access error.

Title: adminer only displays one database

Body:
Adminer will only ever show one database at a time.

You can switch databases very simply, by using the standard links at the top of your screen (just to the left of your "logout" button). I.e.:

MySQL » Server » yourDatabaseName » Table: yourTableName

In this example, clicking on "Server" will return a list of all of the databases to which you have access.

If you can not see a database which you know to exist, you may have a permission and/or access error.


问:
Unable to install app on watchOS simulator Xcode9, iOS11, watchOS4 app crashes
I wrote a program for watchOS and tried running it on simulator. I am unable to run this app on simulator, installation fails with error: Unable to install the app.

I am using xcode9, Simulator: iphone7 + Apple Watch Series 2 - 38mm
Here is my CoreSimulator.log summary

Nov 17 10:38:47 xyz-iMac com.apple.dt.Xcode[351] :
  installApplication:withOptions:error:: Error
  Domain=IXUserPresentableErrorDomain Code=2 "This app was unable to be
  installed." UserInfo={NSLocalizedDescription=This app was unable to be
  installed., NSUnderlyingError=0x7fbc74153480 {Error
  Domain=MIInstallerErrorDomain Code=59 "Appex bundle at
  /Users/fe/Library/Developer/CoreSimulator/Devices/58D7256F-1247-48E3-BDE2-F2F44CEEB0E9/data/Library/Caches/com.apple.mobile.installd.staging/temp.Sku79o/extracted/testwatch.app/Watch/testwatch
  WatchKit App.app/PlugIns/testwatch WatchKit Extension.appex with id
  com.test.testwatch.watchkitapp.watchkitextension specifies a value
  (com.apple.watchkit) for the NSExtensionPointIdentifier key in the
  NSExtension dictionary in its Info.plist that does not correspond to a
  known extension point."
  UserInfo={LegacyErrorString=AppexBundleUnknownExtensionPointIdentifier,
  FunctionName=-[MIPluginKitPluginBundle overlaidInfoPlistWithError:],
  SourceFileLine=215, NSLocalizedDescription=Appex bundle at
  /Users/fe/Library/Developer/CoreSimulator/Devices/58D7256F-1247-48E3-BDE2-F2F44CEEB0E9/data/Library/Caches/com.apple.mobile.installd.staging/temp.Sku79o/extracted/testwatch.app/Watch/testwatch
  WatchKit App.app/PlugIns/testwatch WatchKit Extension.appex with id
  com.test.testwatch.watchkitapp.watchkitextension specifies a value
  (com.apple.watchkit) for the NSExtensionPointIdentifier key in the
  NSExtension dictionary in its Info.plist that does not correspond to a
  known extension point.}}}

This is the error Message
This is info.plist file

答:
Try changing the order between

NSExtensionPointIdentifier

and

NSExtensionAttributes

NSExtensionPointIdentifier: This key is required for every app extension, and must be placed as an immediate child of the NSExtension key.

This key is supported in iOS 8 and later and in macOS 10.10 and later.
Check IOS version.

Have you tried taking a look at this post?


问:
Pretty Paths in Rails
I have a category model and I'm routing it using the default scaffolding of resources :categories. I'm wondering if there's a way to change the paths from /category/:id to /category/:name. I added:

```<code>match "/categories/:name" => "categories#show"
</code>```

above the resources line in routes.rb and changed the show action in the controller to do:

```<code>@category = Category.find_by_name(params[:name])
</code>```

it works, but the 'magic paths' such as link_to some_category still use the :id format.

Is there a way to do this? If this is a bad idea (due to some possible way in which rails works internally), is there another way to accomplish this? So that /categories/music, for example, and /categories/3 both work?

答:
If you don't want to to break existing code that relying on model id you could define your to_param like this:

```<code> def to_param
   "#{id}-#{name}"
 end
</code>```

so your url will be: http://path/1-some-model and you still can load your model with Model.find(params[:id]) because:

"123-hello-world".to_i
    => 123

Title: Pretty Paths in Rails

Body:
I have a category model and I'm routing it using the default scaffolding of resources :categories. I'm wondering if there's a way to change the paths from /category/:id to /category/:name. I added:

match "/categories/:name" => "categories#show"

above the resources line in routes.rb and changed the show action in the controller to do:

@category = Category.find_by_name(params[:name])

it works, but the 'magic paths' such as link_to some_category still use the :id format.

Is there a way to do this? If this is a bad idea (due to some possible way in which rails works internally), is there another way to accomplish this? So that /categories/music, for example, and /categories/3 both work?

Body:
If you don't want to to break existing code that relying on model id you could define your to_param like this:

 def to_param
   "#{id}-#{name}"
 end

so your url will be: http://path/1-some-model and you still can load your model with Model.find(params[:id]) because:

"123-hello-world".to_i
    => 123


问:
Pythonic way to loop two lists
I have two arrays:

```<code>Array_a = [20, 30, 50, 20]
Array_b = [1 ,2  ,3  , 4]
</code>```

would like to have the following output:

(20, '(1,Days Learning)')
(30, '(2,Days Learning)')
(50, '(3,Days Learning)')
(20, '(4,Days Learning)')
```

<p>My code looks like the following:</p>

```for i,j in zip(Array_a, Array_b):
    msg = (i, "(" + str(j) + ",Days Learning)")
    print(msg)
```

<p>but I would like to have it somehow easier like the way:</p>

```for a, b in []
```

答:
How about this :
it looks more pythonic way to me

```<code>Array_a = [20, 30, 50, 20]
Array_b = [1 ,2  ,3  , 4]

sample = tuple(zip(Array_a,zip(Array_b,["Days Learning" for i in range(len(Array_b))])))
print(sample)
</code>```

it will give you this result:

```<code>((20, (1, 'Days Learning')), (30, (2, 'Days Learning')), (50, (3, 'Days Learning')), (20, (4, 'Days Learning')))
</code>```

Title: Pythonic way to loop two lists

Body:
I have two arrays:

Array_a = [20, 30, 50, 20]
Array_b = [1 ,2  ,3  , 4]

would like to have the following output:

(20, '(1,Days Learning)')
(30, '(2,Days Learning)')
(50, '(3,Days Learning)')
(20, '(4,Days Learning)')

My code looks like the following:

for i,j in zip(Array_a, Array_b):
    msg = (i, "(" + str(j) + ",Days Learning)")
    print(msg)

but I would like to have it somehow easier like the way:

for a, b in []

Body:
How about this :
it looks more pythonic way to me

Array_a = [20, 30, 50, 20]
Array_b = [1 ,2  ,3  , 4]

sample = tuple(zip(Array_a,zip(Array_b,["Days Learning" for i in range(len(Array_b))])))
print(sample)

it will give you this result:

((20, (1, 'Days Learning')), (30, (2, 'Days Learning')), (50, (3, 'Days Learning')), (20, (4, 'Days Learning')))


问:
what does this bash script line of code mean
I am new to shell scripting and I found following line of code in a given script.

Could someone explain me with an example what the following line of code means

```<code>Path=`echo $line | awk -F '|' '{print $1}'`
</code>```

答:
```<code>Path=`echo $line | awk -F '|' '{print $1}'`
 ^           ^             ^           ^
 |           |             |           |
 |           |             |           print 1st column
 |           |             |
 |           |           input field separator
 |           |
 |          echo variable line
 |
variable Path
</code>```

-F'|' - by default awk splits record/line/row into columns by single space, but with |, awk splits by pipe

Above one can be written as

```<code>Path=$( awk -F '|' '{ print $1 }' <<< "$line" )
</code>```

Suppose say

```<code>$ line="1|2|3"
$ Path=$( awk -F '|' '{ print $1 }' <<< "$line" )
$ echo $Path; # you get first column
1
</code>```

Same as

```<code>$ Path=$( cut -d'|' -f1 <<< "$line" )
$ echo $Path;
1
</code>```

Body:
I am new to shell scripting and I found following line of code in a given script.

Could someone explain me with an example what the following line of code means

Path=`echo $line | awk -F '|' '{print $1}'`

Body:
Path=`echo $line | awk -F '|' '{print $1}'`
 ^           ^             ^           ^
 |           |             |           |
 |           |             |           print 1st column
 |           |             |
 |           |           input field separator
 |           |
 |          echo variable line
 |
variable Path

-F'|' - by default awk splits record/line/row into columns by single space, but with |, awk splits by pipe

Above one can be written as

Path=$( awk -F '|' '{ print $1 }' <<< "$line" )

Suppose say

$ line="1|2|3"
$ Path=$( awk -F '|' '{ print $1 }' <<< "$line" )
$ echo $Path; # you get first column
1

Same as

$ Path=$( cut -d'|' -f1 <<< "$line" )
$ echo $Path;
1


问:
How can I GROUP_CONCAT values in mySQL with a SEPERATOR "
" but without breaking lines?
When I use in mySQL request...

```<code>GROUP_CONCAT(text SEPARATOR " <br> ") AS texts
</code>```

...my result in my html table is:

```<code>My name is
Fred
My age is 24
My friend's
name is Toni
My job is
teacher
</code>```

But I would need a kind of nowrap result for each element:

```<code>My name is Fred
My age is 24
My friend's name is Toni
My job is teacher
</code>```

I need a solution directly inside the mySQL request:

答:
Please try this:</p>

```<code> GROUP_CONCAT(replace(text,"\r\n","") SEPARATOR " <br> ") AS texts
</code>```

Title: How can I GROUP_CONCAT values in mySQL with a SEPERATOR "<br>" but without breaking lines?

Body:
When I use in mySQL request...

GROUP_CONCAT(text SEPARATOR "
 ") AS texts

...my result in my html table is:

My name is
Fred
My age is 24
My friend's
name is Toni
My job is
teacher

But I would need a kind of nowrap result for each element:

My name is Fred
My age is 24
My friend's name is Toni
My job is teacher

I need a solution directly inside the mySQL request:

Body:
Please try this:

 GROUP_CONCAT(replace(text,"\r\n","") SEPARATOR " <br> ") AS texts


问:
Groovy load .csv files
How to read and import .csv file in groovy on grails. I have .csv file with data and <br/>
need to import in to db using user interface . </p>

答:
Example using opencsv</p>

```<code>@Grab('com.opencsv:opencsv:4.0')
import com.opencsv.CSVReader
import com.opencsv.CSVWriter

class TestCsvReader {

    static main(args) {
        def csv = '''"a","b","c"
"d","e","f"
'''
        def Reader csvFileReader = new StringReader(csv)
        def Writer csvFileWriter = new PrintWriter(System.out)
        def CSVReader reader = new CSVReader(csvFileReader)
        def CSVWriter writer = new CSVWriter(csvFileWriter)

        reader.iterator().each { fields ->
            writer.writeNext(fields)
        }
        reader.close()
        writer.close()
    }
}
</code>```

Title: Groovy load .csv files

Body:
How to read and import .csv file in groovy on grails. I have .csv file with data and

need to import in to db using user interface .

Body:
Example using opencsv

@Grab('com.opencsv:opencsv:4.0')
import com.opencsv.CSVReader
import com.opencsv.CSVWriter

class TestCsvReader {

    static main(args) {
        def csv = '''"a","b","c"
"d","e","f"
'''
        def Reader csvFileReader = new StringReader(csv)
        def Writer csvFileWriter = new PrintWriter(System.out)
        def CSVReader reader = new CSVReader(csvFileReader)
        def CSVWriter writer = new CSVWriter(csvFileWriter)

        reader.iterator().each { fields ->
            writer.writeNext(fields)
        }
        reader.close()
        writer.close()
    }
}


问:
Trying to understand this piece of c code but just cant get it
I have been googling for couple of hours now for explanation for following code but just couldn't find, appreciating if someone can help me.

I have defined memory location like (address is just sample),

```<code>#define address (0x000001)
</code>```

then i have a struct

```<code>typedef struct{
int a;
int c;
int f;
} foo;
</code>```

and last (this part i can't figure out) I have definition like

```<code>#define foo__ ( (foo *) address)
</code>```

does this mean that I'm creating macro whereby I can access elements of structure foo and that foo structure begins at 0x000001?

I know that the code works - have tested it but there is no use if I cant understand what it does.

Edit. Sorry for unclear information on question - yea its LPC microcontroller by NXP which is used in embedded environment - should told that in the first place and - my bad.

Thanks for answers and commends - I figured it out now.

答:
It creates a macro, such that if you use foo__, it will assume an instance of that typedef'd struct exists at (in this example) 0x000001.

So, if an instance does exist there, and you can access it, you'll be able to access those elements accordingly. However, there's no protection here and it's really up to you to decide if that's sensible and safe for you to attempt.

Body:
I have been googling for couple of hours now for explanation for following code but just couldn't find, appreciating if someone can help me.

I have defined memory location like (address is just sample),

#define address (0x000001)

then i have a struct

typedef struct{
int a;
int c;
int f;
} foo;

and last (this part i can't figure out) I have definition like

#define foo__ ( (foo *) address)

does this mean that I'm creating macro whereby I can access elements of structure foo and that foo structure begins at 0x000001?

I know that the code works - have tested it but there is no use if I cant understand what it does.

Edit. Sorry for unclear information on question - yea its LPC microcontroller by NXP which is used in embedded environment - should told that in the first place and - my bad.

Thanks for answers and commends - I figured it out now.


问:
Delete specific values from column with where condition?
I want to delete specific values/data from one column with the WHERE condition. Putting in another way, I don't want to delete the complete row. Is it possible?</p>

答:
UPDATE myTable
   SET myColumn = NULL
 WHERE myCondition
```


问:
Could not find the preLaunch task 'build'
To configure Visual Studio Code to debug C# scripts on OSX, I followed through all the steps listed in the article below:

Debugging C# on OSX with Visual Studio Code

When I tried to debug the sample C# script, Visual Studio Code reported this error:

Could not find the preLaunch task 'build'

As a consequence, I could not inspect the variables defined in the script.

This is a copy of the launch.json file:

```<code>{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch console application",
            "type": "mono",
            "request": "launch",
            "preLaunchTask": "build",
            "program": "${workspaceRoot}/Program.exe",
            "args": [],
            "cwd": "${workspaceRoot}",
            "stopAtEntry": false
        }
    ]
}
</code>```

This is a copy of the tasks.json file:

```<code>{
    "version": "0.1.0",
    "command": "mcs",
    "args": [
        "-debug",
        "Program.cs"
    ],
    "showOutput": "silent",
    "taskSelector": "/t:",
    "tasks": [
        {
            "taskName": "exe",
            "isBuildCommand": true,
            "problemMatcher": "$msCompile"
        }
    ]
}
</code>```

How do I resolve this?

答:
You can use the Visual Studio Code to solve it.

When you see the error message, click on the steps below

Configure Task

Create tasks.json file from template

NET Core Executes .NET Core build commands

The VSCode will create a file like it:

```<code>{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "command": "dotnet build",
            "type": "shell",
            "group": "build",
            "presentation": {
                "reveal": "silent"
            },
            "problemMatcher": "$msCompile"
        }
    ]
}
</code>```

It's finished. The VSCode will build the project before run.

Body:
To configure Visual Studio Code to debug C# scripts on OSX, I followed through all the steps listed in the article below:

Debugging C# on OSX with Visual Studio Code

When I tried to debug the sample C# script, Visual Studio Code reported this error:

Could not find the preLaunch task 'build'

As a consequence, I could not inspect the variables defined in the script.

This is a copy of the launch.json file:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch console application",
            "type": "mono",
            "request": "launch",
            "preLaunchTask": "build",
            "program": "${workspaceRoot}/Program.exe",
            "args": [],
            "cwd": "${workspaceRoot}",
            "stopAtEntry": false
        }
    ]
}

This is a copy of the tasks.json file:

{
    "version": "0.1.0",
    "command": "mcs",
    "args": [
        "-debug",
        "Program.cs"
    ],
    "showOutput": "silent",
    "taskSelector": "/t:",
    "tasks": [
        {
            "taskName": "exe",
            "isBuildCommand": true,
            "problemMatcher": "$msCompile"
        }
    ]
}

How do I resolve this?

Body:
You can use the Visual Studio Code to solve it.

When you see the error message, click on the steps below

Configure Task

Create tasks.json file from template

NET Core Executes .NET Core build commands

The VSCode will create a file like it:

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "command": "dotnet build",
            "type": "shell",
            "group": "build",
            "presentation": {
                "reveal": "silent"
            },
            "problemMatcher": "$msCompile"
        }
    ]
}

It's finished. The VSCode will build the project before run.


问:
Xamarin.Forms UWP - Display HTML in a Label
In Xamarin.Forms, how do I display HTML in a label? In other words, if I have new Label { Text = "some text and some bold text" }, I want it to display as "some text and some bold text".

I know I need to use a custom renderer, and I've implemented in iOS. I just don't know how to implement it in UWP.

答:
For your requirement, you could realize this feature via custom LabelRenderer, and in native project you could make HtmlTextBehavior for TextBlock. The following is Behavior processing logical.

```<code>public class HtmlTextBehavior : Behavior<TextBlock>
{
    private const string ElementA = "A";
    private const string ElementB = "B";
    private const string ElementBr = "BR";
    private const string ElementEm = "EM";
    private const string ElementI = "I";
    private const string ElementP = "P";
    private const string ElementStrong = "STRONG";
    private const string ElementU = "U";
    private const string ElementUl = "UL";
    private const string ElementLi = "LI";
    private const string ElementDiv = "DIV";
    protected override void OnAttached()
    {
        base.OnAttached();

        AssociatedObject.Loaded += OnAssociatedObjectLoaded;
        AssociatedObject.LayoutUpdated += OnAssociatedObjectLayoutUpdated;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        AssociatedObject.Loaded -= OnAssociatedObjectLoaded;
        AssociatedObject.LayoutUpdated -= OnAssociatedObjectLayoutUpdated;
    }

    private void OnAssociatedObjectLayoutUpdated(object sender, object o)
    {
        UpdateText();
    }

    private void OnAssociatedObjectLoaded(object sender, RoutedEventArgs routedEventArgs)
    {
        UpdateText();
        AssociatedObject.Loaded -= OnAssociatedObjectLoaded;
    }

    private void UpdateText()
    {
        if (AssociatedObject == null) return;
        if (string.IsNullOrEmpty(AssociatedObject.Text)) return;

        string text = AssociatedObject.Text;

        // Just incase we are not given text with elements.
        string modifiedText = string.Format("<div>{0}</div>", text);

        // reset the text because we will add to it.
        AssociatedObject.Inlines.Clear();
        try
        {
            var element = XElement.Parse(modifiedText);
            ParseText(element, AssociatedObject.Inlines);
        }
        catch (Exception)
        {
            // if anything goes wrong just show the html
            AssociatedObject.Text = text;
        }
        AssociatedObject.LayoutUpdated -= OnAssociatedObjectLayoutUpdated;
        AssociatedObject.Loaded -= OnAssociatedObjectLoaded;
    }
    private static void ParseText(XElement element, InlineCollection inlines)
    {
        if (element == null) return;

        InlineCollection currentInlines = inlines;
        var elementName = element.Name.ToString().ToUpper();
        switch (elementName)
        {
            case ElementA:
                var link = new Hyperlink();
                var href = element.Attribute("href");
                if (href != null)
                {
                    try
                    {
                        link.NavigateUri = new Uri(href.Value);
                    }
                    catch (System.FormatException) { /* href is not valid */ }
                }
                inlines.Add(link);
                currentInlines = link.Inlines;
                break;
            case ElementB:
            case ElementStrong:
                var bold = new Bold();
                inlines.Add(bold);
                currentInlines = bold.Inlines;
                break;
            case ElementI:
            case ElementEm:
                var italic = new Italic();
                inlines.Add(italic);
                currentInlines = italic.Inlines;
                break;
            case ElementU:
                var underline = new Underline();
                inlines.Add(underline);
                currentInlines = underline.Inlines;
                break;
            case ElementBr:
                inlines.Add(new LineBreak());
                break;
            case ElementP:
                // Add two line breaks, one for the current text and the second for the gap.
                if (AddLineBreakIfNeeded(inlines))
                {
                    inlines.Add(new LineBreak());
                }

                Span paragraphSpan = new Span();
                inlines.Add(paragraphSpan);
                currentInlines = paragraphSpan.Inlines;
                break;
            case ElementLi:
                inlines.Add(new LineBreak());
                inlines.Add(new Run { Text = " • " });
                break;
            case ElementUl:
            case ElementDiv:
                AddLineBreakIfNeeded(inlines);
                Span divSpan = new Span();
                inlines.Add(divSpan);
                currentInlines = divSpan.Inlines;
                break;
        }
        foreach (var node in element.Nodes())
        {
            XText textElement = node as XText;
            if (textElement != null)
            {
                currentInlines.Add(new Run { Text = textElement.Value });
            }
            else
            {
                ParseText(node as XElement, currentInlines);
            }
        }
        // Add newlines for paragraph tags
        if (elementName == "ElementP")
        {
            currentInlines.Add(new LineBreak());
        }
    }
    private static bool AddLineBreakIfNeeded(InlineCollection inlines)
    {
        if (inlines.Count > 0)
        {
            var lastInline = inlines[inlines.Count - 1];
            while ((lastInline is Span))
            {
                var span = (Span)lastInline;
                if (span.Inlines.Count > 0)
                {
                    lastInline = span.Inlines[span.Inlines.Count - 1];
                }
            }
            if (!(lastInline is LineBreak))
            {
                inlines.Add(new LineBreak());
                return true;
            }
        }
        return false;
    }
}
</code>```

And then you could add this behavior to Native Control in cusotm renderer.

```<code>protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
    base.OnElementChanged(e);
    HtmlTextBehavior behavior = new HtmlTextBehavior();
    Interaction.GetBehaviors(Control).Add(behavior);
}
</code>```

I have uploaded code sample. Please check.

Body:
For your requirement, you could realize this feature via custom LabelRenderer, and in native project you could make HtmlTextBehavior for TextBlock. The following is Behavior processing logical.

public class HtmlTextBehavior : Behavior<TextBlock>
{
    private const string ElementA = "A";
    private const string ElementB = "B";
    private const string ElementBr = "BR";
    private const string ElementEm = "EM";
    private const string ElementI = "I";
    private const string ElementP = "P";
    private const string ElementStrong = "STRONG";
    private const string ElementU = "U";
    private const string ElementUl = "UL";
    private const string ElementLi = "LI";
    private const string ElementDiv = "DIV";
    protected override void OnAttached()
    {
        base.OnAttached();

        AssociatedObject.Loaded += OnAssociatedObjectLoaded;
        AssociatedObject.LayoutUpdated += OnAssociatedObjectLayoutUpdated;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        AssociatedObject.Loaded -= OnAssociatedObjectLoaded;
        AssociatedObject.LayoutUpdated -= OnAssociatedObjectLayoutUpdated;
    }

    private void OnAssociatedObjectLayoutUpdated(object sender, object o)
    {
        UpdateText();
    }

    private void OnAssociatedObjectLoaded(object sender, RoutedEventArgs routedEventArgs)
    {
        UpdateText();
        AssociatedObject.Loaded -= OnAssociatedObjectLoaded;
    }

    private void UpdateText()
    {
        if (AssociatedObject == null) return;
        if (string.IsNullOrEmpty(AssociatedObject.Text)) return;

        string text = AssociatedObject.Text;

        // Just incase we are not given text with elements.
        string modifiedText = string.Format("<div>{0}</div>", text);

        // reset the text because we will add to it.
        AssociatedObject.Inlines.Clear();
        try
        {
            var element = XElement.Parse(modifiedText);
            ParseText(element, AssociatedObject.Inlines);
        }
        catch (Exception)
        {
            // if anything goes wrong just show the html
            AssociatedObject.Text = text;
        }
        AssociatedObject.LayoutUpdated -= OnAssociatedObjectLayoutUpdated;
        AssociatedObject.Loaded -= OnAssociatedObjectLoaded;
    }
    private static void ParseText(XElement element, InlineCollection inlines)
    {
        if (element == null) return;

        InlineCollection currentInlines = inlines;
        var elementName = element.Name.ToString().ToUpper();
        switch (elementName)
        {
            case ElementA:
                var link = new Hyperlink();
                var href = element.Attribute("href");
                if (href != null)
                {
                    try
                    {
                        link.NavigateUri = new Uri(href.Value);
                    }
                    catch (System.FormatException) { /* href is not valid */ }
                }
                inlines.Add(link);
                currentInlines = link.Inlines;
                break;
            case ElementB:
            case ElementStrong:
                var bold = new Bold();
                inlines.Add(bold);
                currentInlines = bold.Inlines;
                break;
            case ElementI:
            case ElementEm:
                var italic = new Italic();
                inlines.Add(italic);
                currentInlines = italic.Inlines;
                break;
            case ElementU:
                var underline = new Underline();
                inlines.Add(underline);
                currentInlines = underline.Inlines;
                break;
            case ElementBr:
                inlines.Add(new LineBreak());
                break;
            case ElementP:
                // Add two line breaks, one for the current text and the second for the gap.
                if (AddLineBreakIfNeeded(inlines))
                {
                    inlines.Add(new LineBreak());
                }

                Span paragraphSpan = new Span();
                inlines.Add(paragraphSpan);
                currentInlines = paragraphSpan.Inlines;
                break;
            case ElementLi:
                inlines.Add(new LineBreak());
                inlines.Add(new Run { Text = " • " });
                break;
            case ElementUl:
            case ElementDiv:
                AddLineBreakIfNeeded(inlines);
                Span divSpan = new Span();
                inlines.Add(divSpan);
                currentInlines = divSpan.Inlines;
                break;
        }
        foreach (var node in element.Nodes())
        {
            XText textElement = node as XText;
            if (textElement != null)
            {
                currentInlines.Add(new Run { Text = textElement.Value });
            }
            else
            {
                ParseText(node as XElement, currentInlines);
            }
        }
        // Add newlines for paragraph tags
        if (elementName == "ElementP")
        {
            currentInlines.Add(new LineBreak());
        }
    }
    private static bool AddLineBreakIfNeeded(InlineCollection inlines)
    {
        if (inlines.Count > 0)
        {
            var lastInline = inlines[inlines.Count - 1];
            while ((lastInline is Span))
            {
                var span = (Span)lastInline;
                if (span.Inlines.Count > 0)
                {
                    lastInline = span.Inlines[span.Inlines.Count - 1];
                }
            }
            if (!(lastInline is LineBreak))
            {
                inlines.Add(new LineBreak());
                return true;
            }
        }
        return false;
    }
}

And then you could add this behavior to Native Control in cusotm renderer.

protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
    base.OnElementChanged(e);
    HtmlTextBehavior behavior = new HtmlTextBehavior();
    Interaction.GetBehaviors(Control).Add(behavior);
}

I have uploaded code sample. Please check.


问:
NestedScrollView with 5 multiple recyclerview dont show any value
This is my code for the RecyclerViews Page:

```<code>public class MenuActivity extends AppCompatActivity {

     private RecyclerView firstRecyclerView;

     JsonArrayRequest jsonArrayRequest ;

     RequestQueue requestQueue;

     NestedScrollView nsv;

     private ArrayList<Recipes>GetDataAdapter1;

     RecyclerView.Adapter adapter;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.search);

         firstRecyclerView = (RecyclerView)findViewById(R.id.recycler);

         //create and set layout manager for each RecyclerView
         RecyclerView.LayoutManager firstLayoutManager = new LinearLayoutManager(this);

         firstRecyclerView.setLayoutManager(firstLayoutManager);

         firstRecyclerView.setHasFixedSize(true);

         GetDataAdapter1 =  new ArrayList<>();

         JSON_DATA_WEB_CALL_VIEWS();

     }
</code>```

This is my RecyclerView AdapterList to call the inflate view for the list elements:

```<code>public RecyclerViewAdapterList(List<Recipes> getDataAdapter, Context
 context){

         super();
         this.itemList = getDataAdapter;

         this.context = context;
     }

     @Override
     public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {

         View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.inflate_pagecountry,
 parent, false);
         RecyclerViewHolders rcv = new RecyclerViewHolders(layoutView);
         return rcv;
     }
     @Override
     public void onBindViewHolder(RecyclerViewHolders holder, int position) {
         holder.NameCategory.setText(itemList.get(position).getTitle());
         Picasso.with(context).load(itemList.get(position).getImage()).into(holder.CategoryLogo);
     }
</code>```

I´m getting but logcat says

15:25:53.476 E/RecyclerView﹕ No adapter attached; skipping layout

Can you help me??

答: Actually Problem is that you are initializing n number of RecyclerView but assigning adapter only for one so you have to assign adapter for all OR comment all other RecyclerView</p>

Body:
This is my code for the RecyclerViews Page:

public class MenuActivity extends AppCompatActivity {

     private RecyclerView firstRecyclerView;

     JsonArrayRequest jsonArrayRequest ;

     RequestQueue requestQueue;

     NestedScrollView nsv;

     private ArrayList<Recipes>GetDataAdapter1;

     RecyclerView.Adapter adapter;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.search);

         firstRecyclerView = (RecyclerView)findViewById(R.id.recycler);

         //create and set layout manager for each RecyclerView
         RecyclerView.LayoutManager firstLayoutManager = new LinearLayoutManager(this);

         firstRecyclerView.setLayoutManager(firstLayoutManager);

         firstRecyclerView.setHasFixedSize(true);

         GetDataAdapter1 =  new ArrayList<>();

         JSON_DATA_WEB_CALL_VIEWS();

     }

This is my RecyclerView AdapterList to call the inflate view for the list elements:

public RecyclerViewAdapterList(List<Recipes> getDataAdapter, Context
 context){

         super();
         this.itemList = getDataAdapter;

         this.context = context;
     }

     @Override
     public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {

         View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.inflate_pagecountry,
 parent, false);
         RecyclerViewHolders rcv = new RecyclerViewHolders(layoutView);
         return rcv;
     }
     @Override
     public void onBindViewHolder(RecyclerViewHolders holder, int position) {
         holder.NameCategory.setText(itemList.get(position).getTitle());
         Picasso.with(context).load(itemList.get(position).getImage()).into(holder.CategoryLogo);
     }

I´m getting but logcat says

15:25:53.476 E/RecyclerView﹕ No adapter attached; skipping layout

Can you help me??


问:
Deprecated FacebookSdk method throws RuntimeException
I have FacebookSdk.sdkInitialize(getApplicationContext()) where sdkInitialize() is displayed as deprecated. According to this article we can just delete that line. But then I get following error for the line after AppEventsLogger.activateApp(this) :

```<code>AndroidRuntime: FATAL EXCEPTION: main                                                                              Process: com.daimler.moovel.android:auth, PID: 4011                                java.lang.RuntimeException: Unable to create application com.daimler.moovel.android.DebugApplication: The Facebook sdk must be initialized before calling activateApp                                              at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5879)                                             at android.app.ActivityThread.-wrap3(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1699)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
Caused by: The Facebook sdk must be initialized before calling activateApp
at com.facebook.appevents.AppEventsLogger.activateApp(AppEventsLogger.java:226)
at com.facebook.appevents.AppEventsLogger.activateApp(AppEventsLogger.java:208)
</code>```

So what am I missing?

答:
No need of AppEventsLogger.activateApp(this); now it is not required if you have set up facebook_id in manifest.xml
u just have to add following in Application tag in manifest.xml

```<code> <meta-data
   android:name="com.facebook.sdk.ApplicationId"
   android:value="@string/facebook_app_id" />
</code>```

where facebook_app_id is defined in string.xml

Body:
I have FacebookSdk.sdkInitialize(getApplicationContext()) where sdkInitialize() is displayed as deprecated. According to this article we can just delete that line. But then I get following error for the line after AppEventsLogger.activateApp(this) :

AndroidRuntime: FATAL EXCEPTION: main                                                                              Process: com.daimler.moovel.android:auth, PID: 4011                                java.lang.RuntimeException: Unable to create application com.daimler.moovel.android.DebugApplication: The Facebook sdk must be initialized before calling activateApp                                              at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5879)                                             at android.app.ActivityThread.-wrap3(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1699)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
Caused by: The Facebook sdk must be initialized before calling activateApp
at com.facebook.appevents.AppEventsLogger.activateApp(AppEventsLogger.java:226)
at com.facebook.appevents.AppEventsLogger.activateApp(AppEventsLogger.java:208)

So what am I missing?

Body:
No need of AppEventsLogger.activateApp(this); now it is not required if you have set up facebook_id in manifest.xml
u just have to add following in Application tag in manifest.xml

 <meta-data
   android:name="com.facebook.sdk.ApplicationId"
   android:value="@string/facebook_app_id" />

where facebook_app_id is defined in string.xml


问:
Trustwave scanning ( PCI DSS ) failed
My company providing servers with PCI complains. My client did a scan (Trustwave scan) but the dispute 'SSL/TLS Weak Encryption Algorithms' was denied and they provided following information.

======

Description:
The SSL-based service running on this host appears to support the use of "weak" ciphers such as:

Ciphers suites that have key-lengths of less than 128 bits.

Ciphers suites using anonymous Diffie-Hellman algorithms (no authentication).

Ciphers suites offering no encryption.

Ciphers suites using pre-shared keys.

Ciphers suites using RC4 or MD5

Evidence: Cipher Suite: TLSv1 : RC4-SHA

My Server details:-

CLOUDLINUX 5.11 x86_64
WHM 11.52.1
SSH version : OpenSSH_4.3p2, OpenSSL 0.9.8e-fips-rhel5 01 Jul 2008.

Can somebody explain me what it is and fix for this issue?

答:
This happned because in your Web Server you have enabled this cipher suits.
Disable all this ciphers from your web server's config file and only provide AES ciphers.
then you can also check for the cipher suits here  https://www.ssllabs.com/ssltest/</p>

Title: Trustwave scanning ( PCI DSS ) failed


问:
The number of failing rows exceeds the maximum specified (Microsoft JET Database Engine (80004005): Spreadsheet is full.)
I would like to ask help regarding this error. Here are the details regarding this error.

Step Error Source: Microsoft Data Transformation Services (DTS) Data Pump

Step Error Description:The number of failing rows exceeds the maximum specified. (Microsoft JET Database Engine (80004005): Spreadsheet is full.)

Step Error code: 8004206A

Step Error Help File:sqldts80.hlp

Step Error Help Context ID:0

I'm wondering on where can I locate the specific location of the error for this and other details.

答: The number of records maxed out the number of available records in Excel. What I did was to copy the records and save it in Excel 2007 as this can hold around 1 million rows.</p>


答:
Not as pretty as you probably want, but it does the work.</p>

```<code>List<string> someList = new List<string>{"1-30","20-100","21-23","34-80"};
List<string> newList = new List<string>();
foreach (var v in someList)
     {
        string[] s = v.Split('-');
        newList.Add(s[0]);
     }
</code>```

Title: Split elements of a list and retrieve only the first part from the split

Body:
I have a list say

List<string> someList = new List{"1-30","20-10","21-23","34-80"};

I need to split the list so I have with following values

 {"1","20","21","34"};

I tried

 someList
   .SelectMany(n => n.Split('-')[0])
   .ToList();

But it is not giving me the desired result.

UPDATE:
Sorry everyone, Using Select solved my issue. One of those days, when you make silly mistakes

Body:
Not as pretty as you probably want, but it does the work.

List<string> someList = new List<string>{"1-30","20-100","21-23","34-80"};
List<string> newList = new List<string>();
foreach (var v in someList)
     {
        string[] s = v.Split('-');
        newList.Add(s[0]);
     }


问:
Handlebars precompiled to plain HTML
Is there a way to precompile a Handlebars template to plain HTML? Handlebars precompile produces a js file. Can I run that JS on node to produce a HTML file? This is how I'm trying:

```<code>// Get a Handlebars instance
var hb = require("handlebars");

// Load a template
import fs = require('fs');
var template:string = fs.readFileSync('templates/template.handlebars','utf8');

// Compile said template
var compiled = hb.precompile(template);

// Write JS file
fs.writeFileSync('compiled/template.js', compiled);

var test = compiled.main();

// Write HTML file
fs.writeFileSync('compiled/template.html', test);
</code>```

This fails as compiled.main is not a function. There's a main function in there though, which I'm trying to get at.

答:
Found the solution. You don't precompile, you just compile and then run the compiled template:

```<code>// Get a Handlebars instance
var hb = require("handlebars");

// Load a template
import fs = require('fs');
var template:string = fs.readFileSync('templates/template.handlebars','utf8');

// Compile said template
var compiled = hb.compile(template);
var html = compiled({});

// Write HTML file
fs.writeFileSync('compiled/template.html', html);
</code>```

Pity it isn't in the docs.

Title: Handlebars precompiled to plain HTML

Body:
Is there a way to precompile a Handlebars template to plain HTML? Handlebars precompile produces a js file. Can I run that JS on node to produce a HTML file? This is how I'm trying:

// Get a Handlebars instance
var hb = require("handlebars");

// Load a template
import fs = require('fs');
var template:string = fs.readFileSync('templates/template.handlebars','utf8');

// Compile said template
var compiled = hb.precompile(template);

// Write JS file
fs.writeFileSync('compiled/template.js', compiled);

var test = compiled.main();

// Write HTML file
fs.writeFileSync('compiled/template.html', test);

This fails as compiled.main is not a function. There's a main function in there though, which I'm trying to get at.

Body:
Found the solution. You don't precompile, you just compile and then run the compiled template:

// Get a Handlebars instance
var hb = require("handlebars");

// Load a template
import fs = require('fs');
var template:string = fs.readFileSync('templates/template.handlebars','utf8');

// Compile said template
var compiled = hb.compile(template);
var html = compiled({});

// Write HTML file
fs.writeFileSync('compiled/template.html', html);

Pity it isn't in the docs.


问:
Jmeter 406 error - token not found
I'm using Jmeter for the first time to test the Load from a website. But there are exactly 3 API's that don't seem to work. The three of them have the same error page at the View Results Tree (I translated the error message to english):

The Test Plan already has the HTTP Request Defaults, HTTP Cookie Manager, HTTP Header Manager and Recording Controller.

How can I solve that problem or know which is the Token that is missing? Some API's that come after it have a Cookie Data called .ASPXAUTH. Is that the token I need?

答:
It is quite hard to guess without seeing your request and response details, you can identify the required dynamic parameter (token or whatever) by recording your test one more time and compare resulting .jmx files for differences.

Carefully inspect everything as the token might come as a Cookie, as a Header, as a part of the response URL after redirection or in the response body and use the relevant JMeter's Post-Processor to extract it from the previous response and add to the next request.

The process is known as correlation and you should be able to find a plenty of information on different approaches over the web via jmeter correlation query in your favorite search engine.

You may also be interested in an alternative way of recording a JMeter test which automatically detects and works around dynamic parameters so you won't have to do this manually, check out How to Cut Your JMeter Scripting Time by 80% article for more details.

Title: Jmeter 406 error - token not found


问:
Where is c# 7.2 in visual studio project settings?
Ive seen people using and discussing c# 7.2 features but I cant seem to find it.

Ive got latest updates and only up to version 7.1 is listed. why and how can I get v7.2?

specs:

Visual studio 2017 version 15.4.4

Visual C# 2017 - 00369-60000-00001-AA303

答:
Version 15.4.* of VS 2017 doesn't support C# 7.2.

C# 7.2 support was introduced in VS 2017 version 15.5, which was released on December 4th.


问:
Saving large map in GenServer, is this a valid use case?
Could this be a valid use for GenServer:

If the process_id is the user_id and it is unique. Process contains a query result of a big map of data which is generated via DB. Now if 100's of users log in to the system and ask for their data map they all are saved in their own process referenced by the user_id which is unique

So upon asking for the map I will check to see if there is a process with user_id ( which is process id ) and grab it and feed it to back to the user, if not then I create it and put it in a new state

now if user updated his map, at the update, I make sure to update the sate or create a new one.

Thank you for your guidance

答:
As someone mentioned it on somewhere on Elixir forum already - for pure state store use Agent, for pure computation use Task - for everything in between - GenServers! ;)

Even if you do not need any computation at the moment it may appear that you will need it soon and just because of this I would stick to GenServer.


问:
Setting typeface of hint in TextEdit
Is it possible to set typeface of hint element of EditText view without changing the typeface of the EditText itself? Thanks.</p>

答:
Did you check android:typeface?

This works fine both for the hint and text for the EditText.

Title: Setting typeface of hint in TextEdit


问:
How can I download and save a file from the Internet using Java?
There is an online file (such as http://www.example.com/information.asp) I need to grab and save to a directory. I know there are several methods for grabbing and reading online files (URLs) line-by-line, but is there a way to just download and save the file using Java?

答:
If you are behind a proxy, you can set the proxies in the Java program as below:

```<code>Properties systemSettings = System.getProperties();
systemSettings.put("proxySet", "true");
systemSettings.put("https.proxyHost", "HTTPS proxy of your org");
systemSettings.put("https.proxyPort", "8080");
</code>```

If you are not behind a proxy, don't include the lines above in your code. Full working code to download a file when you are behind a proxy.

```<code>public static void main(String[] args) throws IOException {
    String url = "https://raw.githubusercontent.com/bpjoshi/fxservice/master/src/test/java/com/bpjoshi/fxservice/api/TradeControllerTest.java";
    OutputStream outStream = null;
    URLConnection connection = null;
    InputStream is = null;
    File targetFile = null;
    URL server = null;

    // Setting up proxies
    Properties systemSettings = System.getProperties();
        systemSettings.put("proxySet", "true");
        systemSettings.put("https.proxyHost", "HTTPS proxy of my organisation");
        systemSettings.put("https.proxyPort", "8080");
        // The same way we could also set proxy for HTTP
        System.setProperty("java.net.useSystemProxies", "true");
        // Code to fetch file
    try {
        server = new URL(url);
        connection = server.openConnection();
        is = connection.getInputStream();
        byte[] buffer = new byte[is.available()];
        is.read(buffer);

        targetFile = new File("src/main/resources/targetFile.java");
        outStream = new FileOutputStream(targetFile);
        outStream.write(buffer);
    } catch (MalformedURLException e) {
        System.out.println("THE URL IS NOT CORRECT ");
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println("I/O exception");
        e.printStackTrace();
    }
    finally{
        if(outStream != null)
            outStream.close();
    }
}
</code>```

Body:
If you are behind a proxy, you can set the proxies in the Java program as below:

Properties systemSettings = System.getProperties();
systemSettings.put("proxySet", "true");
systemSettings.put("https.proxyHost", "HTTPS proxy of your org");
systemSettings.put("https.proxyPort", "8080");

If you are not behind a proxy, don't include the lines above in your code. Full working code to download a file when you are behind a proxy.

public static void main(String[] args) throws IOException {
    String url = "https://raw.githubusercontent.com/bpjoshi/fxservice/master/src/test/java/com/bpjoshi/fxservice/api/TradeControllerTest.java";
    OutputStream outStream = null;
    URLConnection connection = null;
    InputStream is = null;
    File targetFile = null;
    URL server = null;

    // Setting up proxies
    Properties systemSettings = System.getProperties();
        systemSettings.put("proxySet", "true");
        systemSettings.put("https.proxyHost", "HTTPS proxy of my organisation");
        systemSettings.put("https.proxyPort", "8080");
        // The same way we could also set proxy for HTTP
        System.setProperty("java.net.useSystemProxies", "true");
        // Code to fetch file
    try {
        server = new URL(url);
        connection = server.openConnection();
        is = connection.getInputStream();
        byte[] buffer = new byte[is.available()];
        is.read(buffer);

        targetFile = new File("src/main/resources/targetFile.java");
        outStream = new FileOutputStream(targetFile);
        outStream.write(buffer);
    } catch (MalformedURLException e) {
        System.out.println("THE URL IS NOT CORRECT ");
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println("I/O exception");
        e.printStackTrace();
    }
    finally{
        if(outStream != null)
            outStream.close();
    }
}