问:
How to group foreach statement by id in c#
I'm having a little challenge, and I am pretty new to mvc. My question is,

How do i group a bunch of foreach statements, by the id of the table it is being called from. here is my code:

```<code>foreach (
                        var owner in
                            _entities.LLAttrDatas.Where(
                                n => n.AttrID == 2 && n.ValStr.Contains(searchInputModel.OwnersName)))
                    {
                        ViewBag.searchName = owner.ValStr;
                    }

                    foreach (
                        var ownerAddress in
                            _entities.LLAttrDatas.Where(
                                n => n.AttrID == 3 && n.ValStr.Contains(searchInputModel.OwnersAddress)))
                    {
                        ViewBag.searchAddress = ownerAddress.ValStr;
                    }

                    foreach (
                        var propertyAddress in
                            _entities.LLAttrDatas.Where(
                                n => n.AttrID == 4 && n.ValStr.Contains(searchInputModel.DescriptionOrLocationOfProp)))
                    {
                        ViewBag.searchProperty = propertyAddress.ValStr;
                    }

                    foreach (
                        var propertyVolumeNo in
                            _entities.LLAttrDatas.Where(
                                n => n.AttrID == 5 && n.ValStr.Contains(searchInputModel.VolumeNumber)))
                    {
                        ViewBag.searchPropertyVolumeNo = propertyVolumeNo.ValStr;
                    }

                    foreach (
                        var propertyPlanNo in
                            _entities.LLAttrDatas.Where(
                                n => n.AttrID == 6 && n.ValStr.Contains(searchInputModel.SurveyPlanNumber))
                        )
                    {
                        ViewBag.searchPropertyPlanNo = propertyPlanNo.ValStr;
                    }
</code>```

Right now, when a user makes a search against any of the above query, just one result is being shown. I want it to display all the results from the different queries since they all have the same ID. Any help will be highly appreciated thanks.

Thanks y'all for your comments and support. We learn everyday. Anyways, I found a better way of doing it:

```<code>public IQueryable<DocumentProperty> GetDocuments(DocumentSearchInputModel searchInputModel)
            {
                Context = new DataContext();

                if (Context != null)
                {
                    var result = Context.DocumentsForSearch.AsQueryable();
                    if (searchInputModel != null)
                    {

                        result =
                            Context.DocumentsForSearch.Where(
                                d =>
                                    d.DescriptionOrLocationOfProp.Contains(searchInputModel.DescriptionOrLocationOfProp)
                                    || d.OwnersAddress.Contains(searchInputModel.OwnersAddress)
                                    || d.OwnersName.Contains(searchInputModel.OwnersName)
                                    || d.SurveyPlanNumber.Contains(searchInputModel.SurveyPlanNumber)
                                    || d.VolumeNumber.Contains(searchInputModel.VolumeNumber)
                                    || d.FileUrl.Contains(searchInputModel.OwnersName));

                    }
                    Logger.Info($"Results found {result}");
                    return result;
                }
                return null;
            }
</code>```

Now the only issue i'm having is how to display the search result in the view. how do i do a foreach where AttrID and ValStr match, and if the user search in only one field (because its a multi search system), I want the result to display all the fields with the same ID (i.e d.ID). Thanks.

答:
Can you do it like this?</p>

```<code>foreach(var myProp in _entities.LLAttrDatas)
{
    if(myProp.AttrID == 1 && myProp.ValStr.StartsWith("foo"))
        // etc..
    else if (myProp.AttrID == 2 && myProp.ValStr.StartsWith("bar"))
        // etc..
}
</code>```

Body:
I'm having a little challenge, and I am pretty new to mvc. My question is,

How do i group a bunch of foreach statements, by the id of the table it is being called from. here is my code:

foreach (
                        var owner in
                            _entities.LLAttrDatas.Where(
                                n => n.AttrID == 2 && n.ValStr.Contains(searchInputModel.OwnersName)))
                    {
                        ViewBag.searchName = owner.ValStr;
                    }

                    foreach (
                        var ownerAddress in
                            _entities.LLAttrDatas.Where(
                                n => n.AttrID == 3 && n.ValStr.Contains(searchInputModel.OwnersAddress)))
                    {
                        ViewBag.searchAddress = ownerAddress.ValStr;
                    }

                    foreach (
                        var propertyAddress in
                            _entities.LLAttrDatas.Where(
                                n => n.AttrID == 4 && n.ValStr.Contains(searchInputModel.DescriptionOrLocationOfProp)))
                    {
                        ViewBag.searchProperty = propertyAddress.ValStr;
                    }

                    foreach (
                        var propertyVolumeNo in
                            _entities.LLAttrDatas.Where(
                                n => n.AttrID == 5 && n.ValStr.Contains(searchInputModel.VolumeNumber)))
                    {
                        ViewBag.searchPropertyVolumeNo = propertyVolumeNo.ValStr;
                    }

                    foreach (
                        var propertyPlanNo in
                            _entities.LLAttrDatas.Where(
                                n => n.AttrID == 6 && n.ValStr.Contains(searchInputModel.SurveyPlanNumber))
                        )
                    {
                        ViewBag.searchPropertyPlanNo = propertyPlanNo.ValStr;
                    }

Right now, when a user makes a search against any of the above query, just one result is being shown. I want it to display all the results from the different queries since they all have the same ID. Any help will be highly appreciated thanks.

Thanks y'all for your comments and support. We learn everyday. Anyways, I found a better way of doing it:

public IQueryable<DocumentProperty> GetDocuments(DocumentSearchInputModel searchInputModel)
            {
                Context = new DataContext();

                if (Context != null)
                {
                    var result = Context.DocumentsForSearch.AsQueryable();
                    if (searchInputModel != null)
                    {

                        result =
                            Context.DocumentsForSearch.Where(
                                d =>
                                    d.DescriptionOrLocationOfProp.Contains(searchInputModel.DescriptionOrLocationOfProp)
                                    || d.OwnersAddress.Contains(searchInputModel.OwnersAddress)
                                    || d.OwnersName.Contains(searchInputModel.OwnersName)
                                    || d.SurveyPlanNumber.Contains(searchInputModel.SurveyPlanNumber)
                                    || d.VolumeNumber.Contains(searchInputModel.VolumeNumber)
                                    || d.FileUrl.Contains(searchInputModel.OwnersName));

                    }
                    Logger.Info($"Results found {result}");
                    return result;
                }
                return null;
            }

Now the only issue i'm having is how to display the search result in the view. how do i do a foreach where AttrID and ValStr match, and if the user search in only one field (because its a multi search system), I want the result to display all the fields with the same ID (i.e d.ID). Thanks.

Body:
Can you do it like this?

foreach(var myProp in _entities.LLAttrDatas)
{
    if(myProp.AttrID == 1 && myProp.ValStr.StartsWith("foo"))
        // etc..
    else if (myProp.AttrID == 2 && myProp.ValStr.StartsWith("bar"))
        // etc..
}


来源: stackexchange

问:
Lucene Scoring Function - bias towards shorter documents
I want Lucene Scoring function to have no bias based on the length of the document. This is really a follow up question to Calculate the score only based on the documents have more occurance of term in lucene

I was wondering how Field.setOmitNorms(true) works? I see that there are two factors that make short documents get a high score:

"boost" that shorter length posts - using doc.getBoost()

"lengthNorm" in the definition of norm(t,d)

Here is the documentation

I was wondering - if I wanted no bias towards shorter documents, is Field.setOmitNorms(true) enough?

答:
Using BM25Similarity you could reduce to 0f:

@param b Controls to what degree document length normalizes tf values

or

@param k1 Controls non-linear term frequency normalization (saturation).

Both params will affect SimWeight

```<code>indexSearcher.setSimilarity(new BM25Similarity(1.2f,0f));
</code>```

More explanation can be found here : http://opensourceconnections.com/blog/2015/10/16/bm25-the-next-generation-of-lucene-relevation/

ContentLicense: CC BY-SA 3.0

Body:
Using BM25Similarity you could reduce to 0f:

@param b Controls to what degree document length normalizes tf values

or

@param k1 Controls non-linear term frequency normalization (saturation).

Both params will affect SimWeight

indexSearcher.setSimilarity(new BM25Similarity(1.2f,0f));

More explanation can be found here : http://opensourceconnections.com/blog/2015/10/16/bm25-the-next-generation-of-lucene-relevation/


问:
oracle sql query error while comparing date columns
I have a following oracle sql query in which START_DATE is a number column and a_date is DATE type and the input value is also of type DATE. kindly let me know how to compare the date columns with the input date.</p>

```<code>select a.id ,a.v ,b.id,b.v
 from DATA a ,FDC  b  where a.START_DATE = to_date('11-DEC-10','YYYYMMDD')
 and a.START_DATE = b.a_date and b.code = 'JFK'
</code>```

答:
It depends entirely on what format your number start_date column is stored in.

However, it would probably be easier if you used the predicate on the true date column, and joined using a format mask just once.

For example:

```<code>SELECT a.id,
       a.v,
       b.id,
       b.v
  FROM data a,
       fdc b
 WHERE b.a_date = to_date('11-DEC-2010','DD-MON-RRRR')
   AND a.start_date = TO_NUMBER(TO_CHAR(b.a_date, 'DDMMRRRR'))
   AND b.code = 'JFK'
</code>```

Please note that the date format matches the format of the date you are comparing - b.a_date = to_date('11-DEC-2010','DD-MON-RRRR'). This query assumes that the a.start_date column is stored in the format DDMMRRRR. You would need to amend this for whichever format your date is stored in e.g. a.start_date = TO_NUMBER(TO_CHAR(b.a_date, 'J')) for a Julian date.

P.s. Why use a number to store a date?

ContentLicense: CC BY-SA 2.5

Body:
I have a following oracle sql query in which START_DATE is a number column and a_date is DATE type and the input value is also of type DATE. kindly let me know how to compare the date columns with the input date.

select a.id ,a.v ,b.id,b.v
 from DATA a ,FDC  b  where a.START_DATE = to_date('11-DEC-10','YYYYMMDD')
 and a.START_DATE = b.a_date and b.code = 'JFK'

Body:
It depends entirely on what format your number start_date column is stored in.

However, it would probably be easier if you used the predicate on the true date column, and joined using a format mask just once.

For example:

SELECT a.id,
       a.v,
       b.id,
       b.v
  FROM data a,
       fdc b
 WHERE b.a_date = to_date('11-DEC-2010','DD-MON-RRRR')
   AND a.start_date = TO_NUMBER(TO_CHAR(b.a_date, 'DDMMRRRR'))
   AND b.code = 'JFK'

Please note that the date format matches the format of the date you are comparing - b.a_date = to_date('11-DEC-2010','DD-MON-RRRR'). This query assumes that the a.start_date column is stored in the format DDMMRRRR. You would need to amend this for whichever format your date is stored in e.g. a.start_date = TO_NUMBER(TO_CHAR(b.a_date, 'J')) for a Julian date.

P.s. Why use a number to store a date?

OwnerDisplayName: Please delete me

LastEditorDisplayName: Please delete me


问:
Merging a set of characters if the next row of characters has the same set?
Let's say I have the following string.

```<code>&eThe quick brown fox &djumps over the &dlazy &adog.
</code>```

Each set of color codes &letter, e.g &e will change the color of the following text until another color code appears. It's redundant to have two of the same codes follow after each other because it's both the same color.

```<code>&djumps over the &dlazy
</code>```

I'm trying to merge any duplicate color code that matches the color code before it, so the above string would change into the following:

```<code>&eThe quick brown fox &djumps over the lazy &adog.
</code>```

However I'm not sure how this is done. Can anyone help?

答:
Your markup language needs an mechanism for the situations where the text includes a & followed by a letter (e.g. D&D, <). The exact solution will depend on your escape mechanism. I have provided code that works if your markup language has no escape mechanism (BAD!), and I've also provided code that works if your markup language's escape mechanism consists of doubling the & (the most obvious mechanism).

// If you don't have an escape mechanism.

let text = '&eThe quick brown fox &djumps over the &dlazy &adog.';

let prev;
let result = text.replace(
   /&([a-zA-Z])/g,
   match => match === prev ? '' : ( prev = match ),
);

console.log(result);```
</div>
</div>
</p>

<p>or</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// If && is an escaped &, and escaping is optional where unambiguous.

let text = '&eThe quick brown fox &djumps over the &dlazy &adog.';

let prev;
let result = text.replace(
   /&(.)/g,
   function (match) {
      return match.replace(
         /^&([a-zA-Z])/,
         match => match === prev ? '' : ( prev = match ),
      );
   },
);

console.log(result);</code>```

Body:
Let's say I have the following string.

&eThe quick brown fox &djumps over the &dlazy &adog.

Each set of color codes &letter, e.g &e will change the color of the following text until another color code appears. It's redundant to have two of the same codes follow after each other because it's both the same color.

&djumps over the &dlazy

I'm trying to merge any duplicate color code that matches the color code before it, so the above string would change into the following:

&eThe quick brown fox &djumps over the lazy &adog.

However I'm not sure how this is done. Can anyone help?

Body:
Your markup language needs an mechanism for the situations where the text includes a & followed by a letter (e.g. D&D, &lt;). The exact solution will depend on your escape mechanism. I have provided code that works if your markup language has no escape mechanism (BAD!), and I've also provided code that works if your markup language's escape mechanism consists of doubling the & (the most obvious mechanism).

// If you don't have an escape mechanism.

let text = '&eThe quick brown fox &djumps over the &dlazy &adog.';

let prev;
let result = text.replace(
   /&([a-zA-Z])/g,
   match => match === prev ? '' : ( prev = match ),
);

console.log(result);

or

// If && is an escaped &, and escaping is optional where unambiguous.

let text = '&eThe quick brown fox &djumps over the &dlazy &adog.';

let prev;
let result = text.replace(
   /&(.)/g,
   function (match) {
      return match.replace(
         /^&([a-zA-Z])/,
         match => match === prev ? '' : ( prev = match ),
      );
   },
);

console.log(result);


问:
Escaping ampersand within a string variable using sed
I am replacing the text SUBJECT with a value from an array variable like this:

```<code>#!/bin/bash

# array of subjects, the ampersand causes a problem.
subjects=("Digital Art" "Digital Photography" "3D Modelling & Animation")

echo $subjects[2] # Subject: 3D Modelling & Animation

sed -i -e "s/SUBJECT/${subjects[2]}/g" test.svg
</code>```

Instead of replacing the text SUBJECT, the resulting text looks like this:

```<code>3D Modelling SUBJECT Animation
</code>```

How can I include the ampersand as a literal & in sed and also have it echo correctly?

答:
Problem is presence of & in your replacement text. & makes sed place fully matched text in replacement hence SUBJECT appears in output.

You can use this trick:

```<code>sed -i "s/SUBJECT/${subjects[2]//&/\\&}/g" test.svg
</code>```

${subjects[2]//&/\\&} replaces each & with \& in 2nd element of subjects array before invoking sed substitution.

Body:
I am replacing the text SUBJECT with a value from an array variable like this:

#!/bin/bash

# array of subjects, the ampersand causes a problem.
subjects=("Digital Art" "Digital Photography" "3D Modelling & Animation")

echo $subjects[2] # Subject: 3D Modelling & Animation

sed -i -e "s/SUBJECT/${subjects[2]}/g" test.svg

Instead of replacing the text SUBJECT, the resulting text looks like this:

3D Modelling SUBJECT Animation

How can I include the ampersand as a literal & in sed and also have it echo correctly?

Body:
Problem is presence of & in your replacement text. & makes sed place fully matched text in replacement hence SUBJECT appears in output.

You can use this trick:

sed -i "s/SUBJECT/${subjects[2]//&/\\&}/g" test.svg

${subjects[2]//&/\\&} replaces each & with \& in 2nd element of subjects array before invoking sed substitution.


答:
You can escape the & in the parameter expansion:

```<code>sed -i -e "s/SUBJECT/${subjects[2]//&/\\&}/g" test.svg
</code>```

This will expand as follows:

```<code>$ echo "${subjects[2]//&/\\&}"
3D Modelling \& Animation
</code>```

and if there is no &, nothing happens.

Title: Escaping ampersand within a string variable using sed

Body:
You can escape the & in the parameter expansion:

sed -i -e "s/SUBJECT/${subjects[2]//&/\\&}/g" test.svg

This will expand as follows:

$ echo "${subjects[2]//&/\\&}"
3D Modelling \& Animation

and if there is no &, nothing happens.


问:
Transform SQL Table
We have a table that has the following format

```<code>RecordID FieldName FieldValue

1         Name      John
1         Age       30
2         Name      Alice
2         Age       40
</code>```

We would like to present this as:

```<code>John   30
Alice  40
</code>```

Anyone have a good solution for this?

答:
```<code>declare @a TABLE(RecordId int, FieldName varchar(20), FieldValue varchar(20))

insert into @a select 1, 'Name', 'John'
insert into @a select 1, 'Age', '30'
insert into @a select 2, 'Name', 'Alice'
insert into @a select 2, 'Age', '40'

select
 records.RecordId
 , name.fieldvalue [Name]
 , age.fieldvalue [Age]
from
 (select distinct recordid from @a) records
 inner join @a name on records.recordid = name.recordid and name.fieldname = 'Name'
 inner join @a age on records.recordid = age.recordid and age.fieldname = 'Age'
</code>```

Title: Transform SQL Table

Body:
We have a table that has the following format

RecordID FieldName FieldValue

1         Name      John
1         Age       30
2         Name      Alice
2         Age       40

We would like to present this as:

John   30
Alice  40

Anyone have a good solution for this?


答:
Try this :</p>

```<code>var results = _entities.LLAttrDatas.select(x = > new {
     owner = x.Where(n => n.AttrID == 2 && n.ValStr.Contains(searchInputModel.OwnersName)).FirstOrDefault(),
     ownerAddress = x.Where(n => n.AttrID == 3 && n.ValStr.Contains(searchInputModel.OwnersAddress)).FirstOrDefault(),
     propertyAddress = x.Where(n => n.AttrID == 4 && n.ValStr.Contains(searchInputModel.DescriptionOrLocationOfProp)).FirstOrDefault(),
     propertyVolumeNo = x.Where(n => n.AttrID == 5 && n.ValStr.Contains(searchInputModel.VolumeNumber)).FirstOrDefault(),
     propertyPlanNo = x.Where(n => n.AttrID == 6 && n.ValStr.Contains(searchInputModel.SurveyPlanNumber)).FirstOrDefault()
}).ToList();
</code>```

Title: How to group foreach statement by id in c#

Body:
Try this :

var results = _entities.LLAttrDatas.select(x = > new {
     owner = x.Where(n => n.AttrID == 2 && n.ValStr.Contains(searchInputModel.OwnersName)).FirstOrDefault(),
     ownerAddress = x.Where(n => n.AttrID == 3 && n.ValStr.Contains(searchInputModel.OwnersAddress)).FirstOrDefault(),
     propertyAddress = x.Where(n => n.AttrID == 4 && n.ValStr.Contains(searchInputModel.DescriptionOrLocationOfProp)).FirstOrDefault(),
     propertyVolumeNo = x.Where(n => n.AttrID == 5 && n.ValStr.Contains(searchInputModel.VolumeNumber)).FirstOrDefault(),
     propertyPlanNo = x.Where(n => n.AttrID == 6 && n.ValStr.Contains(searchInputModel.SurveyPlanNumber)).FirstOrDefault()
}).ToList();


问:
Solr: DocValuesField appears more than once in this document (Solr 6.5)
Receiving this error after upgrading to Solr 6.5 when I attempt to insert a record into the field.

Full Error:

```<code>2017-06-05 02:57:40,685 ERROR
[org.apache.solr.client.solrj.impl.CloudSolrClient] - Request to collection
<collection> failed due to (400)
org.apache.solr.client.solrj.impl.HttpSolrClient$RemoteSolrException: Error
from server at http://<host>:8983/solr/<collection>: Exception
writing document id <number> to the index; possible analysis error:
DocValuesField "location_field_0_coordinate" appears
more than once in this document (only one value is allowed per field)
</code>```

Field Declaration:

```<code><field name="location_field" type="locations" indexed="true" stored="true" required="false" multiValued="true" />
</code>```

Type Declaration (location):

```<code><fieldType name="location" class="solr.LatLonType" subFieldSuffix="_coordinate"/>
</code>```

答:
According to the documentation, solr.LatLonType does not support multivalued fields.

It appears in Solr 6.5 there was a change to check for the condition of inserting multiple values into a solr.LatLonType.

In Solr 6.3 I am able to successfully insert multiple locations into a solr.LatLonType field type.

Solution:
you should replace your location field type with LatLonPointSpatialField, which is a drop in replacement to solr.LatLonType that supports multivalued fields.

```<code><fieldType name="location" class="solr.LatLonPointSpatialField" docValues="true"/>
</code>```

See: https://cwiki.apache.org/confluence/display/solr/Spatial+Search

Body:
Receiving this error after upgrading to Solr 6.5 when I attempt to insert a record into the field.

Full Error:

2017-06-05 02:57:40,685 ERROR
[org.apache.solr.client.solrj.impl.CloudSolrClient] - Request to collection
<collection> failed due to (400)
org.apache.solr.client.solrj.impl.HttpSolrClient$RemoteSolrException: Error
from server at http://<host>:8983/solr/<collection>: Exception
writing document id <number> to the index; possible analysis error:
DocValuesField "location_field_0_coordinate" appears
more than once in this document (only one value is allowed per field)

Field Declaration:

<field name="location_field" type="locations" indexed="true" stored="true" required="false" multiValued="true" />

Type Declaration (location):

<fieldType name="location" class="solr.LatLonType" subFieldSuffix="_coordinate"/>

Body:
According to the documentation, solr.LatLonType does not support multivalued fields.

It appears in Solr 6.5 there was a change to check for the condition of inserting multiple values into a solr.LatLonType.

In Solr 6.3 I am able to successfully insert multiple locations into a solr.LatLonType field type.

Solution:
you should replace your location field type with LatLonPointSpatialField, which is a drop in replacement to solr.LatLonType that supports multivalued fields.

<fieldType name="location" class="solr.LatLonPointSpatialField" docValues="true"/>

See: https://cwiki.apache.org/confluence/display/solr/Spatial+Search


问:
Redirect standard input (read-host) to a Powershell script
Here's a sample powershell script:

```<code>$in = read-host -prompt "input"
write-host $in
</code>```

Here's a sample 'test.txt' file:

```<code>hello
</code>```

And we want to pass piped input to it from powershell.  Here's some I have tried:

```<code>.\test.ps1 < test.txt
.\test.ps1 < .\test.txt
.\test.ps1 | test.txt
.\test.ps1 | .\test.txt
test.txt | .\test.ps1
.\test.txt | .\test.ps1
get-content .\test.txt | .\test.ps1
</code>```

even just trying to echo input doesn't work either:

```<code>echo hi | \.test.ps1
</code>```

Every example above that doesn't produce an error always prompts the user instead of accepting the piped input.

Note: My powershell version table says 4.0.-1.-1

Thanks

Edit/Result: To those looking for a solution, you cannot pipe input to a powershell script.  You have to update your PS file.  See the snippets below.

答:
You can't pipe input to Read-Host, but there should be no need to do so.

PowerShell doesn't support input redirection (<) yet. In practice this is not a (significant) limitation because a < b can be rewritten as b | a (i.e., send output of b as input to a).

PowerShell can prompt for input for a parameter if the parameter's value is missing and it is set as a mandatory attribute. For example:

```<code>function test {
  param(
    [parameter(Mandatory=$true)] [String] $TheValue
  )
  "You entered: $TheValue"
}
</code>```

If you don't provide input for the $TheValue parameter, PowerShell will prompt for it.

In addition, you can specify that a parameter accepts pipeline input. Example:

```<code>function test {
  param(
    [parameter(ValueFromPipeline=$true)] [String] $TheValue
  )
  process {
    foreach ( $item in $TheValue ) {
      "Input: $item"
    }
  }
}
</code>```

So if you write

```<code>"A","B","C" | test
</code>```

The function will output the following:

```<code>Input: A
Input: B
Input: C
</code>```

All of this is spelled out pretty concisely in the PowerShell documentation.

Body:
Here's a sample powershell script:

$in = read-host -prompt "input"
write-host $in

Here's a sample 'test.txt' file:

hello

And we want to pass piped input to it from powershell.  Here's some I have tried:

.\test.ps1 < test.txt
.\test.ps1 < .\test.txt
.\test.ps1 | test.txt
.\test.ps1 | .\test.txt
test.txt | .\test.ps1
.\test.txt | .\test.ps1
get-content .\test.txt | .\test.ps1

even just trying to echo input doesn't work either:

echo hi | \.test.ps1

Every example above that doesn't produce an error always prompts the user instead of accepting the piped input.

Note: My powershell version table says 4.0.-1.-1

Thanks

Edit/Result: To those looking for a solution, you cannot pipe input to a powershell script.  You have to update your PS file.  See the snippets below.

Body:
You can't pipe input to Read-Host, but there should be no need to do so.

PowerShell doesn't support input redirection (<) yet. In practice this is not a (significant) limitation because a < b can be rewritten as b | a (i.e., send output of b as input to a).

PowerShell can prompt for input for a parameter if the parameter's value is missing and it is set as a mandatory attribute. For example:

function test {
  param(
    [parameter(Mandatory=$true)] [String] $TheValue
  )
  "You entered: $TheValue"
}

If you don't provide input for the $TheValue parameter, PowerShell will prompt for it.

In addition, you can specify that a parameter accepts pipeline input. Example:

function test {
  param(
    [parameter(ValueFromPipeline=$true)] [String] $TheValue
  )
  process {
    foreach ( $item in $TheValue ) {
      "Input: $item"
    }
  }
}

So if you write

"A","B","C" | test

The function will output the following:

Input: A
Input: B
Input: C

All of this is spelled out pretty concisely in the PowerShell documentation.


问:
Programmatically change header summary
I have a preference_headers.xml file that I use to populate the headers for my settings. I would like to change the summary of the header to reflect the sharedPreference it holds. I have used an OnSharedPreferenceChangeListener for my other fragments and it works fine, but those are fragments under a preference screen, so I can access them like this..

```<code>SharedPreferences sp = getPreferenceScreen().getSharedPreferences();
        EditTextPreference editTextPref = (EditTextPreference) findPreference("pref_text");
        editTextPref
                .setSummary(sp.getString("pref_text", "Set an email address"));
</code>```

However, I want to edit the summary in the preference_headers file which is an intent to another activity, so I am not using a preference screen to store the shared preference.

```<code><preference-headers xmlns:android="http://schemas.android.com/apk/res/android" >

<header
    android:key="snooze_pref"
    android:summary="Default snooze is 10 minutes"
    android:title="Snooze Timer" >
    <intent
        android:action="android.intent.action.VIEW"
        android:targetClass="com.example.alarmvoltageservicev2.SnoozePicker"
        android:targetPackage="com.example.alarmvoltageservicev2" />
</header>
</code>```

So my question is, how can I change the header summary above programmatically?

答:
Assuming you are extending class PreferenceActivity, in your override of the )" rel="nofollow noreferrer">onBuildHeaders method, after calling LoadHeadersFromResource, simply iterate through the "target" list that is passed to onBuildHeaders.

The list is of type Header which provides access to the summary text, as well as other settings.

(Sorry, I would provide a code example, but I write in C#-monodroid).

Title: Programmatically change header summary

Body:
I have a preference_headers.xml file that I use to populate the headers for my settings. I would like to change the summary of the header to reflect the sharedPreference it holds. I have used an OnSharedPreferenceChangeListener for my other fragments and it works fine, but those are fragments under a preference screen, so I can access them like this..

SharedPreferences sp = getPreferenceScreen().getSharedPreferences();
        EditTextPreference editTextPref = (EditTextPreference) findPreference("pref_text");
        editTextPref
                .setSummary(sp.getString("pref_text", "Set an email address"));

However, I want to edit the summary in the preference_headers file which is an intent to another activity, so I am not using a preference screen to store the shared preference.

<preference-headers xmlns:android="http://schemas.android.com/apk/res/android" >

    <intent
        android:action="android.intent.action.VIEW"
        android:targetClass="com.example.alarmvoltageservicev2.SnoozePicker"
        android:targetPackage="com.example.alarmvoltageservicev2" />

So my question is, how can I change the header summary above programmatically?

Body:
Assuming you are extending class PreferenceActivity, in your override of the onBuildHeaders method, after calling LoadHeadersFromResource, simply iterate through the "target" list that is passed to onBuildHeaders.

The list is of type Header which provides access to the summary text, as well as other settings.

(Sorry, I would provide a code example, but I write in C#-monodroid).


问:
How to list all the commands that executed on a pulled Docker image?
I'm currently studying Docker for the lab use. Imagine this is my situation: I created a Docker image and then pushed it to the Docker Hub with my username(e.g. myname/lab1). Later on, my friend pulled my image and then commit some changes on it, then pushed it to the Docker Hub with his username (his/lab1).
My question is, assume I'm able to pull his the image (his/lab1) which is built upon my original image, how can I find/list all the changes my friend made to my original image?

Many thanks!

答:
You can use docker history <image_name/id>

```<code>▶ docker history ubuntu
IMAGE               CREATED             CREATED BY                                      SIZE                COMMENT
f7b3f317ec73        5 weeks ago         /bin/sh -c #(nop)  CMD ["/bin/bash"]            0 B
<missing>           5 weeks ago         /bin/sh -c mkdir -p /run/systemd && echo '...   7 B
<missing>           5 weeks ago         /bin/sh -c sed -i 's/^#\s*\(deb.*universe\...   2.76 kB
<missing>           5 weeks ago         /bin/sh -c rm -rf /var/lib/apt/lists/*          0 B
<missing>           5 weeks ago         /bin/sh -c set -xe   && echo '#!/bin/sh' >...   745 B
<missing>           5 weeks ago         /bin/sh -c #(nop) ADD file:141408db9037263...   117 MB
</code>```

Add --no-trunc in order to see the complete command (CREATED BY column).

However, IMHO the ideal way to work with your friend should be maintaining a versioned Dockerfile and see the changes there.

If you don't track your changes with Dockerfile, and you use docker commit instead, it is more difficult to see the changes that a layer add. There is a proposal regarding this: https://github.com/moby/moby/issues/12641, that is still an Open Issue, as of Jun/2017.

Body:
You can use docker history <image_name/id>

▶ docker history ubuntu
IMAGE               CREATED             CREATED BY                                      SIZE                COMMENT
f7b3f317ec73        5 weeks ago         /bin/sh -c #(nop)  CMD ["/bin/bash"]            0 B
<missing>           5 weeks ago         /bin/sh -c mkdir -p /run/systemd && echo '...   7 B
<missing>           5 weeks ago         /bin/sh -c sed -i 's/^#\s*\(deb.*universe\...   2.76 kB
<missing>           5 weeks ago         /bin/sh -c rm -rf /var/lib/apt/lists/*          0 B
<missing>           5 weeks ago         /bin/sh -c set -xe   && echo '#!/bin/sh' >...   745 B
<missing>           5 weeks ago         /bin/sh -c #(nop) ADD file:141408db9037263...   117 MB

Add --no-trunc in order to see the complete command (CREATED BY column).

However, IMHO the ideal way to work with your friend should be maintaining a versioned Dockerfile and see the changes there.

If you don't track your changes with Dockerfile, and you use docker commit instead, it is more difficult to see the changes that a layer add. There is a proposal regarding this: https://github.com/moby/moby/issues/12641, that is still an Open Issue, as of Jun/2017.


问:
teamcity 2017.1.1 artifactory plugin release management
We are using TeamCity with the Artifactory plugin, utilising the release management functions for Maven builds.

However, I have just upgraded TeamCity from 8.1.4 to 2017.1.1 and following a successful run of a Release build using the Artifactory Release Management tab, the subsequent build displays a link to the build info but not the Artifactory Release Promotion.

We are running Artifactory Pro 4.15.0, v.2.3.1 of the plugin.

Any ideas why it might not be available?

We have a teamcity-server.log entry:

```<code>[2017-05-30 16:40:04,149]  ERROR -   jetbrains.buildServer.SERVER - Error java.lang.InstantiationException: bean buildId not found within scope while processing request: GET '/viewLog.html?buildId=1151702&tab=buildResultsDiv&buildTypeId=XXXXXXX_Compile', from client 162.11.60.209:58332, authenticated as XXXXXXX {id=2}
java.lang.InstantiationException: bean buildId not found within scope
            at org.apache.jsp.plugins.artifactory.promotionResultsFragmentExtension_jsp._jspService(promotionResultsFragmentExtension_jsp.java:136)
            at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
</code>```

答: Please see this issue addressed in JIRA [TCAP-293][1]. This bug will be fixed in the next release of the TeamCity plugin which is scheduled for the end of June. </p>

Body:
We are using TeamCity with the Artifactory plugin, utilising the release management functions for Maven builds.

However, I have just upgraded TeamCity from 8.1.4 to 2017.1.1 and following a successful run of a Release build using the Artifactory Release Management tab, the subsequent build displays a link to the build info but not the Artifactory Release Promotion.

We are running Artifactory Pro 4.15.0, v.2.3.1 of the plugin.

Any ideas why it might not be available?

We have a teamcity-server.log entry:

[2017-05-30 16:40:04,149]  ERROR -   jetbrains.buildServer.SERVER - Error java.lang.InstantiationException: bean buildId not found within scope while processing request: GET '/viewLog.html?buildId=1151702&tab=buildResultsDiv&buildTypeId=XXXXXXX_Compile', from client 162.11.60.209:58332, authenticated as XXXXXXX {id=2}
java.lang.InstantiationException: bean buildId not found within scope
            at org.apache.jsp.plugins.artifactory.promotionResultsFragmentExtension_jsp._jspService(promotionResultsFragmentExtension_jsp.java:136)
            at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)


问:
VS2010 doesn't always release dlls before building
I have a periodically occurring problem when building with Visual Studio 2010.
Sometimes it refuses to build with an error message like:

Error  102 Unable to copy file "xxxxx\Debug\Services.dll" to "bin\Debug\Services.dll". The process cannot access the file 'bin\Debug\Services.dll' because it is being used by another process.

The only remedy I have found is to restart Visual Studio. Closing the solution is not enough.
I have tried to find the culprit with Process Explorer since I suspected that one of my own threads didn't close down as it should. However the process is devenv.exe, i.e. Visual Studio itself. Also I get this symptom only with VS 2010 even when building upgraded VS 2008 projects. I never experienced this problem with the same projects under VS 2008.

I have a lot of custom made WPF user controls and I have a theory that it is the WPF designer that sometimes hold on to the control's dependent dll's when it should be releasing them for a build. The theory is not well established since this is a periodic problem and sometimes it occurs without the designed being open. I also have the same problem for a windows forms project. Sometimes I get through a day without a locked dll. Sometimes it is every other build or so.

I have asked Microsoft about the problem and they told me to make a dump of Visual Studio and debug the dump. I didn't find that to be sound advice.

Have anybody experienced something similar? It is really annoying.

Update 1

Since this appears to be a Visual Studio bug and Microsoft has responded that they do not intend to do anything about it I would like to encourage everybody who works with custom user controls to up-vote this bug at connect.microsoft.com.

The bug is both reported here: https://connect.microsoft.com/VisualStudio/feedback/details/587281 and by me here https://connect.microsoft.com/VisualStudio/feedback/details/568672

Update 2
I have hacked together a simple Visual Studio macro that closes down all .XAML files before building. So far I have not experienced the lockup with this macro.
Add the following macro in Visual Studio and assigned to your favorite build short cut. Maybe / maybe not that will fix the problem.

```<code>Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics

Public Module CloseXamlAndBuildModule
    Sub CloseXamlAndBuild()
        For Each myDocument As EnvDTE.Document In DTE.Documents
            If myDocument.Name.EndsWith(".xaml") Then
                myDocument.Close()
            End If
        Next
        DTE.Solution.SolutionBuild.Build()
    End Sub

End Module
</code>```

答: I finally found a stable working solution. I realized that the source of the problems were initializing code in the constructors of WCF services and WPF controls. After cleaning the constructors from any dependencies to other assemblies everything has been fine.</p>

Body:
I have a periodically occurring problem when building with Visual Studio 2010.
Sometimes it refuses to build with an error message like:

Error  102 Unable to copy file "xxxxx\Debug\Services.dll" to "bin\Debug\Services.dll". The process cannot access the file 'bin\Debug\Services.dll' because it is being used by another process.

The only remedy I have found is to restart Visual Studio. Closing the solution is not enough.
I have tried to find the culprit with Process Explorer since I suspected that one of my own threads didn't close down as it should. However the process is devenv.exe, i.e. Visual Studio itself. Also I get this symptom only with VS 2010 even when building upgraded VS 2008 projects. I never experienced this problem with the same projects under VS 2008.

I have a lot of custom made WPF user controls and I have a theory that it is the WPF designer that sometimes hold on to the control's dependent dll's when it should be releasing them for a build. The theory is not well established since this is a periodic problem and sometimes it occurs without the designed being open. I also have the same problem for a windows forms project. Sometimes I get through a day without a locked dll. Sometimes it is every other build or so.

I have asked Microsoft about the problem and they told me to make a dump of Visual Studio and debug the dump. I didn't find that to be sound advice.

Have anybody experienced something similar? It is really annoying.

Update 1

Since this appears to be a Visual Studio bug and Microsoft has responded that they do not intend to do anything about it I would like to encourage everybody who works with custom user controls to up-vote this bug at connect.microsoft.com.

The bug is both reported here: https://connect.microsoft.com/VisualStudio/feedback/details/587281 and by me here https://connect.microsoft.com/VisualStudio/feedback/details/568672

Update 2
I have hacked together a simple Visual Studio macro that closes down all .XAML files before building. So far I have not experienced the lockup with this macro.
Add the following macro in Visual Studio and assigned to your favorite build short cut. Maybe / maybe not that will fix the problem.

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics

Public Module CloseXamlAndBuildModule
    Sub CloseXamlAndBuild()
        For Each myDocument As EnvDTE.Document In DTE.Documents
            If myDocument.Name.EndsWith(".xaml") Then
                myDocument.Close()
            End If
        Next
        DTE.Solution.SolutionBuild.Build()
    End Sub

End Module


问:
Upgraded Angular service not working in angular component :cannot get Undefined error
I am working on upgrading an AngularJS app to angular.
But i have now gotten stuck.
I am tryting to get angular to handle the home route and doesn't work. The error appears to come from the upgraded service.

When i let angularJS handle the route it works fine using the same components.

App-routing.module

```<code>class HybridUrlHandlingStrategy implements UrlHandlingStrategy {
  // use only process the `home` url
  shouldProcessUrl(url:UrlTree) {
    console.log(url.toString());
    return url.toString() === '/' || url.toString() ==='/home' ;
  }
  extract(url: UrlTree) { return url; }
  merge(url: UrlTree, whole: UrlTree) { return url; }
}

const appRoutes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', component: HomeComponentNg2 }
];

@NgModule({
    imports:[
        RouterModule.forRoot(appRoutes)
    ],
    exports: [RouterModule ],
    providers:[
    { provide: UrlHandlingStrategy, useClass: HybridUrlHandlingStrategy }
    ]
})

export class AppRoutingModule { }
</code>```

ajs-upgraded-providers.ts

```<code>export function statsServiceFactory(i: any) {
  return i.get('StatsService');
}
export const StatsServiceProvider = {
  provide: StatsService,
  useFactory: statsServiceFactory,
  deps: ['$injector']
};

export function authServiceFactory(i:any){
  return i.get('AuthService');
}

export const AuthServiceProvider = {
  provide: AuthService,
  useFactory: authServiceFactory,
  deps: ['$injector']
</code>```

stats.service

```<code>export class StatsService {
    static $inject = ['$http'];
    constructor(private $http) {
        this.$http = $http;
    };

    getEmplStats() {
        console.log('getEmplstats');
        return this.$http.get('./src/app/JSON/employeeStats.json')
            .then(res => {
            console.log(res);
            return res
        }).catch(error => {
            console.log(error);
        })
    };

    getCustStats() {
        console.log('getCustStats');
        return this.$http.get('./src/app/JSON/customerStats.json')
            .then(res => {
            console.log(" getCustStats "+res);
            return res
        }).catch(error => {
            console.log(error);
        })
    }
}
export default StatsService;
</code>```

The error

```<code>core.es5.js?0445:1084 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'get' of undefined
TypeError: Cannot read property 'get' of undefined
    at statsServiceFactory (eval at 327 (http://localhost:8080/app.js:653:1), <anonymous>:6:13)
    at Ng2AppModuleInjector.get (ng:///Ng2AppModule/module.ngfactory.js:161:69)
    at Ng2AppModuleInjector.getInternal (ng:///Ng2AppModule/module.ngfactory.js:271:52)
    at Ng2AppModuleInjector.NgModuleInjector.get (eval at <anonymous> (http://localhost:8080/vendor.js:84:1), <anonymous>:3783:44)
    at resolveDep (eval at <anonymous> (http://localhost:8080/vendor.js:84:1), <anonymous>:11245:45)
</code>```

I just dont understand why letting AngularJS handle the route it seems to go fine but if i let Angular handle it, it falls apart.
Any help would be apreciated

edit:Added the customer-stats.ng2.component

```<code>@Component({
  selector: 'customer-stats2',
  templateUrl: './customer-stats.ng2.component.html'
})

export class CustomerStatsComponentNg2 implements OnInit{
    customerStats:any;

    constructor(private ss:StatsService){
    }

    ngOnInit()
    {
        console.log('ngoninit cust stats ')
        this.ss.getCustStats().
            then(custStats => this.customerStats = custStats.data)
           .then(error => console.log(error))
    }
}
</code>```

答:
I faced the same issue while trying to upgrade the angularjs service and use in angular. You can find the bug raised in the angular code here.

When we spoke to the angular team during the ng conference they mentioned that we might run into this problem if we are bootstrapping the ng2 application first and then ng1 application, they suggested to switch the bootstrapping process to do ng1 first and then ng2 will solve this problem. We haven't tried the switching bootstrap sequence yet, but hopefully that will solve your problem.

Body:
I am working on upgrading an AngularJS app to angular.
But i have now gotten stuck.
I am tryting to get angular to handle the home route and doesn't work. The error appears to come from the upgraded service.

When i let angularJS handle the route it works fine using the same components.

App-routing.module

class HybridUrlHandlingStrategy implements UrlHandlingStrategy {
  // use only process the `home` url
  shouldProcessUrl(url:UrlTree) {
    console.log(url.toString());
    return url.toString() === '/' || url.toString() ==='/home' ;
  }
  extract(url: UrlTree) { return url; }
  merge(url: UrlTree, whole: UrlTree) { return url; }
}

const appRoutes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', component: HomeComponentNg2 }
];

@NgModule({
    imports:[
        RouterModule.forRoot(appRoutes)
    ],
    exports: [RouterModule ],
    providers:[
    { provide: UrlHandlingStrategy, useClass: HybridUrlHandlingStrategy }
    ]
})

export class AppRoutingModule { }

ajs-upgraded-providers.ts

export function statsServiceFactory(i: any) {
  return i.get('StatsService');
}
export const StatsServiceProvider = {
  provide: StatsService,
  useFactory: statsServiceFactory,
  deps: ['$injector']
};

export function authServiceFactory(i:any){
  return i.get('AuthService');
}

export const AuthServiceProvider = {
  provide: AuthService,
  useFactory: authServiceFactory,
  deps: ['$injector']

stats.service

export class StatsService {
    static $inject = ['$http'];
    constructor(private $http) {
        this.$http = $http;
    };

    getEmplStats() {
        console.log('getEmplstats');
        return this.$http.get('./src/app/JSON/employeeStats.json')
            .then(res => {
            console.log(res);
            return res
        }).catch(error => {
            console.log(error);
        })
    };

    getCustStats() {
        console.log('getCustStats');
        return this.$http.get('./src/app/JSON/customerStats.json')
            .then(res => {
            console.log(" getCustStats "+res);
            return res
        }).catch(error => {
            console.log(error);
        })
    }
}
export default StatsService;

The error

core.es5.js?0445:1084 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'get' of undefined
TypeError: Cannot read property 'get' of undefined
    at statsServiceFactory (eval at 327 (http://localhost:8080/app.js:653:1), <anonymous>:6:13)
    at Ng2AppModuleInjector.get (ng:///Ng2AppModule/module.ngfactory.js:161:69)
    at Ng2AppModuleInjector.getInternal (ng:///Ng2AppModule/module.ngfactory.js:271:52)
    at Ng2AppModuleInjector.NgModuleInjector.get (eval at <anonymous> (http://localhost:8080/vendor.js:84:1), <anonymous>:3783:44)
    at resolveDep (eval at <anonymous> (http://localhost:8080/vendor.js:84:1), <anonymous>:11245:45)

I just dont understand why letting AngularJS handle the route it seems to go fine but if i let Angular handle it, it falls apart.
Any help would be apreciated

edit:Added the customer-stats.ng2.component

@Component({
  selector: 'customer-stats2',
  templateUrl: './customer-stats.ng2.component.html'
})

export class CustomerStatsComponentNg2 implements OnInit{
    customerStats:any;

    constructor(private ss:StatsService){
    }

    ngOnInit()
    {
        console.log('ngoninit cust stats ')
        this.ss.getCustStats().
            then(custStats => this.customerStats = custStats.data)
           .then(error => console.log(error))
    }
}


问:
when i type _ (underscore) in my search form based on php , why results still come out?
```<code>$i_name  = mysqli_real_escape_string($con,$_GET['search']);

$search_item = "SELECT * FROM items WHERE itemname LIKE '%$i_name%' ORDER by 1 DESC LIMIT 5";
$find_item  =  mysqli_query($con,$search_item);
$count_item =  mysqli_num_rows($find_item);
</code>```

What am I doing wrong?

答:
Underscore is a special character in the SQL like syntax

It means match any one character, you'll have to escape it with a \, you might also want to escape % as well.

```<code>$i_name = str_replace(["_","%"], ["\_","\%"], $i_name);
</code>```

Body:
$i_name  = mysqli_real_escape_string($con,$_GET['search']);

$search_item = "SELECT * FROM items WHERE itemname LIKE '%$i_name%' ORDER by 1 DESC LIMIT 5";
$find_item  =  mysqli_query($con,$search_item);
$count_item =  mysqli_num_rows($find_item);

What am I doing wrong?

Body:
Underscore is a special character in the SQL like syntax

It means match any one character, you'll have to escape it with a \, you might also want to escape % as well.

$i_name = str_replace(["_","%"], ["\_","\%"], $i_name);


问:
MVC 5 Windows Authentication in AuthorizeAttribute and Service layer
I have a 3 tier MVC solution:  MVC Web - Business Layer - Data Access Layer

I have custom tables for users and groups in a database back-end, the user groups are mapped to a custom permission structure.  The authentication needs to check for presence of the user and the authorisation needs to verify what the user can do based on their permissions.

I can perform the authentication and authorization by implementing a custom AuthorizeAttribute and asking the service level if the HttpContext.User.Identity.Name exists in the user table and also verify the user permissions based on the controller and action.

However, the service level needs to authorise the user again when being called from the action in the controller.   This allows finer control over what the user can and can't do - for example, there are some fields that are read-only or hidden depending on the user group membership.

The issue being that I will end up authenticating and authorizing the user both in the AuthorizeAttribute of the controller action and from within the controller action itself (via the service level).

This is a design issue more than anything else but wanted to see if I am approaching the problem in the best way!

答: If I understand your question correctly, you have a requirement to check user permissions/role on your service layer and perform some logic on the basis of that. The answer really depends on what is the type of service layer you are using? Is it a web API or interface based service contracts. IF you are using web api then, you can inject token in Authorization header before calling your web api controller actions which is the common architecture for SPA using MVC and Web Api. In this scenario web api and MVC need not to be hosted on the same server since you are using Bearer token approach. If you are using cookie based authentication then that's a different case.</p>


问:
R: Dynamically referencing column names when using "$" or "[:]" syntax?
Let's say in R I have a data frame (called df) with a bunch of columns containing integer data named "Var1foo", "Var2foo", and so on.

Now suppose I want to create a new column called sum1 that adds up everything between "Var3foo" and "Var6foo". I might do:

```<code>df$sum1 <- rowSums(df[Var3foo:Var6foo])
</code>```

Or, I might do something a bit more complicated and create a new column called foobar with apply() like so:

```<code>eenie = 3
meenie = 2
df$foobar <- apply(df, 1, function(x) if (sum(x[Var2foo:Var7foo]) == eenie & sum(x[1:Var3foo]) != meenie) 1 else 0)
</code>```

The problem is I always have to explicitly write out the column names or index when referring to those columns. What if I want to refer to column "Varxfoo" where x <- 8 or "Varyfoo" where y <- 12?

What I mean is, I wouldn't be able to do df$paste0("Var", x, "foo") or sum(x[paste0("Var", x, "foo"):paste0("Var", y, "foo")]).

I also considered using dplyr::mutate() to create df$sum1 and df$foobar but it seems to also need explicit column (variable) names.

What should I do? Thanks!!

答:
A simple solution would be directly referencing the columns, with

```<code>sum(df[,x:y])
</code>```

Of course this only works if the columns are in order.

Body:
Let's say in R I have a data frame (called df) with a bunch of columns containing integer data named "Var1foo", "Var2foo", and so on.

Now suppose I want to create a new column called sum1 that adds up everything between "Var3foo" and "Var6foo". I might do:

df$sum1 <- rowSums(df[Var3foo:Var6foo])

Or, I might do something a bit more complicated and create a new column called foobar with apply() like so:

eenie = 3
meenie = 2
df$foobar <- apply(df, 1, function(x) if (sum(x[Var2foo:Var7foo]) == eenie & sum(x[1:Var3foo]) != meenie) 1 else 0)

The problem is I always have to explicitly write out the column names or index when referring to those columns. What if I want to refer to column "Varxfoo" where x <- 8 or "Varyfoo" where y <- 12?

What I mean is, I wouldn't be able to do df$paste0("Var", x, "foo") or sum(x[paste0("Var", x, "foo"):paste0("Var", y, "foo")]).

I also considered using dplyr::mutate() to create df$sum1 and df$foobar but it seems to also need explicit column (variable) names.

What should I do? Thanks!!

Body:
A simple solution would be directly referencing the columns, with

sum(df[,x:y])

Of course this only works if the columns are in order.


问:
Understanding the Scala Map object when mapping to the head of a list
Hi I have the following data and want to map it to the first item in the second parameter. So for:

```<code>1 -> List((1,11))
1 -> List((1,1), (1,111))
</code>```

I want:

```<code>(1,11)
(1,1)
</code>```

When this data is in an RDD I can do the following:

```<code>scala> val m = sc.parallelize(Seq(11 -> List((1,11)), 1 -> List((1,1),(1,111))))
m: org.apache.spark.rdd.RDD[(Int, List[(Int, Int)])] = ParallelCollectionRDD[198] at parallelize at <console>:47

scala> m.map(_._2.head).collect.foreach(println)
(1,11)
(1,1)
</code>```

However, when it is in a Map object (result of a groupBy) I get the following:

```<code>scala> val m = Map(11 -> List((1,11)), 1 -> List((1,1)))
m: scala.collection.immutable.Map[Int,List[(Int, Int)]] = Map(11 -> List((1,11)), 1 -> List((1,1), (1,111)))

scala> m.map(_._2.head)
res1: scala.collection.immutable.Map[Int,Int] = Map(1 -> 1)
</code>```

When I map to the whole list I get what I would expect, but not when I call head on it

```<code>scala> m.map(_._2)
res2: scala.collection.immutable.Iterable[List[(Int, Int)]] = List(List((1,11)), List((1,1), (1,111)))
</code>```

I can also get the result I want if I do either of the following:

```<code>scala> m.map(_._2).map(_.head)
res4: scala.collection.immutable.Iterable[(Int, Int)] = List((1,11), (1,1))

scala> m.values.map(_.head)
res5: Iterable[(Int, Int)] = List((1,11), (1,1))
</code>```

Could someone explain please what is going on here?

答:
This is a bit tricky and depends on the implicit parameter CanBuildFrom of the map. Depending the output type of your function f it will be able to build one structure or the other (it will be built by the implicit CanBuildFrom).

```<code>m.map(_._2.head) // The passed function retrieves a pair (Int, Int)
</code>```

There is a implicit CanBuildFrom from (A, A) to Map[A,A], that object is passed to your map implicitly, that's why in that case the the returned object is Map[Int, Int]

On the other case you have

```<code>m.map(_._2) // The passed function retrieves a List[(Int, Int)]
</code>```

The implicit CanBuildFrom for List[A] will build a Iterable[A], in this case from List[(Int, Int)] to Iterable[(Int, Int)]

Body:
Hi I have the following data and want to map it to the first item in the second parameter. So for:

1 -> List((1,11))
1 -> List((1,1), (1,111))

I want:

(1,11)
(1,1)

When this data is in an RDD I can do the following:

scala> val m = sc.parallelize(Seq(11 -> List((1,11)), 1 -> List((1,1),(1,111))))
m: org.apache.spark.rdd.RDD[(Int, List[(Int, Int)])] = ParallelCollectionRDD[198] at parallelize at <console>:47

scala> m.map(_._2.head).collect.foreach(println)
(1,11)
(1,1)

However, when it is in a Map object (result of a groupBy) I get the following:

scala> val m = Map(11 -> List((1,11)), 1 -> List((1,1)))
m: scala.collection.immutable.Map[Int,List[(Int, Int)]] = Map(11 -> List((1,11)), 1 -> List((1,1), (1,111)))

scala> m.map(_._2.head)
res1: scala.collection.immutable.Map[Int,Int] = Map(1 -> 1)

When I map to the whole list I get what I would expect, but not when I call head on it

scala> m.map(_._2)
res2: scala.collection.immutable.Iterable[List[(Int, Int)]] = List(List((1,11)), List((1,1), (1,111)))

I can also get the result I want if I do either of the following:

scala> m.map(_._2).map(_.head)
res4: scala.collection.immutable.Iterable[(Int, Int)] = List((1,11), (1,1))

scala> m.values.map(_.head)
res5: Iterable[(Int, Int)] = List((1,11), (1,1))

Could someone explain please what is going on here?

Body:
This is a bit tricky and depends on the implicit parameter CanBuildFrom of the map. Depending the output type of your function f it will be able to build one structure or the other (it will be built by the implicit CanBuildFrom).

m.map(_._2.head) // The passed function retrieves a pair (Int, Int)

There is a implicit CanBuildFrom from (A, A) to Map[A,A], that object is passed to your map implicitly, that's why in that case the the returned object is Map[Int, Int]

On the other case you have

m.map(_._2) // The passed function retrieves a List[(Int, Int)]

The implicit CanBuildFrom for List[A] will build a Iterable[A], in this case from List[(Int, Int)] to Iterable[(Int, Int)]


问:
sabre GetHotelImageRQ Error
I am using Sabre's soap api and trying to get a hotel image using GetHotelImageRQ. Here's my request xml:

```<code>    <GetHotelImageRQ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" version="1.0.0">
      <HotelRefs xmlns="http://services.sabre.com/hotel/image/v1">
         <HotelRef HotelCode="0027857" CodeContext="Sabre"/>
      </HotelRefs>
      <ImageRef xmlns="http://services.sabre.com/hotel/image/v1" Type="THUMBNAIL" CategoryCode="1" LanguageCode="EN"/>
    </GetHotelImageRQ>
</code>```

However I'm getting the following error : Service GetHotelImageRQ:GetHotelImageRQ:1.0.0 not found

I don't know what's wrong and My request matches the schema. Thanks for your help.

答:
Try removing the Service node from the envelope, or sending a null value in it.

```<code><Service />
</code>```

Title: sabre GetHotelImageRQ Error

Body:
I am using Sabre's soap api and trying to get a hotel image using GetHotelImageRQ. Here's my request xml:

    <GetHotelImageRQ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" version="1.0.0">
      <HotelRefs xmlns="http://services.sabre.com/hotel/image/v1">
         <HotelRef HotelCode="0027857" CodeContext="Sabre"/>
      </HotelRefs>
      <ImageRef xmlns="http://services.sabre.com/hotel/image/v1" Type="THUMBNAIL" CategoryCode="1" LanguageCode="EN"/>
    </GetHotelImageRQ>

However I'm getting the following error : Service GetHotelImageRQ:GetHotelImageRQ:1.0.0 not found

I don't know what's wrong and My request matches the schema. Thanks for your help.

Body:
Try removing the Service node from the envelope, or sending a null value in it.

<Service />


问:
parsing class instance methods with custom grammar in python
So I have a problem I'm trying to solve in which I have two fundamental classes CMIX and C, whereby CMIX contains a list of instances of C: [C1, C2, .... Cn] which will be manipulated by a custom grammar (string values operators - "+", "-", "", "(", ")", but in the sense that there is the ability to embed extra logic into operations. For example, a [C1 + C2 + ... + Cn] composition would call C.foo() for each C1,C2,...Cn, and then add those results. Similarly, a composition of grammar terms with the object set, e.g.: [C1 "" "(" C1 "+" C2 "*" "("C2"+"C2")"")"] would call C1.foo(), C2.foo(), and then combine those results according to normal mathematical evaluation. Initially, I just want to deal with basic math operations like * + ( ) but would like to be able to extend it later for custom (non math) terms .

A basic representative sketch of the class functionality is as follows (this is mainly conceptual; especially the CMIX, as I'm unsure of the best way to go about the parsing syntax logic)

```<code>class CMIX():
   self.C_list = []  # List of instances of type C
   self.grammar = []
   def my_val(self, val):
      ## call every .foo(val=val) in self.C_list, and apply the grammar rules accordingly.

class C():
   def __init__(self, location):
      self.location= location
   def my_val(self, val):
      return val * 2
   def check_location(self):
      if self.location == "antarctica":
         return "cold"
      elif self.location == "moon":
         return "bouncy"
      else:
         return "lost"
</code>```

for example, say we have defined the global grammar operator

+ means if C.check_location() == "lost" then return -100*C.my_val(val) otherwise just return C.m

the grammar said C1 + C2, and C1.location="lost", C2.location="antarctica", then CMIX.my_val(20) would evaluate like: -100*C1.my_val(20) + C2.my_val(20)

Is there an existing easy way to do this in python? Or perhaps a lightweight library that allows one to create such evaluation rules. I have found for instance https://github.com/pydata/numexpr however this applies directly onto datatypes, whereas it should apply onto the object layer, apply custom logic, and then execute the standard math grammar order of operations.

Any direction for trying to do this is greatly appreciated!
regards

答: Pyparsing makes it pretty easy to define infix notation parsers, and can wrap operators and operands in classes to do standard or customized behavior. See this question and its pyparsing-based solution: pyparsing nestedExpr and nested parentheses</p>

Body:
So I have a problem I'm trying to solve in which I have two fundamental classes CMIX and C, whereby CMIX contains a list of instances of C: [C1, C2, .... Cn] which will be manipulated by a custom grammar (string values operators - "+", "-", "", "(", ")", but in the sense that there is the ability to embed extra logic into operations. For example, a [C1 + C2 + ... + Cn] composition would call C.foo() for each C1,C2,...Cn, and then add those results. Similarly, a composition of grammar terms with the object set, e.g.: [C1 "" "(" C1 "+" C2 "*" "("C2"+"C2")"")"] would call C1.foo(), C2.foo(), and then combine those results according to normal mathematical evaluation. Initially, I just want to deal with basic math operations like * + ( ) but would like to be able to extend it later for custom (non math) terms .

A basic representative sketch of the class functionality is as follows (this is mainly conceptual; especially the CMIX, as I'm unsure of the best way to go about the parsing syntax logic)

class CMIX():
   self.C_list = []  # List of instances of type C
   self.grammar = []
   def my_val(self, val):
      ## call every .foo(val=val) in self.C_list, and apply the grammar rules accordingly.

class C():
   def __init__(self, location):
      self.location= location
   def my_val(self, val):
      return val * 2
   def check_location(self):
      if self.location == "antarctica":
         return "cold"
      elif self.location == "moon":
         return "bouncy"
      else:
         return "lost"

for example, say we have defined the global grammar operator

+ means if C.check_location() == "lost" then return -100*C.my_val(val) otherwise just return C.m

the grammar said C1 + C2, and C1.location="lost", C2.location="antarctica", then CMIX.my_val(20) would evaluate like: -100*C1.my_val(20) + C2.my_val(20)

Is there an existing easy way to do this in python? Or perhaps a lightweight library that allows one to create such evaluation rules. I have found for instance https://github.com/pydata/numexpr however this applies directly onto datatypes, whereas it should apply onto the object layer, apply custom logic, and then execute the standard math grammar order of operations.

Any direction for trying to do this is greatly appreciated!
regards


问:
Retrieve old searches from Google web history
I want to retrieve old Google searches which I did a few years/months back and that are present in Google web history.  How can I programmatically retrieve them all?

https://www.google.com/history/?output=rss only provides recent Google searches, but not all of them.

Also this question : How can I retrieve my Google search history? doesn't provide any answer for my question!

答:
```<code>static void GetGoogleWebHistory(int month, int day, int yr, string UserName, string Pass)
{
    string iURL = "http://www.google.com/history/lookup?month=" + month + "&day=" + day + "&yr=" + yr + "&output=rss";
    WebClient client = new WebClient();
    GDataCredentials gdc = new GDataCredentials(UserName, Pass);
    RequestSettings rs = new RequestSettings(Guid.NewGuid().ToString(), gdc);
    XmlDocument XDoc = new XmlDocument();
    XDoc.LoadXml(client.DownloadString(iURL));
}
</code>```


问:
how can I convert string into HTML. I want the actual href to show/display instead of the text
how can I convert string into HTML. I want the actual href to show/display instead of the text. </p>

```<code>    var zzz = "test";
    var value0 = 14251876;
    var value1 = "AAAA";

    var EmailSubject = 'Transcription Assigned   Due (' + zzz + ')';
    var EmailBody = 'Dear ' + zzz + ',\n\n' + 'A dictation for the following Service has been assigned to you;\n\n' + 'Service Name: ' + zzz + '\n\n' + 'Thank you,\n' + 'Assessments\n' + '(416) 111 - 2222';
    EmailBody = EmailBody + $($.parseHTML('<div><a href="/Apps/app_editevent.jsp?eventid=' + value1 + '" target="_blank">' + value0 + '</a></div>'));
    send_msg(false,'',20,0,'mailer@test.ca',1081636,'',EmailSubject,EmailBody);
</code>```

答:
I think you are not getting link of href.</p>

```<code>var zzz = "test";
var value0 = 14251876;
        var value1 = "AAAA";
        var EmailSubject = 'Transcription Assigned   Due (' + zzz + ')';
        var EmailBody = 'Dear ' + zzz + ',\n\n' + 'A dictation for the following Service has been assigned to you;\n\n' + 'Service Name: ' + zzz + '\n\n' + 'Thank you,\n' + 'Assessments\n' + '(416) 111 - 2222';
        EmailBody = EmailBody + '<div><a href="/Apps/app_editevent.jsp?eventid=' + value1 + '" target="_blank">' + value0 + '</a></div>';
        document.getElementById('inner').innerHTML = EmailBody;
</code>```

Body:
how can I convert string into HTML. I want the actual href to show/display instead of the text.

    var zzz = "test";
    var value0 = 14251876;
    var value1 = "AAAA";

    var EmailSubject = 'Transcription Assigned   Due (' + zzz + ')';
    var EmailBody = 'Dear ' + zzz + ',\n\n' + 'A dictation for the following Service has been assigned to you;\n\n' + 'Service Name: ' + zzz + '\n\n' + 'Thank you,\n' + 'Assessments\n' + '(416) 111 - 2222';
    EmailBody = EmailBody + $($.parseHTML('
' + value0 + '
'));
    send_msg(false,'',20,0,'mailer@test.ca',1081636,'',EmailSubject,EmailBody);

Body:
I think you are not getting link of href.

var zzz = "test";
var value0 = 14251876;
        var value1 = "AAAA";
        var EmailSubject = 'Transcription Assigned   Due (' + zzz + ')';
        var EmailBody = 'Dear ' + zzz + ',\n\n' + 'A dictation for the following Service has been assigned to you;\n\n' + 'Service Name: ' + zzz + '\n\n' + 'Thank you,\n' + 'Assessments\n' + '(416) 111 - 2222';
        EmailBody = EmailBody + '<div><a href="/Apps/app_editevent.jsp?eventid=' + value1 + '" target="_blank">' + value0 + '</a></div>';
        document.getElementById('inner').innerHTML = EmailBody;


问:
How to tune a MLPRegressor?
I currently have a dataset with variables and observations. I want to predict a variable (demand), which is a continuous one, thus I need to use a Regression model. I tried with Linear Regression, and evaluated it using the R2 metric, which was around 0.85. I wanted to evaluate its performance with other models, and one of them was the NNs. I believe that Neural Networks are more suitable in other task like classification, nevertheless I wanted to give them a try.

I decided to use scikit-learn mainly because it offers both models (Linear Regression and Multi Layer Perceptron), the thing is that the R2 metric was way too far and bad compared to the Linear Regression's one. Thus, I concluded that I am missing many important configurations. Below you can see my code and how the data comes.

My data has the following columns, only demand (which is my label), population,gdp, day and year are numerical continuous, the rest are categorical.

```<code>['demand','holy','gdp','population', 'day','year', 'f0', 'f1', 'f2', 'f3', 'f4','f5', 'f6', 'f7', 'f8', 'f9', 'f10', 'f11', 'f12', 'f13', 'f14', 'f15', 'f16', 'f17', 'f18', 'f19', 'f20', 'f21', 'f22', 'f23', 'g0', 'g1', 'g2', 'g3', 'g4', 'g5', 'g6', 'g7', 'g8', 'g9', 'g10', 'g11']
</code>```

This is what I actually do, I removed some outputs.

```<code>import pandas as pd
import numpy as np
import math as math

from sklearn.linear_model import LinearRegression
from sklearn.neural_network import MLPRegressor
from sklearn.metrics import r2_score

training_data, validation_data = np.split(data.sample(frac=1), [int(.8*len(data))])

linear_model = LinearRegression().fit(training_data[[c for c in data.columns if c != "demand"]], training_data[["demand"]])

validation_data_predictions = linear_model.predict(validation_data[[c for c in training_data.columns if c != "demand"]])

validation_predictions_pd = pd.DataFrame(data=validation_data_predictions,
                                         index=validation_data.index.values,
                                         columns=["prediction"])

# join both pandas
result_df = validation_data.join(validation_predictions_pd, how="inner")

r2_error = r2_score(y_true=result_df[["demand"]], y_pred=result_df[["prediction"]], multioutput="uniform_average")

print(r2_error) # outputs 0.85

# NN section
clf = MLPRegressor(hidden_layer_sizes=(10,), max_iter=100000)

neural_model = clf.fit(training_data[[c for c in training_data.columns if c != "demand"]], training_data[["demand"]])

validation_data_predictions = neural_model.predict(validation_data[[c for c in training_data.columns if c != "demand"]])

validation_predictions_pd = pd.DataFrame(data=validation_data_predictions,
                                     index=validation_data.index.values,
                                     columns=["prediction"])

result_df = validation_data.join(validation_predictions_pd, how="inner")

r2_error = r2_score(y_true=result_df[["demand"]], y_pred=result_df[["prediction"]], multioutput="uniform_average")
print(r2_error) # outputs 0.23
</code>```

So, as you can see the NN´s performance is very poor. And I think its performance can be improved, any hints?

答:
MLP is sensitive to feature scaling. Have you normalzied your data?

Modify your network structure: add more hidden layers and change number of perceptrons of each layer

change activation function to sigmod/tanh/relu etc.

Title: How to tune a MLPRegressor?

Body:
I currently have a dataset with variables and observations. I want to predict a variable (demand), which is a continuous one, thus I need to use a Regression model. I tried with Linear Regression, and evaluated it using the R2 metric, which was around 0.85. I wanted to evaluate its performance with other models, and one of them was the NNs. I believe that Neural Networks are more suitable in other task like classification, nevertheless I wanted to give them a try.

I decided to use scikit-learn mainly because it offers both models (Linear Regression and Multi Layer Perceptron), the thing is that the R2 metric was way too far and bad compared to the Linear Regression's one. Thus, I concluded that I am missing many important configurations. Below you can see my code and how the data comes.

My data has the following columns, only demand (which is my label), population,gdp, day and year are numerical continuous, the rest are categorical.

['demand','holy','gdp','population', 'day','year', 'f0', 'f1', 'f2', 'f3', 'f4','f5', 'f6', 'f7', 'f8', 'f9', 'f10', 'f11', 'f12', 'f13', 'f14', 'f15', 'f16', 'f17', 'f18', 'f19', 'f20', 'f21', 'f22', 'f23', 'g0', 'g1', 'g2', 'g3', 'g4', 'g5', 'g6', 'g7', 'g8', 'g9', 'g10', 'g11']

This is what I actually do, I removed some outputs.

import pandas as pd
import numpy as np
import math as math

from sklearn.linear_model import LinearRegression
from sklearn.neural_network import MLPRegressor
from sklearn.metrics import r2_score

training_data, validation_data = np.split(data.sample(frac=1), [int(.8*len(data))])

linear_model = LinearRegression().fit(training_data[[c for c in data.columns if c != "demand"]], training_data[["demand"]])

validation_data_predictions = linear_model.predict(validation_data[[c for c in training_data.columns if c != "demand"]])

validation_predictions_pd = pd.DataFrame(data=validation_data_predictions,
                                         index=validation_data.index.values,
                                         columns=["prediction"])

# join both pandas
result_df = validation_data.join(validation_predictions_pd, how="inner")

r2_error = r2_score(y_true=result_df[["demand"]], y_pred=result_df[["prediction"]], multioutput="uniform_average")

print(r2_error) # outputs 0.85

# NN section
clf = MLPRegressor(hidden_layer_sizes=(10,), max_iter=100000)

neural_model = clf.fit(training_data[[c for c in training_data.columns if c != "demand"]], training_data[["demand"]])

validation_data_predictions = neural_model.predict(validation_data[[c for c in training_data.columns if c != "demand"]])

validation_predictions_pd = pd.DataFrame(data=validation_data_predictions,
                                     index=validation_data.index.values,
                                     columns=["prediction"])

result_df = validation_data.join(validation_predictions_pd, how="inner")

r2_error = r2_score(y_true=result_df[["demand"]], y_pred=result_df[["prediction"]], multioutput="uniform_average")
print(r2_error) # outputs 0.23

So, as you can see the NN´s performance is very poor. And I think its performance can be improved, any hints?


问:
Button is not focusable because it is out of reach - tvOS Swift
I am creating a tvOS movie browser. This view holds the movie description and displays 4 things: the movie cover image, the movie description text, a watch button, and a collection view of the movie's cast (blue boxes). The preferredFocusView is set the the watchButton. However, once I switch focus to the collection view below it, I am not able to focus on the watch button again if the cast is too short.

The watch button is focusable here since the cast extends to just below the button

The watch button IS NOT focusable here

Ultimately, I know I can fix it by rearranging the UI so that the watch button is directly above the first cast member, but I want to know if there is an actual way to achieve the original look I was going for.

Thanks!

答:
To fix this, I added a focus guide to my view controller.

```<code>private var focusGuide: UIFocusGuide!
</code>```

and in viewDidLoad:

```<code>// Create focus guide
focusGuide = UIFocusGuide()
view.addLayoutGuide(focusGuide)

focusGuide.leftAnchor.constraint(equalTo: header.imageView.leftAnchor).isActive = true
focusGuide.bottomAnchor.constraint(equalTo: header.imageView.bottomAnchor).isActive = true
focusGuide.widthAnchor.constraint(equalTo: header.imageView.widthAnchor).isActive = true
focusGuide.heightAnchor.constraint(equalTo: header.watchButton.heightAnchor).isActive = true
</code>```

Body:
To fix this, I added a focus guide to my view controller.

private var focusGuide: UIFocusGuide!

and in viewDidLoad:

// Create focus guide
focusGuide = UIFocusGuide()
view.addLayoutGuide(focusGuide)

focusGuide.leftAnchor.constraint(equalTo: header.imageView.leftAnchor).isActive = true
focusGuide.bottomAnchor.constraint(equalTo: header.imageView.bottomAnchor).isActive = true
focusGuide.widthAnchor.constraint(equalTo: header.imageView.widthAnchor).isActive = true
focusGuide.heightAnchor.constraint(equalTo: header.watchButton.heightAnchor).isActive = true


问:
ASP.NET MVC - How to call void controller method without leaving the view?
Question background:

I am implementing some basic 'shopping cart' logic to an MVC app. Currently when I click a link - denoted as 'Add To Cart' on the screen shot below this calls to an 'AddToCart' method in the 'ProductController' as shown:

Product.cshtml code:

```<code>@Html.ActionLink("Add To Cart", "AddToCart")
</code>```

'AddToCart' method in the ProductController:

```<code>public void AddToCart()
{
   //Logic to add item to the cart.
}
</code>```

The issue:

Not an issue as such but currently when I click the 'Add To Cart' button on the ActionLink on the ProductDetail.cshtml view the page calls the 'AddToCart' method on the ProductController and gives a blank view on the page - as shown below. I want the view to stay on 'ProductDetail.cshtml' and just call the 'AddToCart' method, how do I do this?

答:
using System.Web.Mvc;

using System.Web.Mvc.Html;

```<code>public ActionResult Index()
{
    HtmlHelper helper = new HtmlHelper(new ViewContext(ControllerContext, new WebFormView(ControllerContext, "Index"), new ViewDataDictionary(), new TempDataDictionary(), new System.IO.StringWriter()), new ViewPage());
    helper.RenderAction("Index2");

    return View();
}

public void Index2(/*your arg*/)
{
    //your code

}
</code>```

Body:
Question background:

I am implementing some basic 'shopping cart' logic to an MVC app. Currently when I click a link - denoted as 'Add To Cart' on the screen shot below this calls to an 'AddToCart' method in the 'ProductController' as shown:

Product.cshtml code:

@Html.ActionLink("Add To Cart", "AddToCart")

'AddToCart' method in the ProductController:

public void AddToCart()
{
   //Logic to add item to the cart.
}

The issue:

Not an issue as such but currently when I click the 'Add To Cart' button on the ActionLink on the ProductDetail.cshtml view the page calls the 'AddToCart' method on the ProductController and gives a blank view on the page - as shown below. I want the view to stay on 'ProductDetail.cshtml' and just call the 'AddToCart' method, how do I do this?

Body:
using System.Web.Mvc;

using System.Web.Mvc.Html;

public ActionResult Index()
{
    HtmlHelper helper = new HtmlHelper(new ViewContext(ControllerContext, new WebFormView(ControllerContext, "Index"), new ViewDataDictionary(), new TempDataDictionary(), new System.IO.StringWriter()), new ViewPage());
    helper.RenderAction("Index2");

    return View();
}

public void Index2(/*your arg*/)
{
    //your code

}


问:
Escaping ampersand within a string variable using sed
I am replacing the text SUBJECT with a value from an array variable like this:

```<code>#!/bin/bash

# array of subjects, the ampersand causes a problem.
subjects=("Digital Art" "Digital Photography" "3D Modelling & Animation")

echo $subjects[2] # Subject: 3D Modelling & Animation

sed -i -e "s/SUBJECT/${subjects[2]}/g" test.svg
</code>```

Instead of replacing the text SUBJECT, the resulting text looks like this:

```<code>3D Modelling SUBJECT Animation
</code>```

How can I include the ampersand as a literal & in sed and also have it echo correctly?

答:
```<code>sed -i -e "s/SUBJECT/${subjects[2]//&/\\&}/g" test.svg
</code>```

Body:
I am replacing the text SUBJECT with a value from an array variable like this:

#!/bin/bash

# array of subjects, the ampersand causes a problem.
subjects=("Digital Art" "Digital Photography" "3D Modelling & Animation")

echo $subjects[2] # Subject: 3D Modelling & Animation

sed -i -e "s/SUBJECT/${subjects[2]}/g" test.svg

Instead of replacing the text SUBJECT, the resulting text looks like this:

3D Modelling SUBJECT Animation

How can I include the ampersand as a literal & in sed and also have it echo correctly?


问:
Set Background in a LinearLayout from byte array
I have a LinearLayout with a default Background, but in some circumstances I need to set a custom Background from a byte[] data from Blob object in SQL Database.
I alreay have made the custom Adapter but I have no idea how do the image part.</p>

```<code>if (Ad.getAd_image().length > 0) {
    //Ad.getAd_image() is a byte[] object
    ad_image_layout.setBackground(???);
}
</code>```

答: Check out the decodeByteArray methods of BitmapFactory.  The byte array must be in one of the supported image formats.

Body:
I have a LinearLayout with a default Background, but in some circumstances I need to set a custom Background from a byte[] data from Blob object in SQL Database.
I alreay have made the custom Adapter but I have no idea how do the image part.

if (Ad.getAd_image().length > 0) {
    //Ad.getAd_image() is a byte[] object
    ad_image_layout.setBackground(???);
}


问:
I want to select xpath of the following dropdown list of Airports
Here if I type in something then the list of airports matching that text are shown up!! So is there a general way by which I can select the xpath for it? Here is the screenshot.enter image description here

and here is the HTML:

```<code><document>
<html lang="en">
<head>
<body>
<!-- Keeping body block so that it can be used by public site as well. -->
<nav class="navbar navbar-default navbar-static-top">
<div id="timezone-change-dialog" class="col-md-12 content content-confirmation hidden">
<div class="container-fluid">
<div class="row">
<div class="col-md-12 wizard-steps-container">
<div class="col-md-12 content">
<div class="row">
<div class="col-md-12">
<form id="id_create-shipment-step-2" class="form-horizontal has-validation-callback fv-form fv-form-bootstrap" role="form" method="post" enctype="multipart/form-data" novalidate="novalidate">
<button class="fv-hidden-submit" type="submit" style="display: none; width: 0px; height: 0px;"/>
<input name="csrfmiddlewaretoken" value="gk0wq70Am8U0sKat5IJ6f8nKquxYlZaz" autocomplete="off" type="hidden"/>
<div class="form-group">
<div class="form-group">
<div class="form-group">
<div id="pickup_airport" class="form-group" style="display: block;">
<label class="col-sm-4 control-label" for="">
<div class="col-sm-6 has-success">
<div class="typeahead-container result hint">
<div class="typeahead-field">
<div class="typeahead-result">
<ul class="typeahead-list">
<li class="typeahead-item">
<a href="javascript:;" data-group="airports" data-index="0">
<span>
(
<strong>AIR</strong>
) Aripuana
<strong>Air</strong>
port, Aripuana, MT, BR
</span>
</a>
</li>
<li class="typeahead-item">
<li class="typeahead-item active">
</code>```

答:
If the span contains text and it is under li tag then you can do that like this. </p>

<p>//span[contains(text(),'airports')]/parent::li</p>

Body:
Here if I type in something then the list of airports matching that text are shown up!! So is there a general way by which I can select the xpath for it? Here is the screenshot.enter image description here

and here is the HTML:

<document>

<form id="id_create-shipment-step-2" class="form-horizontal has-validation-callback fv-form fv-form-bootstrap" role="form" method="post" enctype="multipart/form-data" novalidate="novalidate">
<button class="fv-hidden-submit" type="submit" style="display: none; width: 0px; height: 0px;"/>
<input name="csrfmiddlewaretoken" value="gk0wq70Am8U0sKat5IJ6f8nKquxYlZaz" autocomplete="off" type="hidden"/>

(
AIR
) Aripuana
Air
port, Aripuana, MT, BR

Body:
If the span contains text and it is under li tag then you can do that like this.

//span[contains(text(),'airports')]/parent::li


问:
best way to sum up Matrix elements parallel in c#
What is the fastest most efficient way to sumUp all matrix elements parallel in .net 4.0 ?

using Parallel.For end in inner loop making lock(objectLock) { result += matrix[i, j] } is 2 times slowwer then sequential approach.

thanks for any hints,
bye

答:
ParallelEnumerable.Sum knows how to do the sum without needing either locking or interlocked operations (I assume it sums subsets on each thread, and then sums those results).

Assuming your matrix is IEnumerable<IEnumerable<numeric>>:

```<code>var sum = (from row in matrix.AsParallel()
           select row.Sum()).Sum();
</code>```

The AsParallel means the rows are processed in parallel, but the inner (column) sum is just Enumerable.Sum (unless the rows are very long, the overhead of concurrency will overwhelm any possible benefits).

Body:
ParallelEnumerable.Sum knows how to do the sum without needing either locking or interlocked operations (I assume it sums subsets on each thread, and then sums those results).

Assuming your matrix is IEnumerable<IEnumerable<numeric>>:

var sum = (from row in matrix.AsParallel()
           select row.Sum()).Sum();

The AsParallel means the rows are processed in parallel, but the inner (column) sum is just Enumerable.Sum (unless the rows are very long, the overhead of concurrency will overwhelm any possible benefits).


问:
How to open (expand) block element to the left?
lets say I have 2 block elements that have fixed position and look like this in a window:

```<code>--------------
|        xxx |
|        xxx |
|            |
|        xxx |
|        xxx |
|            |
--------------
</code>```

I want an element to expand to the left on hover, like this:

```<code>--------------
|        xxx |
|        xxx |
|            |
|     xxxxxx |
|     xxxxxx |
|            |
--------------
</code>```

However, right now it expands to the right. Working example can be seen here: https://jsfiddle.net/eeuho5vq/2/

Any solution would be highly appreciated.

答:
Use display: flex; flex-direction: column; align-items: flex-end; on the parent and that align the elements to the right.

 $(".container").each(function(){
  $(this).hover(function(){
   $(this).toggleClass("show");
  })
 })```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#wrapper {
  position: fixed;
  right: 1em;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.container {
  width: 2em;
  height: 2em;
  background: yellow;
  margin: 1em 0;
}

.container.show {
  width: 4em;
  height: 2em;
}</code>```

```

Body:
lets say I have 2 block elements that have fixed position and look like this in a window:

--------------
|        xxx |
|        xxx |
|            |
|        xxx |
|        xxx |
|            |
--------------

I want an element to expand to the left on hover, like this:

--------------
|        xxx |
|        xxx |
|            |
|     xxxxxx |
|     xxxxxx |
|            |
--------------

However, right now it expands to the right. Working example can be seen here: https://jsfiddle.net/eeuho5vq/2/

Any solution would be highly appreciated.

Body:
Use display: flex; flex-direction: column; align-items: flex-end; on the parent and that align the elements to the right.

 $(".container").each(function(){
  $(this).hover(function(){
   $(this).toggleClass("show");
  })
 })

#wrapper {
  position: fixed;
  right: 1em;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.container {
  width: 2em;
  height: 2em;
  background: yellow;
  margin: 1em 0;
}

.container.show {
  width: 4em;
  height: 2em;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
  <div class="container">
    <!--element 1-->
  </div>

  <div class="container">
    <!--element 2-->
  </div>

</div>


问:
Invalid login on create user event when working with Cloud Functions for Firebase and node mailer
I am using Cloud Functions for Firebase and Nodemailer and putting together code to fire welcome email. Following is the code I have:

```<code>const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

const nodemailer = require('nodemailer');
const gmailEmail = encodeURIComponent(functions.config().gmail.email);
const gmailPassword = encodeURIComponent(functions.config().gmail.password);

const mailTransport = nodemailer.createTransport(
`smtps://${gmailEmail}:${gmailPassword}@smtp.gmail.com`);
const APP_NAME = 'Test';

exports.sendWelcomeEmail = functions.auth.user().onCreate(event => {
    const user = event.data; // The Firebase user.
    const email = user.email; // The email of the user.
    const displayName = user.displayName; // The display name of the user.

    return sendWelcomeEmail(email, displayName);
});

function sendWelcomeEmail(email, displayName) {
    const mailOptions = {
        from: '"Test" <noreply@test.com>',
        to: email
    };

    // The user subscribed to the newsletter.
    mailOptions.subject = `Welcome to hell!`;
    mailOptions.text = `Hey I hope you will enjoy our service.`;
    return mailTransport.sendMail(mailOptions).then(() => {
        console.log('New welcome email sent to:', email);
    });
}
</code>```

I do have Allow Less secure Apps turned on

I do see my gmail address and password in the config. I have verified this by typing firebase functions:config:get in the command line

I am getting the following error

答:
I solved it just using the correct email address in from: the one you put in the config.

from: '"Test" <youremail@gmail.com>',

Body:
I am using Cloud Functions for Firebase and Nodemailer and putting together code to fire welcome email. Following is the code I have:

const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

const nodemailer = require('nodemailer');
const gmailEmail = encodeURIComponent(functions.config().gmail.email);
const gmailPassword = encodeURIComponent(functions.config().gmail.password);

const mailTransport = nodemailer.createTransport(
`smtps://${gmailEmail}:${gmailPassword}@smtp.gmail.com`);
const APP_NAME = 'Test';

exports.sendWelcomeEmail = functions.auth.user().onCreate(event => {
    const user = event.data; // The Firebase user.
    const email = user.email; // The email of the user.
    const displayName = user.displayName; // The display name of the user.

    return sendWelcomeEmail(email, displayName);
});

function sendWelcomeEmail(email, displayName) {
    const mailOptions = {
        from: '"Test" <noreply@test.com>',
        to: email
    };

    // The user subscribed to the newsletter.
    mailOptions.subject = `Welcome to hell!`;
    mailOptions.text = `Hey I hope you will enjoy our service.`;
    return mailTransport.sendMail(mailOptions).then(() => {
        console.log('New welcome email sent to:', email);
    });
}

I do have Allow Less secure Apps turned on

I do see my gmail address and password in the config. I have verified this by typing firebase functions:config:get in the command line

I am getting the following error


问:
IE 11 issue with flexbox item with max-width
In IE 11 when an item items don't properly center if they have maximum width property. This example however works in Chrome and Firefox.

JS Bin

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: blue;
  width: 100%;
}

.red {
  background-color: red;
  flex-grow: 1;
  display: flex;
  max-width: 200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="red">non centered box</div>
</div></code>```

答: Explicitly set width: calc(100%); so IE knows the box width and center it properly.

Body:
In IE 11 when an item items don't properly center if they have maximum width property. This example however works in Chrome and Firefox.

JS Bin

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: blue;
  width: 100%;
}

.red {
  background-color: red;
  flex-grow: 1;
  display: flex;
  max-width: 200px;
}

non centered box


问:
replacing shared library on AIX
I have a shared library (.so) on AIX
I know what all processes are using it.
I have stopped all the concerned processes.
I need to replace the above .so file (with the new library) using cp -p command.
But the above command is giving error:
"Cannot remove the running program"

While i am trying "cp -p -f" it is wroking fine,
But I need to use only "cp -p"
Any idea on this matter will be helpful.
Thanks.

答: used slibclean command,then "cp -p" worked fine.</p>

Title: replacing shared library on AIX


问:
VS Code + CMake : cmake.build not found
I have CMake working perfectly fine with Visual Studio 2015. I wanted to try VS Code with C++ and CMake extensions, but when I try to call the build command (configured to F7 by default with the CMake extension for VSCode), I only get the message:

```<code>command 'cmake.build' not found
</code>```

Is it trying to tell me it can't find CMake ? Because Cmake is installed and working so... I also tried changing in the settings to the full path to cmake with no success. I installed both CMake and CMake Tools from Extensions. Also the toolbar for CMake doesn't appear on the blue VSCode toolbar as shown in CMake Tools extension doc.

答:
Edit:

The author of that extension believes they've resolved this issue in the latest version 0.9.7.

https://github.com/vector-of-bool/vscode-cmake-tools/issues/157#issuecomment-307005140

So, I've just pushed 0.9.7:

No more dependency on twxs.cmake, so that shouldn't be causing any
  issues anymore

@ytimenkov fixed some version parsing code that was
  lying about what version of CMake was installed. Should fix issues
  people are seeing with pre-3.7 versions.

@ytimenkov added better
  errors when initialization failed. This should help create future
  tickets!

As such, I'm going to close this issue and ask that anyone
  with any further issues open a new ticket using the new error messages
  that appear during a failed initialization.

I too had this issue and was given a solution here in my ticket.

For some people, one of their dependencies isn't getting installed correctly on our system. So you need to install another additional extension to get it to work.

It's called "CMake" or "twxs.cmake" (actual package name) and can be found here: https://marketplace.visualstudio.com/items?itemName=twxs.cmake

If it still isn't working, some have reported that they needed to uninstall both extensions then reinstall them both to get it to work--making sure to restart VSCode.

Title: VS Code + CMake : cmake.build not found

Body:
I have CMake working perfectly fine with Visual Studio 2015. I wanted to try VS Code with C++ and CMake extensions, but when I try to call the build command (configured to F7 by default with the CMake extension for VSCode), I only get the message:

command 'cmake.build' not found

Is it trying to tell me it can't find CMake ? Because Cmake is installed and working so... I also tried changing in the settings to the full path to cmake with no success. I installed both CMake and CMake Tools from Extensions. Also the toolbar for CMake doesn't appear on the blue VSCode toolbar as shown in CMake Tools extension doc.


答:
Just removed parseHTML, It will work for you.</p>

```<code>        var zzz = "test";
        var value0 = 14251876;
        var value1 = "AAAA";
        var EmailSubject = 'Transcription Assigned   Due (' + zzz + ')';
        var EmailBody = 'Dear ' + zzz + ',\n\n' + 'A dictation for the following Service has been assigned to you;\n\n' + 'Service Name: ' + zzz + '\n\n' + 'Thank you,\n' + 'Assessments\n' + '(416) 111 - 2222';
        EmailBody = EmailBody + '<div><a href="/Apps/app_editevent.jsp?eventid=' + value1 + '" target="_blank">' + value0 + '</a></div>';
         send_msg(false,'',20,0,'mailer@test.ca',1081636,'',EmailSubject,EmailBody);
</code>```

Title: how can I convert string into HTML. I want the actual href to show/display instead of the text

Body:
Just removed parseHTML, It will work for you.

        var zzz = "test";
        var value0 = 14251876;
        var value1 = "AAAA";
        var EmailSubject = 'Transcription Assigned   Due (' + zzz + ')';
        var EmailBody = 'Dear ' + zzz + ',\n\n' + 'A dictation for the following Service has been assigned to you;\n\n' + 'Service Name: ' + zzz + '\n\n' + 'Thank you,\n' + 'Assessments\n' + '(416) 111 - 2222';
        EmailBody = EmailBody + '<div><a href="/Apps/app_editevent.jsp?eventid=' + value1 + '" target="_blank">' + value0 + '</a></div>';
         send_msg(false,'',20,0,'mailer@test.ca',1081636,'',EmailSubject,EmailBody);