问:
Structuring Database First model classes with MVVM in WPF App
I am following this course on integrating an MVVM architecture with an WPF app, but using code first. For my own app I am using database first, with only a
few tables.

This is my project structure, with the 3 layers, Model-View-ViewModel. In the course he creates two model classes, of course using code first in the model project, while the Data Access project handles migrations and the DbContext.

Now, when I use Database First, EF creates all the model classes for me, but the database context is included as well. My edmx is structured like this:

My question is what I need to place in which project? I'm aware that I have my view models in the UI project, which then use a data service to create a new context, but it seems I can do this all in the UI project.

答:
Personally, I would keep everything in the same project, separated by namespaces (folders) for each distinct area.

In my own project I have a UI folder for Views and ViewModels, then a separate folder for Models and a bunch of other folders for things such as helper classes.


来源: stackexchange

问:
What is the role of TimeDistributed layer in Keras?
I am trying to grasp what TimeDistributed wrapper does in Keras.

I get that TimeDistributed "applies a layer to every temporal slice of an input."

But I did some experiment and got the results that I cannot understand.

In short, in connection to LSTM layer, TimeDistributed and just Dense layer bear same results.

```<code>model = Sequential()
model.add(LSTM(5, input_shape = (10, 20), return_sequences = True))
model.add(TimeDistributed(Dense(1)))
print(model.output_shape)

model = Sequential()
model.add(LSTM(5, input_shape = (10, 20), return_sequences = True))
model.add((Dense(1)))
print(model.output_shape)
</code>```

For both models, I got output shape of (None, 10, 1).

Can anyone explain the difference between TimeDistributed and Dense layer after an RNN layer?

答:
In keras - while building a sequential model - usually the second dimension (one after sample dimension) - is related to a time dimension. This means that if for example, your data is 5-dim with (sample, time, width, length, channel) you could apply a convolutional layer using TimeDistributed (which is applicable to 4-dim with (sample, width, length, channel)) along a time dimension (applying the same layer to each time slice) in order to obtain 5-d output.

The case with Dense is that in keras from version 2.0 Dense is by default applied to only last dimension (e.g. if you apply Dense(10) to input with shape (n, m, o, p) you'll get output with shape (n, m, o, 10)) so in your case Dense and TimeDistributed(Dense) are equivalent.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to grasp what TimeDistributed wrapper does in Keras.

I get that TimeDistributed "applies a layer to every temporal slice of an input."

But I did some experiment and got the results that I cannot understand.

In short, in connection to LSTM layer, TimeDistributed and just Dense layer bear same results.

model = Sequential()
model.add(LSTM(5, input_shape = (10, 20), return_sequences = True))
model.add(TimeDistributed(Dense(1)))
print(model.output_shape)

model = Sequential()
model.add(LSTM(5, input_shape = (10, 20), return_sequences = True))
model.add((Dense(1)))
print(model.output_shape)

For both models, I got output shape of (None, 10, 1).

Can anyone explain the difference between TimeDistributed and Dense layer after an RNN layer?


问:
Select documents in Elasticsearch that have ANY of the provided objects within it's nested property
In my index I have a mapping that contains the locations property of type "nested". This property contains an array of locations. Each location is an object with the following structure:

```<code>{
    "id": string,
    "type": string
}
</code>```

On my website I want to select multiple locations and find all documents that have ANY of these locations I selected. I was able to search by one location but I have to modify my query somehow to search for many locations.

I have the following index set up:

```<code>"mappings": {
    "users": {
        "properties": {
            "locations": {
                "type": "nested",
                "properties": {
                    "id": {
                        "type": "text",
                        "fields": {
                            "keyword": {
                                "type": "keyword",
                                "ignore_above": 256
                            }
                        }
                    },
                    "type": {
                        "type": "text",
                        "fields": {
                            "keyword": {
                                "type": "keyword",
                                "ignore_above": 256
                            }
                        }
                    }
                }
            },
            "id": {
                "type": "long"
            }
        }
    }
}
</code>```

Example document:

```<code>{
    "locations": [
        {
            "id": "UA",
            "type": "country"
        },
        {
            "id": "RU",
            "type": "country"
        },
        {
            "id": "OC",
            "type": "continent"
        }
    ]
}
</code>```

My query that searches for users by location:

```<code>{
    "query": {
        "bool": {
            "must": [
                {
                    "nested": {
                        "path": "locations",
                        "query": {
                            "bool": {
                                "must": [
                                    {
                                        "match": { "locations.id": "RU" }
                                    },
                                    {
                                        "match": { "locations.type": "country" }
                                    }
                                ]
                            }
                        }
                    }
                }
            ]
        }
    }
}
</code>```

EDIT:
I also want to retreive documents which have locations.type equal to continent. In SQL it would look like

```<code>WHERE (id IN ('UA', 'RU') AND type = 'country')
OR (id IN ('EU', 'OC', 'NA') AND type = 'continent')
</code>```

答:
for multiple value search use Terms and for OR condition use should (see here):

```<code>{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "locations",
            "query": {
              "bool": {
                "should": [
                  {
                    "bool": {
                      "must": [
                        {
                          "terms": {
                            "locations.id": [
                              "UA",
                              "RU"
                            ]
                          }
                        },
                        {
                          "term": {
                            "locations.type": "country"
                          }
                        }
                      ]
                    }
                  },
                  {
                    "bool": {
                      "must": [
                        {
                          "terms": {
                            "locations.id": [
                              "EU",
                              "OC"
                            ]
                          }
                        },
                        {
                          "term": {
                            "locations.type": "continent"
                          }
                        }
                      ]
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  }
}
</code>```

Body:
In my index I have a mapping that contains the locations property of type "nested". This property contains an array of locations. Each location is an object with the following structure:

{
    "id": string,
    "type": string
}

On my website I want to select multiple locations and find all documents that have ANY of these locations I selected. I was able to search by one location but I have to modify my query somehow to search for many locations.

I have the following index set up:

"mappings": {
    "users": {
        "properties": {
            "locations": {
                "type": "nested",
                "properties": {
                    "id": {
                        "type": "text",
                        "fields": {
                            "keyword": {
                                "type": "keyword",
                                "ignore_above": 256
                            }
                        }
                    },
                    "type": {
                        "type": "text",
                        "fields": {
                            "keyword": {
                                "type": "keyword",
                                "ignore_above": 256
                            }
                        }
                    }
                }
            },
            "id": {
                "type": "long"
            }
        }
    }
}

Example document:

{
    "locations": [
        {
            "id": "UA",
            "type": "country"
        },
        {
            "id": "RU",
            "type": "country"
        },
        {
            "id": "OC",
            "type": "continent"
        }
    ]
}

My query that searches for users by location:

{
    "query": {
        "bool": {
            "must": [
                {
                    "nested": {
                        "path": "locations",
                        "query": {
                            "bool": {
                                "must": [
                                    {
                                        "match": { "locations.id": "RU" }
                                    },
                                    {
                                        "match": { "locations.type": "country" }
                                    }
                                ]
                            }
                        }
                    }
                }
            ]
        }
    }
}

EDIT:
I also want to retreive documents which have locations.type equal to continent. In SQL it would look like

WHERE (id IN ('UA', 'RU') AND type = 'country')
OR (id IN ('EU', 'OC', 'NA') AND type = 'continent')

Body:
for multiple value search use Terms and for OR condition use should (see here):

{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "locations",
            "query": {
              "bool": {
                "should": [
                  {
                    "bool": {
                      "must": [
                        {
                          "terms": {
                            "locations.id": [
                              "UA",
                              "RU"
                            ]
                          }
                        },
                        {
                          "term": {
                            "locations.type": "country"
                          }
                        }
                      ]
                    }
                  },
                  {
                    "bool": {
                      "must": [
                        {
                          "terms": {
                            "locations.id": [
                              "EU",
                              "OC"
                            ]
                          }
                        },
                        {
                          "term": {
                            "locations.type": "continent"
                          }
                        }
                      ]
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  }
}


问:
Rails: Has and belongs to many (HABTM) -- create association without creating other records
Spent all day on Google, but can't find an answer. :\

I have a HABTM relationship between Users and Core_Values.

```<code>class CoreValue < ActiveRecord::Base
  has_and_belongs_to_many :users

class User < ActiveRecord::Base
  has_and_belongs_to_many :core_values
</code>```

In my controller, I need to do two separate things:

If a CoreValue does not exist, create a new one and associate it with a given user id, and

Assuming I know a particular CoreValue does exist already, create the association without creating any new CoreValues or Users

For # 1, I've got this to work:

```<code>User.find(current_user.id).core_values.create({:value => v, :created_by => current_user.id})
</code>```

This creates a new CoreValue with :value and :created_by and creates the association.

For # 2, I've tried a few things, but can't quite seem to create the association ONLY.

Thanks for your help!

答:
Add a method in your user model:

```<code>class User < ActiveRecord::Base
  def assign_core_value(v)
    core_values.find_by_name(v) || ( self.core_values <<
      CoreValue.find_or_create_by_name(:name => v, :created_by => self)).last
  end
end
</code>```

The assign_core_value method meets requirement 1,2  and returns the core value assigned to the user (with the given name).

Now you can do the following:

```<code>current_user.assign_core_value(v)
</code>```

Note 1

Method logic is as follows:

1) Checks if the CoreValue is already associated with the user. If so no action is taken, core value is returned.

2) Checks if the CoreValue with the given name exists. If not creates the CoreValue. Associates the core value(created/found) with the user.

ContentLicense: CC BY-SA 2.5

Body:
Spent all day on Google, but can't find an answer. :\

I have a HABTM relationship between Users and Core_Values.

class CoreValue < ActiveRecord::Base
  has_and_belongs_to_many :users

class User < ActiveRecord::Base
  has_and_belongs_to_many :core_values

In my controller, I need to do two separate things:

If a CoreValue does not exist, create a new one and associate it with a given user id, and

Assuming I know a particular CoreValue does exist already, create the association without creating any new CoreValues or Users

For # 1, I've got this to work:

User.find(current_user.id).core_values.create({:value => v, :created_by => current_user.id})

This creates a new CoreValue with :value and :created_by and creates the association.

For # 2, I've tried a few things, but can't quite seem to create the association ONLY.

Thanks for your help!

Body:
Add a method in your user model:

class User < ActiveRecord::Base
  def assign_core_value(v)
    core_values.find_by_name(v) || ( self.core_values <<
      CoreValue.find_or_create_by_name(:name => v, :created_by => self)).last
  end
end

The assign_core_value method meets requirement 1,2  and returns the core value assigned to the user (with the given name).

Now you can do the following:

current_user.assign_core_value(v)

Note 1

Method logic is as follows:

1) Checks if the CoreValue is already associated with the user. If so no action is taken, core value is returned.

2) Checks if the CoreValue with the given name exists. If not creates the CoreValue. Associates the core value(created/found) with the user.


问:
-webkit-baseline-middle and -moz-middle-with-baseline
When using browsers web inspectors I came across two different and non-standard property for the CSS attribute vertical-align.

-webkit-baseline-middle is only available in Chrome while -moz-middle-with-baseline is available on Firefox. The naming is similar but NOT the same.

I couldn't find any information regarding these two on the web. They are not even listed on MDN.

My questions:

Are they part of any standards?

What is the expected behavior when
using them?

答:
@VSG24:

Are they part of any standards?

Both properties are not part of any standards, according to W3C CSS reference. They only seem to be used by Webkit and Gecko to behave correctly, as expected in CSS 2.1 specification:

Align the vertical midpoint of the box with the baseline of the parent box plus half the x-height of the parent.

CSS 2.1 specs, p170

@VSG24:

What is the expected behavior when using them?

After some search on the web, here's what I've found about -webkit-baseline-middle on the Safari CSS Reference:

vertical-align: -webkit-baseline-middle:

The center of the element is aligned with the baseline of the text.

I was unable to get any info about -moz-middle-with-baseline other than this one :

Q: Webkit-baseline-middle - are there alternatives?

A: the same, only for Mozilla
 >vertical-align: -moz-middle-with-baseline;

https://toster.ru/q/255210

Below is a test, you may try it using Webkit based browsers (such as Chrome) and Gecko (Firefox):

div {
  width: 15%;
  height: 100px;
  display: inline-block;
  box-sizing: border-box;
}

hr {
  width: 100%;
  position: absolute;
  top: 90px;
  height: 1px;
  background: hotpink;
  border: none;
}

.container {
  border: 2px solid hotpink;
  position: absolute;
  top: 0;
  left: 0;
  height: 200px;
  width: 100%;
  z-index: -1;
}

.reference {
  background: darkblue;
}

.standard {
  background: teal;
  vertical-align: middle;
}

.moz {
  background: antiquewhite;
  vertical-align: -moz-middle-with-baseline;
}

.webkit {
  background: darksalmon;
  vertical-align: -webkit-baseline-middle
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <hr />
  <div class="reference"></div>
  <div class="standard"></div>
  <div class="moz"></div>
  <div class="webkit"></div>
</div></code>```

References :

Safari and WebKit implement a large subset of the CSS 2.1 Specification defined by the World Wide Web Consortium (W3C), along with portions of the CSS 3 Specification. This reference describes the supported properties and provides Safari availability information. If a property is not listed here, it is not implemented by Safari and WebKit.

Safari CSS Reference

Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification

Hope I helped a bit :)

Body:
@VSG24:

Are they part of any standards?

Both properties are not part of any standards, according to W3C CSS reference. They only seem to be used by Webkit and Gecko to behave correctly, as expected in CSS 2.1 specification:

Align the vertical midpoint of the box with the baseline of the parent box plus half the x-height of the parent.

CSS 2.1 specs, p170

@VSG24:

What is the expected behavior when using them?

After some search on the web, here's what I've found about -webkit-baseline-middle on the Safari CSS Reference:

vertical-align: -webkit-baseline-middle:

The center of the element is aligned with the baseline of the text.

I was unable to get any info about -moz-middle-with-baseline other than this one :

Q: Webkit-baseline-middle - are there alternatives?

A: the same, only for Mozilla
 >vertical-align: -moz-middle-with-baseline;

https://toster.ru/q/255210

Below is a test, you may try it using Webkit based browsers (such as Chrome) and Gecko (Firefox):

div {
  width: 15%;
  height: 100px;
  display: inline-block;
  box-sizing: border-box;
}

hr {
  width: 100%;
  position: absolute;
  top: 90px;
  height: 1px;
  background: hotpink;
  border: none;
}

.container {
  border: 2px solid hotpink;
  position: absolute;
  top: 0;
  left: 0;
  height: 200px;
  width: 100%;
  z-index: -1;
}

.reference {
  background: darkblue;
}

.standard {
  background: teal;
  vertical-align: middle;
}

.moz {
  background: antiquewhite;
  vertical-align: -moz-middle-with-baseline;
}

.webkit {
  background: darksalmon;
  vertical-align: -webkit-baseline-middle
}

<div class="container">
  <hr />
  <div class="reference"></div>
  <div class="standard"></div>
  <div class="moz"></div>
  <div class="webkit"></div>
</div>

References :

Safari and WebKit implement a large subset of the CSS 2.1 Specification defined by the World Wide Web Consortium (W3C), along with portions of the CSS 3 Specification. This reference describes the supported properties and provides Safari availability information. If a property is not listed here, it is not implemented by Safari and WebKit.

Safari CSS Reference

Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification

Hope I helped a bit :)

ContentLicense: CC BY-SA 4.0


问:
Web Api 2 : How to make ModelState recognize optional parameters?
I currently have this controller

```<code>[RoutePrefix("api/Home")]
public class HomeController : ApiController
{

    [HttpGet]
    [Route("")]
    public IHttpActionResult GetByIdAndAnotherID([FromUri]int? id, [FromUri]int? AnotherId ){

        if (!ModelState.IsValid) //From ApiController.ModelState
        {
            return BadRequest(ModelState);
        }
    }
}
</code>```

When I try to access /api/Home?id=&AnotherId=1 or /api/Home?id=1&AnotherId=, it returns the following error A value is required but was not present in the request. I have clearly indicated that id or AnotherId should be an optional value.

Why is the ModelState not valid? What am I doing wrong?

答:
The route that you have defined is:

[Route("{id?}/{AnotherId?}")]

which means you would call it as follows /api/Home/0/1 where 0 would resolve to the value of id and 1 would resolve to the value of AnotherId.

I believe if you remove that route attribute and just leave the [Route("")] route attribute you should be able to call the method as you are expecting(/api/Home?id=&AnotherId=1 or /api/Home?id=1&AnotherId=) and get the results you are expecting.

Body:
I currently have this controller

[RoutePrefix("api/Home")]
public class HomeController : ApiController
{

    [HttpGet]
    [Route("")]
    public IHttpActionResult GetByIdAndAnotherID([FromUri]int? id, [FromUri]int? AnotherId ){

        if (!ModelState.IsValid) //From ApiController.ModelState
        {
            return BadRequest(ModelState);
        }
    }
}

When I try to access /api/Home?id=&AnotherId=1 or /api/Home?id=1&AnotherId=, it returns the following error A value is required but was not present in the request. I have clearly indicated that id or AnotherId should be an optional value.

Why is the ModelState not valid? What am I doing wrong?


问:
c# mocking IFormFile CopyToAsync() method
I am working on a unit test for an async function that converts a list of IFormFile to a list of my own arbitrary database file classes.

The method that converts the file data to a byte array is:

```<code>internal async Task<List<File>> ConvertFormFilesToFiles(ICollection<IFormFile> formFiles)
{
    var file = new File
    {
        InsertDateTime = DateTime.Now,
        LastChangeDateTime = DateTime.Now
    };
    if (formFile.Length > 0)
    {
        using (var memoryStream = new MemoryStream())
        {
            await formFile.CopyToAsync(memoryStream, CancellationToken.None);
            file.FileData = memoryStream.ToArray();
        }
    }
    // ...
}
</code>```

The function receives an ICollection of IFormFiles so it is mockable.

For now I have test code like this:

```<code>//Arrange
var fileConverter = new FilesConverter();
using (var fileStream = new FileStream("Files/uploadme.txt", FileMode.Open, FileAccess.Read))
{
    using (var memoryStream = new MemoryStream())
    {
        var newMemoryStream = new MemoryStream();
        fileStream.CopyTo(memoryStream);
        FormFileMock.Setup(f => f.CopyToAsync(newMemoryStream, CancellationToken.None)).Returns(Task.CompletedTask);
        // some other setups

        //Act
        var result = await fileConverter.ConvertFormFilesToFiles(new List<IFormFile> { FormFileMock.Object });
        //Assert
        Assert.IsTrue(result.Any());
    }
}
</code>```

The newMemoryStream variable is created because the function calls the CopyToAsync method with a new and empty memorystream (I'm not sure if this is necessary).

The problem is that the await formFile.CopyToAsync(memoryStream, CancellationToken.None) doesn't copy any data to the memoryStream.

答:
The problem is that the await formFile.CopyToAsync(memoryStream, CancellationToken.None) doesn't copy any data to the memoryStream.

According to your setup. Nothing will actually be copied.

You just setup the call to return as completed. No actual functionality was implemented.

You'll need to add a Callback to perform some desired functionality before returning the task.

```<code>FormFileMock
    .Setup(_ => _.CopyToAsync(It.IsAny<Stream>(), CancellationToken.None))
    .Callback<Stream, CancellationToken>((stream, token) => {
        //memory stream in this scope is the one that was populated
        //when you called **fileStream.CopyTo(memoryStream);** in the test
        memoryStream.CopyTo(stream);
    })
    .Returns(Task.CompletedTask);
</code>```

Body:
I am working on a unit test for an async function that converts a list of IFormFile to a list of my own arbitrary database file classes.

The method that converts the file data to a byte array is:

internal async Task<List<File>> ConvertFormFilesToFiles(ICollection<IFormFile> formFiles)
{
    var file = new File
    {
        InsertDateTime = DateTime.Now,
        LastChangeDateTime = DateTime.Now
    };
    if (formFile.Length > 0)
    {
        using (var memoryStream = new MemoryStream())
        {
            await formFile.CopyToAsync(memoryStream, CancellationToken.None);
            file.FileData = memoryStream.ToArray();
        }
    }
    // ...
}

The function receives an ICollection of IFormFiles so it is mockable.

For now I have test code like this:

//Arrange
var fileConverter = new FilesConverter();
using (var fileStream = new FileStream("Files/uploadme.txt", FileMode.Open, FileAccess.Read))
{
    using (var memoryStream = new MemoryStream())
    {
        var newMemoryStream = new MemoryStream();
        fileStream.CopyTo(memoryStream);
        FormFileMock.Setup(f => f.CopyToAsync(newMemoryStream, CancellationToken.None)).Returns(Task.CompletedTask);
        // some other setups

        //Act
        var result = await fileConverter.ConvertFormFilesToFiles(new List<IFormFile> { FormFileMock.Object });
        //Assert
        Assert.IsTrue(result.Any());
    }
}

The newMemoryStream variable is created because the function calls the CopyToAsync method with a new and empty memorystream (I'm not sure if this is necessary).

The problem is that the await formFile.CopyToAsync(memoryStream, CancellationToken.None) doesn't copy any data to the memoryStream.

Body:
The problem is that the await formFile.CopyToAsync(memoryStream, CancellationToken.None) doesn't copy any data to the memoryStream.

According to your setup. Nothing will actually be copied.

You just setup the call to return as completed. No actual functionality was implemented.

You'll need to add a Callback to perform some desired functionality before returning the task.

FormFileMock
    .Setup(_ => _.CopyToAsync(It.IsAny<Stream>(), CancellationToken.None))
    .Callback<Stream, CancellationToken>((stream, token) => {
        //memory stream in this scope is the one that was populated
        //when you called **fileStream.CopyTo(memoryStream);** in the test
        memoryStream.CopyTo(stream);
    })
    .Returns(Task.CompletedTask);


问:
How to display both single quotes and double quotes in echo in unix
I need to display a string like Today's "program" as output in unix. But If i gave the below none of the options are working .

```<code>>echo "Today's "program""
Today's program

> echo "Today\'s "program""
Today\'s program

> echo 'Today's "program"'
>

echo 'Today\'s "program"'
>
</code>```

答:
If you want to display double quotes inside double quotes, you have to escape them:

```<code>$> echo "today's \"program\""
today's "program"
</code>```

You could also concatenate quoted strings:

```<code>$> echo 'today'"'"'s "program"'
today's "program"
</code>```

Or just escape them all:

```<code>$> echo today\'s \"program\"
today's "program"
</code>```

Body:
I need to display a string like Today's "program" as output in unix. But If i gave the below none of the options are working .

>echo "Today's "program""
Today's program

> echo "Today\'s "program""
Today\'s program

> echo 'Today's "program"'
>

echo 'Today\'s "program"'
>

Body:
If you want to display double quotes inside double quotes, you have to escape them:

$> echo "today's \"program\""
today's "program"

You could also concatenate quoted strings:

$> echo 'today'"'"'s "program"'
today's "program"

Or just escape them all:

$> echo today\'s \"program\"
today's "program"


问:
Get column value of repeating table?
I have this table:

var table = document.getElementById('tableID'),
    cells = table.getElementsByTagName('td');

for (var x = 0, len = cells.length; x < len; x++) {
    cells[x].onclick = function () {
        console.log(this.innerHTML);
    };
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="table table-striped" id="tableID">
    <tbody>
      <tr ng-repeat="cup in cups">
          <td>{{cup.cupnum}}</td>
          <td>{{::cup.contents.model}}</td>
          <td>{{::cup.contents.woa}}</td>
          <td>{{::cup.contents.perfBy}}</td>
          <td>{{::cup.contents.perfAt}}</td>
          <td>{{::cup.contents.loadEvent}}</td>
          <td>{{samples[cup.contents.sampleID-1].contents.name}}</td>
          <td>{{holders[cup.contents.holderID-1].contents.type}}</td>
      </tr>
    </tbody>
</table></code>```

How can I make it so that i'm just getting the value of the last column for each row without having to click? The: {{holders[cup.contents.holderID-1].contents.type}}
column

答:
To access the last columns, query all td:last-child

var cells = document.querySelectorAll('#tableID td:last-child');
var result = document.getElementById("result");
result.innerHTML="";
for (var x = 0, len = cells.length; x < len; x++) {
        result.innerHTML+=cells[x].innerHTML+"
";
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="table table-striped" id="tableID" border="1">
    <tbody>
      <tr ng-repeat="cup in cups">
          <td>{{cup.cupnum}}</td>
          <td>{{::cup.contents.model}}</td>
          <td>{{::cup.contents.woa}}</td>
          <td>{{::cup.contents.perfBy}}</td>
          <td>{{::cup.contents.perfAt}}</td>
          <td>{{::cup.contents.loadEvent}}</td>
          <td>{{samples[cup.contents.sampleID-1].contents.name}}</td>
          <td>{{holders[cup.contents.holderID-1].contents.type}}</td>
      </tr>
       <tr ng-repeat="cup in cups">
          <td>{{cup.cupnum}}</td>
          <td>{{::cup.contents.model}}</td>
          <td>{{::cup.contents.woa}}</td>
          <td>{{::cup.contents.perfBy}}</td>
          <td>{{::cup.contents.perfAt}}</td>
          <td>{{::cup.contents.loadEvent}}</td>
          <td>{{samples[cup.contents.sampleID-1].contents.name}}</td>
          <td>{{holders[cup.contents.holderID-1].contents.type}}</td>
      </tr>
    </tbody>
</table>
<hr>
<h2>Result</h2>
<div id="result"></div></code>```

Title: Get column value of repeating table?

Body:
I have this table:

var table = document.getElementById('tableID'),
    cells = table.getElementsByTagName('td');

for (var x = 0, len = cells.length; x < len; x++) {
    cells[x].onclick = function () {
        console.log(this.innerHTML);
    };
}

          {{cup.cupnum}}
          {{::cup.contents.model}}
          {{::cup.contents.woa}}
          {{::cup.contents.perfBy}}
          {{::cup.contents.perfAt}}
          {{::cup.contents.loadEvent}}
          {{samples[cup.contents.sampleID-1].contents.name}}
          {{holders[cup.contents.holderID-1].contents.type}}

How can I make it so that i'm just getting the value of the last column for each row without having to click? The: {{holders[cup.contents.holderID-1].contents.type}}
column

Body:
To access the last columns, query all td:last-child

var cells = document.querySelectorAll('#tableID td:last-child');
var result = document.getElementById("result");
result.innerHTML="";
for (var x = 0, len = cells.length; x < len; x++) {
        result.innerHTML+=cells[x].innerHTML+"<br>";
};

<table class="table table-striped" id="tableID" border="1">
    <tbody>
      <tr ng-repeat="cup in cups">
          <td>{{cup.cupnum}}</td>
          <td>{{::cup.contents.model}}</td>
          <td>{{::cup.contents.woa}}</td>
          <td>{{::cup.contents.perfBy}}</td>
          <td>{{::cup.contents.perfAt}}</td>
          <td>{{::cup.contents.loadEvent}}</td>
          <td>{{samples[cup.contents.sampleID-1].contents.name}}</td>
          <td>{{holders[cup.contents.holderID-1].contents.type}}</td>
      </tr>
       <tr ng-repeat="cup in cups">
          <td>{{cup.cupnum}}</td>
          <td>{{::cup.contents.model}}</td>
          <td>{{::cup.contents.woa}}</td>
          <td>{{::cup.contents.perfBy}}</td>
          <td>{{::cup.contents.perfAt}}</td>
          <td>{{::cup.contents.loadEvent}}</td>
          <td>{{samples[cup.contents.sampleID-1].contents.name}}</td>
          <td>{{holders[cup.contents.holderID-1].contents.type}}</td>
      </tr>
    </tbody>
</table>
<hr>
<h2>Result</h2>
<div id="result"></div>


问:
Importing top level file from lower level file
I’m unclear on this: __init__.py describes the current folder as a module, no?

So if my top level project folder, my_project, contains file config.py (my_project/config.py), then the file in my_project/drivers/sales/customer.py should be able to import the config.py module simply by:

import my_project.config (Errors to: ModuleNotFoundError: No module named 'my_project')

Or, from .. import config (Errors to: ValueError: attempted relative import beyond top-level package) - Btw, tried with three dots (...) with same error.

Or, simply import config (Errors to: ModuleNotFoundError: No module named 'config')

with the following terminal command:

```<code>(env) localhost:/Users/myname/Sites/my_project
$ python drivers/sales/customer.py
</code>```

How can I accomplish this import?

Versions:

```<code>$ python
Python 3.6.2 (default, Jul 17 2017, 16:44:45)
</code>```

答:
One way is to expose the path of your project as below:

```<code>import sys
sys.path.append('path/to/your/project') # /Users/nabin/Desktop in my case
</code>```

#I have "my_project" in Desktop i.e /Users/nabin/Desktop/my_project

Then you can do the following

```<code>from my_project import config
</code>```

So when combined, what you need is following:

```<code>import sys
sys.path.append('path/to/your/project')

from my_project import config
</code>```

Body:
I’m unclear on this: __init__.py describes the current folder as a module, no?

So if my top level project folder, my_project, contains file config.py (my_project/config.py), then the file in my_project/drivers/sales/customer.py should be able to import the config.py module simply by:

import my_project.config (Errors to: ModuleNotFoundError: No module named 'my_project')

Or, from .. import config (Errors to: ValueError: attempted relative import beyond top-level package) - Btw, tried with three dots (...) with same error.

Or, simply import config (Errors to: ModuleNotFoundError: No module named 'config')

with the following terminal command:

(env) localhost:/Users/myname/Sites/my_project
$ python drivers/sales/customer.py

How can I accomplish this import?

Versions:

$ python
Python 3.6.2 (default, Jul 17 2017, 16:44:45)

Body:
One way is to expose the path of your project as below:

import sys
sys.path.append('path/to/your/project') # /Users/nabin/Desktop in my case

#I have "my_project" in Desktop i.e /Users/nabin/Desktop/my_project

Then you can do the following

from my_project import config

So when combined, what you need is following:

import sys
sys.path.append('path/to/your/project')

from my_project import config


问:
Save byte array to binary file
I have class representing car with two attributes. I want to convert it to byte[] and save it to binary file.

```<code>class Car
    {
        private string type;
        private int id;

        public Car(string paType, int paId)
        {
            type = paType;
            id = paId;
        }

        public byte[] ByteConverter()
        {
            byte[] bArr = new byte[14];

            byte[] hlpType = Encoding.UTF8.GetBytes(this.type);

            byte[] hlpId = BitConverter.GetBytes(this.id);

            hlpType.CopyTo(bArr, 0);
            hlpId.CopyTo(bArr, hlpType.Length);

            return bArr;
        }
    }
</code>```

Save method body:

```<code>Car c = new Car("abcd", 12);
FileStream fsStream = new FileStream("cardata.bin", FileMode.Create);
fsStream.Write(c.ByteConverter(), 0, 14);
fsStream.Close();
</code>```

If I open file cardata.dat, there is string.

abcd

How to solve this? Thanks.

答:
If you want save to / load from file explicitly (type then id format preserved) you can put it as

```<code>private void SaveToFile(string fileName) {
  File.WriteAllBytes(fileName, Encoding.UTF8
    .GetBytes(type)
    .Concat(BitConverter.GetBytes(id))
    .ToArray());
}

private void LoadFromFile(string fileName) {
   byte[] data = File.ReadAllBytes(fileName);

   type = Encoding.UTF8.GetString(data
     .Take(data.Length - sizeof(int))
     .ToArray());

   id = BitConverter.ToInt32(data, data.Length - sizeof(int))
}
</code>```

Title: Save byte array to binary file

Body:
I have class representing car with two attributes. I want to convert it to byte[] and save it to binary file.

class Car
    {
        private string type;
        private int id;

        public Car(string paType, int paId)
        {
            type = paType;
            id = paId;
        }

        public byte[] ByteConverter()
        {
            byte[] bArr = new byte[14];

            byte[] hlpType = Encoding.UTF8.GetBytes(this.type);

            byte[] hlpId = BitConverter.GetBytes(this.id);

            hlpType.CopyTo(bArr, 0);
            hlpId.CopyTo(bArr, hlpType.Length);

            return bArr;
        }
    }

Save method body:

Car c = new Car("abcd", 12);
FileStream fsStream = new FileStream("cardata.bin", FileMode.Create);
fsStream.Write(c.ByteConverter(), 0, 14);
fsStream.Close();

If I open file cardata.dat, there is string.

abcd

How to solve this? Thanks.

Body:
If you want save to / load from file explicitly (type then id format preserved) you can put it as

private void SaveToFile(string fileName) {
  File.WriteAllBytes(fileName, Encoding.UTF8
    .GetBytes(type)
    .Concat(BitConverter.GetBytes(id))
    .ToArray());
}

private void LoadFromFile(string fileName) {
   byte[] data = File.ReadAllBytes(fileName);

   type = Encoding.UTF8.GetString(data
     .Take(data.Length - sizeof(int))
     .ToArray());

   id = BitConverter.ToInt32(data, data.Length - sizeof(int))
}


问:
Cannot read configuration file ' trying to read configuration data from file '\\?\<EMPTY>', line number '0'
An app pool kept stopping every time it was started and gave this error in the application logs:

The worker process for application pool 'APP_POOL_NAME' encountered an
  error 'Cannot read configuration file ' trying to read configuration
  data from file '\\?\<EMPTY>', line number '0'. The data field contains
  the error code.

Several users have noted this occurs after the Windows 10 Fall Update.

答:
If you recently installed the Windows 10 Fall Creators Update, this problem and a solution for it may be covered in this Microsoft knowledge base article. The solution:

Open an Administrator Command Prompt (not a Powershell prompt)

Run: net stop WAS /y

Run: rmdir /s /q C:\inetpub\temp\appPools

Run: net start W3SVC

Thanks to @weir for reporting this issue.

This wasn't a permission error in this instance, but it's would be well worth ensuring IIS_IUSRS has access to your site config just in case. See here
for steps on how to do this.

This issue appeared to be a virtual directory appeared in the IIS temp files, which was pointing to the wrong place. To fix:

Go to the drive your IIS is installed on, eg. C:\inetpub\temp\appPools\

Delete the directory (or virtual directory) with the same name as your app pool.

Recycle/Start your app pool again.


答:
Multiple possibilities:

```<code>> echo 'Today'"'"'s "program"'
Today's "program"
> echo Today"'"s '"program"'
Today's "program"
> echo Today\'s '"program"'
Today's "program"
> echo Today\'s \"program\"
Today's "program"
</code>```

For the difference between these 3 kinds of escaping see for example this article.

Title: How to display both single quotes and double quotes in echo in unix

Body:
Multiple possibilities:

> echo 'Today'"'"'s "program"'
Today's "program"
> echo Today"'"s '"program"'
Today's "program"
> echo Today\'s '"program"'
Today's "program"
> echo Today\'s \"program\"
Today's "program"

For the difference between these 3 kinds of escaping see for example this article.


问:
Font sizes on different pages
Ok so I'm not sure if questions like this are allowed on here so if not please tell me and I will remove it. My question is about whether font sizes should be the same on all pages.

Here's my situation. I have several headings spread across multiple pages on a website which I am creating. They all use the same styles but as they all have different character lengths when the screen gets smaller some of the headings start breaking at points which just make the website look rubbish. To make a couple of these heading look good I have had to use a font size of 16px, which isn't ideal as the the body text is 16px but still it looks better than what it did look like.

So what would you usually do in this situation? Would you keep all the headings the same size to keep in theme with the other pages? or is it ok to have some smaller than others? will the user even notice?

答: You should totally keep the headlines in the same size. There is no reason to scale it down. Sometimes there are longer headlines that's a genuine use case there is no reason to scale down the font-size.</p>

Title: Font sizes on different pages


问:
How to import and read a shelve or Numpy file in Google Colaboratory?
I have file.npy and I want to load it in Google Colaboratory Notebook. I already know that I must load the file from Google Drive, however I have no idea how to do so.

Any help is welcome

答:
Upload your file into Colaboratory Notebook with the following:

```<code>from google.colab import files
uploaded = files.upload()
</code>```

Then you can reach the contents of your file from uploaded object and then write it into a file:

```<code>with open("my_data.h5", 'w') as f:
    f.write(uploaded[uploaded.keys()[0]])
</code>```

If you run:

```<code>!ls
</code>```

you will see my_data.h5 file in the current directory.

This is the method that worked for me. Hope it helps.

Body:
Upload your file into Colaboratory Notebook with the following:

from google.colab import files
uploaded = files.upload()

Then you can reach the contents of your file from uploaded object and then write it into a file:

with open("my_data.h5", 'w') as f:
    f.write(uploaded[uploaded.keys()[0]])

If you run:

!ls

you will see my_data.h5 file in the current directory.

This is the method that worked for me. Hope it helps.


问:
VBA: How to click a drop down in a web page with the help of HREF and CLASS HTML tag avilable
I am trying to automate one of my website working on a secured server, the code which help me to log into the web page but after that I have to click a dropdown from a menu bar where the HTML tag available is CLASS and HREF only.

HTML

```<code><li>
<a Class = "childmenu" href="./1713363899/ViewLogsPage">
<span>Logs</Span>
</a>
</li>
</code>```

A part of my VBA code is

```<code>Dim MyHTML_Element as IHTMLElement
Set HTMLDoc = MyBrowser.document

For Each MyHTML_Element In HTMLDoc.getElementsByClassName ("childmenu")
If MyHTML_Element.href = "./1713363899/ViewLogsPage" Then MyHTML_Element.Click:
Exit For
Next
</code>```

but this code not working and Skip after executing this line ".....ClassName ("childmenu")" and jump to END sub, when i run my code in Debug mode.

答:
Try </p>

```<code>If Instr(MyHTML_Element.href, "1713363899/ViewLogsPage") Then MyHTML_Element.Click
</code>```

<p>If not works, add debug.print MyHTML_Element.href before line with If. It is possible that link is generated while page is being download. </p>

Body:
I am trying to automate one of my website working on a secured server, the code which help me to log into the web page but after that I have to click a dropdown from a menu bar where the HTML tag available is CLASS and HREF only.

HTML

Logs

A part of my VBA code is

Dim MyHTML_Element as IHTMLElement
Set HTMLDoc = MyBrowser.document

For Each MyHTML_Element In HTMLDoc.getElementsByClassName ("childmenu")
If MyHTML_Element.href = "./1713363899/ViewLogsPage" Then MyHTML_Element.Click:
Exit For
Next

but this code not working and Skip after executing this line ".....ClassName ("childmenu")" and jump to END sub, when i run my code in Debug mode.

Body:
Try

If Instr(MyHTML_Element.href, "1713363899/ViewLogsPage") Then MyHTML_Element.Click

If not works, add debug.print MyHTML_Element.href before line with If. It is possible that link is generated while page is being download.


问:
How to install dependency scripts while installing an npm module
I have published an angular 2 library to npm recently.I have listed all the dependency scripts in the libraries package.json file. when I run npm install my-library all the dependency scripts are not installed.So, my question is how to install the dependency scripts while installing the library.

答:
(This answer is valid for npm5+) In package.json you can specify 3 types of dependencies:

peerDependencies - they are not automatically downloaded in any case ("good to have")

devDependencies - which are downloaded when running npm install in the project itself, packages listed here are needed for development purposes only

dependencies - which are downloaded on every npm install (also when adding your package to someone's project, "must-to-have")

Example:

```<code>{
  "peerDependencies": {
    "@angular/core": ">=2.3.0",
  },
  "devDependencies": {
    "@angular/compiler": "~4.0.0",
    "@angular/compiler-cli": "~4.0.0",
    "@angular/core": "~4.0.0",
    "@angular/platform-server": "~4.0.0",
    "@types/node": "^7.0.39",
    "core-js": "^2.4.1",
    "es6-shim": "^0.35.3",
    "rimraf": "^2.5.4",
    "rxjs": "^5.4.2",
    "tslint": "^4.5.0",
    "typescript": "^2.6.1",
    "zone.js": "^0.8.16"
  },
  "dependencies": {
    "ngx-store": "^1.2.2"
  }
}
</code>```

Body:
(This answer is valid for npm5+) In package.json you can specify 3 types of dependencies:

peerDependencies - they are not automatically downloaded in any case ("good to have")

devDependencies - which are downloaded when running npm install in the project itself, packages listed here are needed for development purposes only

dependencies - which are downloaded on every npm install (also when adding your package to someone's project, "must-to-have")

Example:

{
  "peerDependencies": {
    "@angular/core": ">=2.3.0",
  },
  "devDependencies": {
    "@angular/compiler": "~4.0.0",
    "@angular/compiler-cli": "~4.0.0",
    "@angular/core": "~4.0.0",
    "@angular/platform-server": "~4.0.0",
    "@types/node": "^7.0.39",
    "core-js": "^2.4.1",
    "es6-shim": "^0.35.3",
    "rimraf": "^2.5.4",
    "rxjs": "^5.4.2",
    "tslint": "^4.5.0",
    "typescript": "^2.6.1",
    "zone.js": "^0.8.16"
  },
  "dependencies": {
    "ngx-store": "^1.2.2"
  }
}


问:
Unknown setting ‘host’ for elasticsearch in logstash conf
My logstash.conf file and mysql-connector-java-5.1.38.jar both are in F:\Software\logstash-5.5.1\logstash-5.5.1\bin location
Getting below error while running conf file in cmd :

F:\Software\logstash-5.5.1\logstash-5.5.1\bin>logstash -f logstash.conf
  ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
  Sending Logstash’s logs to F:/Software/logstash-5.5.1/logstash-5.5.1/logs which is now configured via log4j2.properties
  [2017-08-03T16:01:17,142][ERROR][logstash.outputs.elasticsearch] Unknown setting ‘host’ for elasticsearch
  [2017-08-03T16:01:17,149][ERROR][logstash.agent ] Cannot create pipeline {:reason=>“Something is wrong with your configuration.”}

Below is my conf file:

```<code>input {
jdbc {
    # MySql jdbc connection string to our database, testdb
    jdbc_connection_string => "jdbc:mysql://localhost:3306/testdb"
    # The user we wish to execute our statement as
    jdbc_user => "root"
    jdbc_password => "root"
    # The path to our downloaded jdbc driver
    jdbc_driver_library => "F:/Software/logstash-5.5.1/logstash-5.5.1/bin/mysql-connector-java-5.1.38/mysql-connector-java-5.1.38.jar"
    # The name of the driver class for Postgresql
    jdbc_driver_class => "com.mysql.jdbc.Driver"
    # our query
    statement => "SELECT * from testtable"
}
</code>```

}

```<code>output {
stdout { codec => json_lines }
elasticsearch{
 hosts => ["localhost:9200"]
 protocol => "http"
 index => "test-migrate"
 document_type => "data"
}
</code>```

}

答:
This is standard and basic conf file

Good luck !!!!

```<code>input {
    jdbc {
        jdbc_driver_library => "/mysql-connector-java-5.1.44-bin.jar"
        jdbc_driver_class => "com.mysql.jdbc.Driver"
        jdbc_connection_string => "jdbc:mysql://localhost:3306/yourdatabase"
        jdbc_user => "root"
        jdbc_password => ""
        statement => "SELECT * from yourtable"
    }
}
output {
    #stdout {codec => rubydebug}
    elasticsearch {
        hosts => "localhost:9200"
        index => "inandi"
        document_type => "name"
        document_id => "%{name}"
    }
}
</code>```

Body:
My logstash.conf file and mysql-connector-java-5.1.38.jar both are in F:\Software\logstash-5.5.1\logstash-5.5.1\bin location
Getting below error while running conf file in cmd :

F:\Software\logstash-5.5.1\logstash-5.5.1\bin>logstash -f logstash.conf
  ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
  Sending Logstash’s logs to F:/Software/logstash-5.5.1/logstash-5.5.1/logs which is now configured via log4j2.properties
  [2017-08-03T16:01:17,142][ERROR][logstash.outputs.elasticsearch] Unknown setting ‘host’ for elasticsearch
  [2017-08-03T16:01:17,149][ERROR][logstash.agent ] Cannot create pipeline {:reason=>“Something is wrong with your configuration.”}

Below is my conf file:

input {
jdbc {
    # MySql jdbc connection string to our database, testdb
    jdbc_connection_string => "jdbc:mysql://localhost:3306/testdb"
    # The user we wish to execute our statement as
    jdbc_user => "root"
    jdbc_password => "root"
    # The path to our downloaded jdbc driver
    jdbc_driver_library => "F:/Software/logstash-5.5.1/logstash-5.5.1/bin/mysql-connector-java-5.1.38/mysql-connector-java-5.1.38.jar"
    # The name of the driver class for Postgresql
    jdbc_driver_class => "com.mysql.jdbc.Driver"
    # our query
    statement => "SELECT * from testtable"
}

}

output {
stdout { codec => json_lines }
elasticsearch{
 hosts => ["localhost:9200"]
 protocol => "http"
 index => "test-migrate"
 document_type => "data"
}

}

Body:
This is standard and basic conf file

Good luck !!!!

input {
    jdbc {
        jdbc_driver_library => "/mysql-connector-java-5.1.44-bin.jar"
        jdbc_driver_class => "com.mysql.jdbc.Driver"
        jdbc_connection_string => "jdbc:mysql://localhost:3306/yourdatabase"
        jdbc_user => "root"
        jdbc_password => ""
        statement => "SELECT * from yourtable"
    }
}
output {
    #stdout {codec => rubydebug}
    elasticsearch {
        hosts => "localhost:9200"
        index => "inandi"
        document_type => "name"
        document_id => "%{name}"
    }
}


问:
Second Run of a Function
I got a script which declares a variable and sets it to a pandas Series object.

```<code>Pi = pd.Series(0, index=[some_index])
</code>```

then a for loop adds more values to that pandas Series object:

```<code>for i in range(0, 10):
        Pi = Pi.add(some_value[i], fill_value=0)
</code>```

the thing I want to code is a function which I can put inside this for loop, like:

```<code>for i in range(0, 10):
        Pi = my_function()
</code>```

but the problem is my_function() should declare a pandas series object at first run (return pd.Series(0)) and after the first run, it should somehow change and add new values (return pd.add(some_value)) instead of defining pd.Series(0) again.

Ty

答:
You shouldn't do this as it has no benefits and is confusing.

```<code>def my_function(Pi, i):
    if i == 0: # First iteration, Create the Series
        Pi = pd.Series(0, index=[some_index])

    Pi = Pi.add(some_value[i], fill_value=0)
    return Pi

Pi=None
for i in range(0, 10):
    Pi = my_function(Pi, i)
</code>```

Perhaps a class is what you want:

```<code>class PiSeries:

    def __init__(self, some_index):
        self.Pi = pd.Series(0, index=[some_index])

    def my_function(self, i):
        self.Pi = self.Pi.add(some_value[i], fill_value=0)

    def create_series(self, start, end):
        for i in range(start, end):
            self.my_function(i)

        return self.Pi

PiSeries(index=some_index).create_series(start=0, end=10)
</code>```

Title: Second Run of a Function

Body:
I got a script which declares a variable and sets it to a pandas Series object.

Pi = pd.Series(0, index=[some_index])

then a for loop adds more values to that pandas Series object:

for i in range(0, 10):
        Pi = Pi.add(some_value[i], fill_value=0)

the thing I want to code is a function which I can put inside this for loop, like:

for i in range(0, 10):
        Pi = my_function()

but the problem is my_function() should declare a pandas series object at first run (return pd.Series(0)) and after the first run, it should somehow change and add new values (return pd.add(some_value)) instead of defining pd.Series(0) again.

Ty

Body:
You shouldn't do this as it has no benefits and is confusing.

def my_function(Pi, i):
    if i == 0: # First iteration, Create the Series
        Pi = pd.Series(0, index=[some_index])

    Pi = Pi.add(some_value[i], fill_value=0)
    return Pi

Pi=None
for i in range(0, 10):
    Pi = my_function(Pi, i)

Perhaps a class is what you want:

class PiSeries:

    def __init__(self, some_index):
        self.Pi = pd.Series(0, index=[some_index])

    def my_function(self, i):
        self.Pi = self.Pi.add(some_value[i], fill_value=0)

    def create_series(self, start, end):
        for i in range(start, end):
            self.my_function(i)

        return self.Pi

PiSeries(index=some_index).create_series(start=0, end=10)


问:
Getting the source code of an iframe
Is there anyway to get the source code of the page that an iframe loaded? I do not wish to CHANGE any of the code, I just want to READ it. I also need to be able to get this using javascript/html.</p>

答:
```<code>document.getElementById('iframeID').contentWindow.document.body.innerHTML
</code>```

Works in Firefox, Chrome, Opera, IE9 beta

Title: Getting the source code of an iframe

Body:
document.getElementById('iframeID').contentWindow.document.body.innerHTML

Works in Firefox, Chrome, Opera, IE9 beta


问:
TFS build error path incorrect
I have the following TFS structure:

FolderA --> FolderB --> FolderC

In the build definition the Solution is set to FolderB/FolderC/MySolution.sln
Under get sources the Workspace is mapped to $/FolderA

When I build I get an error because the path is missing FolderA.

C:\agent_work\2\s\FolderB\FolderC\MySolution.sln

答:
..\s is the root -level of your mapping (in this case $/FolderA = ..\s).
If you need the path to be ..\s\FolderA (why ?) go to your build -> "Get sources" -> "workspace mappings" and configure the field "Local path under $(build.sourcesdirectory)" with "FolderA"</p>

Title: TFS build error path incorrect


问:
MySQL - Select row if appear more than x times in other table
Lets say I have two tables, Members and Orders with a 1:N relation:

```<code>Members         | Orders
UserID  Name    | OrderID   UserID  Name
111     Peter   | 777       111     Peter
222     Bart    | 888       333     Joe
333     Joe     | 999       111     Peter
444     Andrew  | 101       444     Andrew
                | 102       111     Peter
                | 103       333     Joe
</code>```

I am trying to get the Members ID from the Members table, in case that Member has more than 1 order in the Orders table.

So the result should be...

```<code>Members
UserID  Name
111     Peter
333     Joe
</code>```

...because Peter and Joe both have at least 2 orders in the Orders table.

I have tried to get a result with:

```<code>SELECT
    s.UserID,
FROM Members s
    INNER JOIN Orders o
        ON s.UserID = o.UserID
WHERE
    s.UserID IN
    (
        SELECT UserID
        FROM Orders
        GROUP BY UserID
        HAVING COUNT(*) > 5
    )
</code>```

But that gives me Peter back 3 times, and Joe 2 times; so I get duplicates instead of each UserID once. How can I get the result without duplicates?

答:
You just need a subquery having count(OrderID) > 1 as below.

```<code>SELECT *
FROM members
WHERE UserID IN (
        SELECT UserId
        FROM orders
        GROUP BY userid
        HAVING count(OrderID) > 1
        );
</code>```

Result:

```<code>UserID  Name
--------------
111     Peter
333     Joe
</code>```

DEMO

Body:
Lets say I have two tables, Members and Orders with a 1:N relation:

Members         | Orders
UserID  Name    | OrderID   UserID  Name
111     Peter   | 777       111     Peter
222     Bart    | 888       333     Joe
333     Joe     | 999       111     Peter
444     Andrew  | 101       444     Andrew
                | 102       111     Peter
                | 103       333     Joe

I am trying to get the Members ID from the Members table, in case that Member has more than 1 order in the Orders table.

So the result should be...

Members
UserID  Name
111     Peter
333     Joe

...because Peter and Joe both have at least 2 orders in the Orders table.

I have tried to get a result with:

SELECT
    s.UserID,
FROM Members s
    INNER JOIN Orders o
        ON s.UserID = o.UserID
WHERE
    s.UserID IN
    (
        SELECT UserID
        FROM Orders
        GROUP BY UserID
        HAVING COUNT(*) > 5
    )

But that gives me Peter back 3 times, and Joe 2 times; so I get duplicates instead of each UserID once. How can I get the result without duplicates?

Body:
You just need a subquery having count(OrderID) > 1 as below.

SELECT *
FROM members
WHERE UserID IN (
        SELECT UserId
        FROM orders
        GROUP BY userid
        HAVING count(OrderID) > 1
        );

Result:

UserID  Name
--------------
111     Peter
333     Joe

DEMO


问:
Biztalk 2016 Fail to configuration Group
I am facing to a problem during configuration Biztalk 2016 Group

[2017-01-06 16:25:27:0170  Error BtsCfg] The server has not been configured.
To configure the server, run the BizTalk Server Configuration wizard and configure the Group feature.
[2017-01-06 16:25:27:0186  Info BtsCfg] Instantiating IBTSMsgBoxPerformance object
[2017-01-06 16:25:27:0186  Info BtsCfg] Calling IBTSMsgBoxPerformance::UninstallArtifacts
Exception in CounterManager.UninstallArtifacts when uninstalling the perf counter instances. The exception details are:
Source of exception: System
Message: Cannot delete Performance Category because this category is not registered or is a system category.
Stack trace:    at System.Diagnostics.PerformanceCounterCategory.Delete(String categoryName)
   at Microsoft.BizTalk.MsgBoxPerfCounters.MgmtDbAccessEntity.UninstallInstances(Boolean regularUninstall)
   at Microsoft.BizTalk.MsgBoxPerfCounters.CounterManager.UninstallArtifacts(Boolean regularUninstall, String logFileName)

I checked these things:

SQL Server machine is accessable, SQL Server is running, TCP/IP is
enabled.

The installing user have Administrators right.

MSDTC is configured on the Biztalk server machine and SQL Server machine,
using DTCPing to test the connection from server to sql server
machine is success.

SSO had been successfully configured.

Edit:
First error line in log:

[2017-01-09 14:40:21:0833  Error BAMConfigWizExt] d:\bt\52584\private\source\monitoring\configuration\extention\helpers.h(2068): FAILED hr = 80004005
Then

[2017-01-09 14:42:34:0913  Error BtsCfg] d:\bt\52584\private\source\setup\btscfg\btswmi.cpp(436): FAILED hr = c0c025b3

[2017-01-09 14:42:34:0913  Error BtsCfg] Exception of type 'System.EnterpriseServices.TransactionProxyException' was thrown.

[2017-01-09 14:42:34:0913  Error BtsCfg] d:\bt\52584\private\source\setup\btscfg\btscfg.cpp(1820): FAILED hr = c0c025b3

[2017-01-09 14:42:34:0913  Info BtsCfg] Entering function: CBtsCfg::UnConfigureFeature

[2017-01-09 14:42:34:0913  Info BtsCfg]     Unconfiguring feature: WMI

[2017-01-09 14:42:34:0913  Warning BtsCfg] BTS management server or DB names are not found in the registry.

[2017-01-09 14:42:34:0913  Info BtsCfg] Entering function: CWMI::StopHostInstance

[2017-01-09 14:42:34:0913  Error BtsCfg] d:\bt\52584\private\source\setup\btscfg\btswmi.cpp(1551): FAILED hr = c0c024bf

[2017-01-09 14:42:34:0913  Error BtsCfg] The server has not been configured.
To configure the server, run the BizTalk Server Configuration wizard and configure the Group feature.

[2017-01-09 14:42:34:0913  Info BtsCfg] Entering function: CWMI::UnMapHost

[2017-01-09 14:42:34:0913  Error BtsCfg] d:\bt\52584\private\source\setup\btscfg\btswmi.cpp(1696): FAILED hr = c0c024bf

[2017-01-09 14:42:34:0913  Error BtsCfg] The server has not been configured.
To configure the server, run the BizTalk Server Configuration wizard and configure the Group feature.

[2017-01-09 14:42:34:0913  Info BtsCfg] Instantiating IBTSMsgBoxPerformance object

[2017-01-09 14:42:34:0929  Info BtsCfg] Calling IBTSMsgBoxPerformance::UninstallArtifacts
Exception in CounterManager.UninstallArtifacts when uninstalling the perf counter instances. The exception details are:
Source of exception: System
Message: Cannot delete Performance Category because this category is not registered or is a system category.
Stack trace:    at System.Diagnostics.PerformanceCounterCategory.Delete(String categoryName)
   at Microsoft.BizTalk.MsgBoxPerfCounters.MgmtDbAccessEntity.UninstallInstances(Boolean regularUninstall)
   at Microsoft.BizTalk.MsgBoxPerfCounters.CounterManager.UninstallArtifacts(Boolean regularUninstall, String logFileName)

[2017-01-09 14:42:34:0929  Info BtsCfg] Stopping Tracing

[2017-01-09 14:42:34:0929  Info BtsCfg] Entering function: CWMI::DeleteServer

[2017-01-09 14:42:34:0929  Error BtsCfg] d:\bt\52584\private\source\setup\btscfg\btswmi.cpp(1351): FAILED hr = c0c024bf

[2017-01-09 14:42:34:0929  Error BtsCfg] The server has not been configured.
To configure the server, run the BizTalk Server Configuration wizard and configure the Group feature.

[2017-01-09 14:42:34:0929  Info BtsCfg] Entering function: CWMI::UnConfigureGroup
[2017-01-09 14:42:34:0929  Error BtsCfg] d:\bt\52584\private\source\setup\btscfg\btswmi.cpp(1074): FAILED hr = c0c024bf

[2017-01-09 14:42:34:0929  Error BtsCfg] The server has not been configured.
To configure the server, run the BizTalk Server Configuration wizard and configure the Group feature.

[2017-01-09 14:42:34:0929  Info BtsCfg] Leaving function: CBtsCfg::UnConfigureFeature

[2017-01-09 14:42:34:0929  Info BtsCfg] Leaving function: CBtsCfg::ConfigureFeature

[2017-01-09 14:42:34:0929 Warning Configuration Framework]Feature failed to configure: WMI.

[2017-01-09 14:42:37:0058 Info Configuration Framework]Configuration Summaries:

[2017-01-09 14:42:37:0058 Error Configuration Framework]Feature: [Group] Failed to configure with error message [Exception of type 'System.EnterpriseServices.TransactionProxyException' was thrown.]

[2017-01-09 14:42:37:0058 Error Configuration Framework]Feature: [BizTalk Runtime] Failed to configure with error message [Feature is skipped due to dependent feature (Group) failed to configure correctly.]

[2017-01-09 14:42:37:0058 Error Configuration Framework]Feature: [BAM Tools] Failed to configure with error message [Feature is skipped due to dependent feature (Group) failed to configure correctly.]

[2017-01-09 14:42:37:0058 Error Configuration Framework]Feature: [BAM Portal] Failed to configure with error message [Feature is skipped due to dependent feature (Group) failed to configure correctly.]

答: Also make sure Windows Firewall is not running, or at least not blocking MSDTC. I would turn it off entirely to rule it out, and then turn it back on and fine-tune what it is allowing if you really want Windows Firewall running.</p>


问:
Setting UIPicker view to selected string - Swift
Is there a way to set a UIPicker view to a selected string? My picker view is populated from a database and contains a set of names. I want to set the value of the view to a selected name when it is populated. The row number will change every time. Is it possible to set the value to match a string?

Below is my attempt based on the comments:

```<code>            var i : Int = 0
        while (nameArray[i] != assetArray[0].Owner)
        {
            i=i+1
        }
        scroll_owners.selectRow(i, inComponent: i, animated: true)
</code>```

This causes the code to break when trying to load it due to Index out of bounds.

答:
You are trying the correct approach but need to implement in another way.
Try this:

```<code>    let index = self.nameArray.index(where: {$0 == assetArray[0].Owner })
    scroll_owners.selectRow(index ?? 0, inComponent: 0, animated: true)
</code>```

Note: Pass the correct value for inComponent, if your picker view have only one column then it'll work fine.

Body:
Is there a way to set a UIPicker view to a selected string? My picker view is populated from a database and contains a set of names. I want to set the value of the view to a selected name when it is populated. The row number will change every time. Is it possible to set the value to match a string?

Below is my attempt based on the comments:

            var i : Int = 0
        while (nameArray[i] != assetArray[0].Owner)
        {
            i=i+1
        }
        scroll_owners.selectRow(i, inComponent: i, animated: true)

This causes the code to break when trying to load it due to Index out of bounds.

Body:
You are trying the correct approach but need to implement in another way.
Try this:

    let index = self.nameArray.index(where: {$0 == assetArray[0].Owner })
    scroll_owners.selectRow(index ?? 0, inComponent: 0, animated: true)

Note: Pass the correct value for inComponent, if your picker view have only one column then it'll work fine.


问:
php mysql - get product thumbnail image of a product
I'm using woocommerce, I'm trying to retrieve thumbnail image of a product, I've tried to use woocommerce api but it did not have any parameters for thumbnail, I've searched in database and found it in wp_postmeta table, but the structure of meta_value is very difficult to read, for example:

```<code>a:5:{s:5:"width";i:694;s:6:"height";i:660;s:4:"file";s:69:"2017/11/روغن-ذرت-زرین-1.8-لیتری-33150-26500اصل.jpg";s:5:"sizes";a:4:{s:9:"thumbnail";a:4:{s:4:"file";s:69:"روغن-ذرت-زرین-1.8-لیتری-33150-26500اصل-150x150.jpg";s:5:"width";i:150;s:6:"height";i:150;s:9:"mime-type";s:10:"image/jpeg";}s:6:"medium";a:4:{s:4:"file";s:69:"روغن-ذرت-زرین-1.8-لیتری-33150-26500اصل-300x285.jpg";s:5:"width";i:300;s:6:"height";i:285;s:9:"mime-type";s:10:"image/jpeg";}s:14:"shop_thumbnail";a:4:{s:4:"file";s:69:"روغن-ذرت-زرین-1.8-لیتری-33150-26500اصل-150x143.jpg";s:5:"width";i:150;s:6:"height";i:143;s:9:"mime-type";s:10:"image/jpeg";}s:12:"shop_catalog";a:4:{s:4:"file";s:69:"روغن-ذرت-زرین-1.8-لیتری-33150-26500اصل-300x285.jpg";s:5:"width";i:300;s:6:"height";i:285;s:9:"mime-type";s:10:"image/jpeg";}}s:10:"image_meta";a:12:{s:8:"aperture";s:1:"0";s:6:"credit";s:0:"";s:6:"camera";s:0:"";s:7:"caption";s:0:"";s:17:"created_timestamp";s:1:"0";s:9:"copyright";s:0:"";s:12:"focal_length";s:1:"0";s:3:"iso";s:1:"0";s:13:"shutter_speed";s:1:"0";s:5:"title";s:0:"";s:11:"orientation";s:1:"1";s:8:"keywords";a:0:{}}}
</code>```

it has all images of a product with different sizes, the question is, how can I read this in php and get the image src I want from this?

答:
Just a comment on @Aiyaz's Answer,
to include wordpress functions, just use
require_once("wordpress-folder-path/wp-load.php");
where wordpress-folder-path is the path to your wordpress installation.

But you could probably get away with using php's native unserialize($data) function.

Body:
I'm using woocommerce, I'm trying to retrieve thumbnail image of a product, I've tried to use woocommerce api but it did not have any parameters for thumbnail, I've searched in database and found it in wp_postmeta table, but the structure of meta_value is very difficult to read, for example:

a:5:{s:5:"width";i:694;s:6:"height";i:660;s:4:"file";s:69:"2017/11/روغن-ذرت-زرین-1.8-لیتری-33150-26500اصل.jpg";s:5:"sizes";a:4:{s:9:"thumbnail";a:4:{s:4:"file";s:69:"روغن-ذرت-زرین-1.8-لیتری-33150-26500اصل-150x150.jpg";s:5:"width";i:150;s:6:"height";i:150;s:9:"mime-type";s:10:"image/jpeg";}s:6:"medium";a:4:{s:4:"file";s:69:"روغن-ذرت-زرین-1.8-لیتری-33150-26500اصل-300x285.jpg";s:5:"width";i:300;s:6:"height";i:285;s:9:"mime-type";s:10:"image/jpeg";}s:14:"shop_thumbnail";a:4:{s:4:"file";s:69:"روغن-ذرت-زرین-1.8-لیتری-33150-26500اصل-150x143.jpg";s:5:"width";i:150;s:6:"height";i:143;s:9:"mime-type";s:10:"image/jpeg";}s:12:"shop_catalog";a:4:{s:4:"file";s:69:"روغن-ذرت-زرین-1.8-لیتری-33150-26500اصل-300x285.jpg";s:5:"width";i:300;s:6:"height";i:285;s:9:"mime-type";s:10:"image/jpeg";}}s:10:"image_meta";a:12:{s:8:"aperture";s:1:"0";s:6:"credit";s:0:"";s:6:"camera";s:0:"";s:7:"caption";s:0:"";s:17:"created_timestamp";s:1:"0";s:9:"copyright";s:0:"";s:12:"focal_length";s:1:"0";s:3:"iso";s:1:"0";s:13:"shutter_speed";s:1:"0";s:5:"title";s:0:"";s:11:"orientation";s:1:"1";s:8:"keywords";a:0:{}}}

it has all images of a product with different sizes, the question is, how can I read this in php and get the image src I want from this?


问:
How does android:layout_weight work?
When I have the following, it shows top layout with four colors has much smaller area than the bottom layout area.

According to this documentation, when you add more to layout_weight, it should increase the area, but it decreases in the code.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

  <LinearLayout
      android:orientation="horizontal"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:layout_weight="4">
      <TextView
          android:text="red"
          android:gravity="center_horizontal"
          android:background="#aa0000"
          android:layout_width="wrap_content"
          android:layout_height="fill_parent"
          android:layout_weight="3"/>
      <TextView
          android:text="green"
          android:gravity="center_horizontal"
          android:background="#00aa00"
          android:layout_width="wrap_content"
          android:layout_height="fill_parent"
          android:layout_weight="1"/>
      <TextView
          android:text="blue"
          android:gravity="center_horizontal"
          android:background="#0000aa"
          android:layout_width="wrap_content"
          android:layout_height="fill_parent"
          android:layout_weight="1"/>
      <TextView
          android:text="yellow"
          android:gravity="center_horizontal"
          android:background="#aaaa00"
          android:layout_width="wrap_content"
          android:layout_height="fill_parent"
          android:layout_weight="1"/>
  </LinearLayout>

  <LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1">
    <TextView
        android:text="row one"
        android:textSize="15pt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>
    <TextView
        android:text="row two"
        android:textSize="15pt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>
    <TextView
        android:text="row three"
        android:textSize="15pt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>
    <TextView
        android:text="row four"
        android:textSize="15pt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>
  </LinearLayout>

</LinearLayout>
</code>```

答: I had the same problem. The trick is not to use "wrap_content" or "fill_parent" for the controls you are setting a weight to. Instead set the layout_height to 0px (when inside a vertical layout) and then the child controls will get proportioned per the weight values.</p>

Title: How does android:layout_weight work?

Body:
When I have the following, it shows top layout with four colors has much smaller area than the bottom layout area.

According to this documentation, when you add more to layout_weight, it should increase the area, but it decreases in the code.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

  <LinearLayout
      android:orientation="horizontal"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:layout_weight="4">
      <TextView
          android:text="red"
          android:gravity="center_horizontal"
          android:background="#aa0000"
          android:layout_width="wrap_content"
          android:layout_height="fill_parent"
          android:layout_weight="3"/>
      <TextView
          android:text="green"
          android:gravity="center_horizontal"
          android:background="#00aa00"
          android:layout_width="wrap_content"
          android:layout_height="fill_parent"
          android:layout_weight="1"/>
      <TextView
          android:text="blue"
          android:gravity="center_horizontal"
          android:background="#0000aa"
          android:layout_width="wrap_content"
          android:layout_height="fill_parent"
          android:layout_weight="1"/>
      <TextView
          android:text="yellow"
          android:gravity="center_horizontal"
          android:background="#aaaa00"
          android:layout_width="wrap_content"
          android:layout_height="fill_parent"
          android:layout_weight="1"/>
  </LinearLayout>

  <LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1">
    <TextView
        android:text="row one"
        android:textSize="15pt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>
    <TextView
        android:text="row two"
        android:textSize="15pt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>
    <TextView
        android:text="row three"
        android:textSize="15pt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>
    <TextView
        android:text="row four"
        android:textSize="15pt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>
  </LinearLayout>

</LinearLayout>


问:
symfony adding repository function before rendering base.html.twig
In Symfony 3.4, base.html.twig I have a navbar showing number of the current user's messages. I use a repository entity function to do this. This function must be call every time when template base.html.twig is rendering but I don't want to put this function in all controllers how to do this by event listener before rendering base.html.twig? Override base controller ? </p>

```<code>base.html.twig :
  ....
  {{ include top_bar_nav.html.twig }}
  ....
</code>```

答:
A custom Twig extension is the correct way:

example in twig:

```<code>{{ number_of_current_users() }}
</code>```

create twig extension like this:

```<code><?php

namespace AppBundle\Twig;

use Doctrine\ORM\EntityRepository;

class UserExtension extends \Twig_Extension
{
    /**
     * @var EntityRepository
     */
    private $userRepository;

    /**
     * @param EntityRepository $repository
     */
    public function __construct(EntityRepository $repository)
    {
        $this->userRepository = $repository;
    }

    /**
     * {@inheritdoc}
     */
    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction('number_of_current_users', array($this, 'numberOfCurrentUsers')),
        );
    }

    /**
     * @param $sku
     *
     * @return string
     */
    public function numberOfCurrentUsers()
    {
        return $this->userRepository->getNumberOfCurrentUsers();
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'user';
    }
}
</code>```

and register it like this:

```<code>app.twig.users:
    class: AppBundle\Twig\UserExtension
    arguments: ['INJECT YOUR USER REPOSITORY HERE']
    public: false
    tags:
        - { name: twig.extension }
</code>```

Body:
In Symfony 3.4, base.html.twig I have a navbar showing number of the current user's messages. I use a repository entity function to do this. This function must be call every time when template base.html.twig is rendering but I don't want to put this function in all controllers how to do this by event listener before rendering base.html.twig? Override base controller ?

base.html.twig :
  ....
  {{ include top_bar_nav.html.twig }}
  ....

Body:
A custom Twig extension is the correct way:

example in twig:

{{ number_of_current_users() }}

create twig extension like this:

<?php

namespace AppBundle\Twig;

use Doctrine\ORM\EntityRepository;

class UserExtension extends \Twig_Extension
{
    /**
     * @var EntityRepository
     */
    private $userRepository;

    /**
     * @param EntityRepository $repository
     */
    public function __construct(EntityRepository $repository)
    {
        $this->userRepository = $repository;
    }

    /**
     * {@inheritdoc}
     */
    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction('number_of_current_users', array($this, 'numberOfCurrentUsers')),
        );
    }

    /**
     * @param $sku
     *
     * @return string
     */
    public function numberOfCurrentUsers()
    {
        return $this->userRepository->getNumberOfCurrentUsers();
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'user';
    }
}

and register it like this:

app.twig.users:
    class: AppBundle\Twig\UserExtension
    arguments: ['INJECT YOUR USER REPOSITORY HERE']
    public: false
    tags:
        - { name: twig.extension }


问:
Are there security risks to whitelisting all the column names in a model with strong params?
I'm in the process of extracting some parts of a project into an engine and I wanted to whitelist user params in such a way that the user doesn't have to configure anything.

This is what I ultimately came up with:

```<code>def user_params
  params.permit(::User.columns.map(&:name), :current_password, :password, :password_confirmation)
end
</code>```

It works so far (it allows all attributes in the user model and seems to reject anything else), however, I can't find another implementation of this in my searching that does it the same way and I'm wondering if that's because there's something I'm not seeing.

Is there a security vulnerability with setting strong params up like this?

答:
I'm in the process of extracting some parts of a project into an
  engine and I wanted to whitelist user params in such a way that the
  user doesn't have to configure anything.

The road the hell is paved with good intentions. What you are actually doing is just creating a mass assigment vulnerablity for any users of your gem.

Is there a security vulnerability with setting strong params up like
  this?

Yes. A malicous user can assign the id param or admin = true for example. Thats the exact scenario strong parameters is meant to avoid.

You should also wrap your head around that parameter whitelisting is not a model concern. That approach has been deemed deeply flawed since models are not request aware and the parameters that should be permitted can depend on the context and authorization.

Don't be that guy.

As a gem author your responsibility is to be secure by default. Convention over configuration means providing a good set of defaults - not making it idiot friendly.

You might want to look at Devise and provide a set of good default parameters and allow users to override it.

```<code>class SomeGem::UserController < SomeGem::BaseController

  def create
    @user = User.new(create_params)
    if @user.save
      yield @user if block_given?
      # ...
    else
      # ...
    end
  end

  private

  def create_params
    params.require(param_key).permit(*base_params)
  end

  def base_params
    :email, :current_password, :password, :password_confirmation
  end

  def param_key
     :user
  end
end
</code>```

This can then be simply overridden by users of the gem:

```<code>class MyUserController < SomeGem::UserController
  private

  def base_params
    super + [:first_name, :last_name]
  end
end
</code>```

An alternative to inheritance is by using a config option which can be changed in an initializer.

Body:
I'm in the process of extracting some parts of a project into an engine and I wanted to whitelist user params in such a way that the user doesn't have to configure anything.

This is what I ultimately came up with:

def user_params
  params.permit(::User.columns.map(&:name), :current_password, :password, :password_confirmation)
end

It works so far (it allows all attributes in the user model and seems to reject anything else), however, I can't find another implementation of this in my searching that does it the same way and I'm wondering if that's because there's something I'm not seeing.

Is there a security vulnerability with setting strong params up like this?

Body:
I'm in the process of extracting some parts of a project into an
  engine and I wanted to whitelist user params in such a way that the
  user doesn't have to configure anything.

The road the hell is paved with good intentions. What you are actually doing is just creating a mass assigment vulnerablity for any users of your gem.

Is there a security vulnerability with setting strong params up like
  this?

Yes. A malicous user can assign the id param or admin = true for example. Thats the exact scenario strong parameters is meant to avoid.

You should also wrap your head around that parameter whitelisting is not a model concern. That approach has been deemed deeply flawed since models are not request aware and the parameters that should be permitted can depend on the context and authorization.

Don't be that guy.

As a gem author your responsibility is to be secure by default. Convention over configuration means providing a good set of defaults - not making it idiot friendly.

You might want to look at Devise and provide a set of good default parameters and allow users to override it.

class SomeGem::UserController < SomeGem::BaseController

  def create
    @user = User.new(create_params)
    if @user.save
      yield @user if block_given?
      # ...
    else
      # ...
    end
  end

  private

  def create_params
    params.require(param_key).permit(*base_params)
  end

  def base_params
    :email, :current_password, :password, :password_confirmation
  end

  def param_key
     :user
  end
end

This can then be simply overridden by users of the gem:

class MyUserController < SomeGem::UserController
  private

  def base_params
    super + [:first_name, :last_name]
  end
end

An alternative to inheritance is by using a config option which can be changed in an initializer.


问:
Limit the number of Luigi workers when several scripts are run concurently
From what I saw and understood, when running several Luigi workflows at the same time, the number of workers is summed. This means that if I run two workflows together and that the number of workers is set to n, in the luigi.cfg file and provided that the workflows use more than n workers at the same time, the central scheduler will make use of 2xn workers.

In the manual of Luigi, I could not find any way to restrict the number of workers to n, even if I run a dozen of workflows at the same time.

This is my luigi.cfg file

```<code>[core]
workers: 3
</code>```

This is the example script I am using (it makes in fact use of sciluigi (a layer on top of luigi) but I don't think it makes a difference concerning the task and the scheduler configuration). I'd like that when I run it several times together, the 3 last workflows wait that the three first workflows are done before starting.

```<code>import optparse
import luigi
import sciluigi
import random
import time
import sys
import os
import subprocess

class MyFooWriter(sciluigi.Task):
    # We have no inputs here
    # Define outputs:
    outdir = sciluigi.Parameter();
    def out_foo(self):
        return sciluigi.TargetInfo(self, os.path.join(self.outdir,'foo.txt'))
    def run(self):
        with self.out_foo().open('w') as foofile:
            foofile.write('foo\n')

class MyFooReplacer(sciluigi.Task):
    replacement = sciluigi.Parameter() # Here, we take as a parameter
                                  # what to replace foo with.
    outFile = sciluigi.Parameter();
    outdir = sciluigi.Parameter();
    # Here we have one input, a "foo file":
    in_foo = None

    # ... and an output, a "bar file":
    def out_replaced(self):
        return sciluigi.TargetInfo(self, os.path.join(self.outdir, self.outFile))

    def run(self):
        replacement = ""
        with open(self.in_foo().path, 'r') as content_file:
            content = content_file.read()
            replacement = content.replace('foo', self.replacement)
            for i in range(1,30):
                sys.stderr.write(str(i)+"\n")
                time.sleep(1)
        with open(self.out_replaced().path,'w') as out_f:
            out_f.write(replacement)

class MyWorkflow(sciluigi.WorkflowTask):
    outdir = luigi.Parameter()
    def workflow(self):
        #rdint = random.randint(1,1000)
        rdint = 100
        barfile = "foobar_" + str(rdint) +'.bar.txt'
        foowriter = self.new_task('foowriter', MyFooWriter, outdir = self.outdir)
        fooreplacer = self.new_task('fooreplacer', MyFooReplacer, replacement='bar', outFile = barfile,  outdir =  self.outdir)
        fooreplacer.in_foo = foowriter.out_foo
        return fooreplacer

# End of script ....
if __name__ == '__main__':
    parser = optparse.OptionParser()
    parser.add_option('-d', dest = "outdir", action="store", default=".")
    options, remainder = parser.parse_args()
    params = {"outdir" : options.outdir}
    wf = [MyWorkflow(outdir = options.outdir)]
    luigi.build(wf)
</code>```

This is a little perl script I use to run the script concurrently (in Perl, my favourite language :-)).

```<code>#! /usr/bin/perl

use strict;

for (my $i = 0; $i < 6; $i++) {
  my $testdir = "test".$i;
  system("mkdir -p $testdir");
  system("python run_sciluigi.py -d $testdir&");
  sleep (2)
}
</code>```

答:
While not exactly a workers restriction, it is possible to use the resources concept to put a global limit on concurrent execution.

In luigi.cfg

```<code>[resources]
max_workers=5
</code>```

In all of your tasks:

```<code>class MyFooReplacer(sciluigi.Task):
    resources = {'max_workers': 1}
</code>```

http://luigi.readthedocs.io/en/stable/configuration.html#resources

Body:
From what I saw and understood, when running several Luigi workflows at the same time, the number of workers is summed. This means that if I run two workflows together and that the number of workers is set to n, in the luigi.cfg file and provided that the workflows use more than n workers at the same time, the central scheduler will make use of 2xn workers.

In the manual of Luigi, I could not find any way to restrict the number of workers to n, even if I run a dozen of workflows at the same time.

This is my luigi.cfg file

[core]
workers: 3

This is the example script I am using (it makes in fact use of sciluigi (a layer on top of luigi) but I don't think it makes a difference concerning the task and the scheduler configuration). I'd like that when I run it several times together, the 3 last workflows wait that the three first workflows are done before starting.

import optparse
import luigi
import sciluigi
import random
import time
import sys
import os
import subprocess

class MyFooWriter(sciluigi.Task):
    # We have no inputs here
    # Define outputs:
    outdir = sciluigi.Parameter();
    def out_foo(self):
        return sciluigi.TargetInfo(self, os.path.join(self.outdir,'foo.txt'))
    def run(self):
        with self.out_foo().open('w') as foofile:
            foofile.write('foo\n')

class MyFooReplacer(sciluigi.Task):
    replacement = sciluigi.Parameter() # Here, we take as a parameter
                                  # what to replace foo with.
    outFile = sciluigi.Parameter();
    outdir = sciluigi.Parameter();
    # Here we have one input, a "foo file":
    in_foo = None

    # ... and an output, a "bar file":
    def out_replaced(self):
        return sciluigi.TargetInfo(self, os.path.join(self.outdir, self.outFile))

    def run(self):
        replacement = ""
        with open(self.in_foo().path, 'r') as content_file:
            content = content_file.read()
            replacement = content.replace('foo', self.replacement)
            for i in range(1,30):
                sys.stderr.write(str(i)+"\n")
                time.sleep(1)
        with open(self.out_replaced().path,'w') as out_f:
            out_f.write(replacement)

class MyWorkflow(sciluigi.WorkflowTask):
    outdir = luigi.Parameter()
    def workflow(self):
        #rdint = random.randint(1,1000)
        rdint = 100
        barfile = "foobar_" + str(rdint) +'.bar.txt'
        foowriter = self.new_task('foowriter', MyFooWriter, outdir = self.outdir)
        fooreplacer = self.new_task('fooreplacer', MyFooReplacer, replacement='bar', outFile = barfile,  outdir =  self.outdir)
        fooreplacer.in_foo = foowriter.out_foo
        return fooreplacer

# End of script ....
if __name__ == '__main__':
    parser = optparse.OptionParser()
    parser.add_option('-d', dest = "outdir", action="store", default=".")
    options, remainder = parser.parse_args()
    params = {"outdir" : options.outdir}
    wf = [MyWorkflow(outdir = options.outdir)]
    luigi.build(wf)

This is a little perl script I use to run the script concurrently (in Perl, my favourite language :-)).

#! /usr/bin/perl

use strict;

for (my $i = 0; $i < 6; $i++) {
  my $testdir = "test".$i;
  system("mkdir -p $testdir");
  system("python run_sciluigi.py -d $testdir&");
  sleep (2)
}

Body:
While not exactly a workers restriction, it is possible to use the resources concept to put a global limit on concurrent execution.

In luigi.cfg

[resources]
max_workers=5

In all of your tasks:

class MyFooReplacer(sciluigi.Task):
    resources = {'max_workers': 1}

http://luigi.readthedocs.io/en/stable/configuration.html#resources


问:
Using XMLHttpRequests in Javascript
Chrome extensions are allowed to make XMLhttpRequests outside of your own domain if you specify them in your Json file. However, after I have done this, I still get status 0 when trying to make an XMLhttpRequest. Does anyone know how to fix this?

My javascript:

```<code>var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
   if (xhr.readyState == 4) {
   alert(xhr.status);
       if (xhr.status == 200) {
       alert(xhr.responseText);
       }
   }
}
var url = "http://search.twitter.com/trends/current.json?exclude=hashtags";
xhr.open("GET", url, true);
xhr.send();
</code>```

My Json file

```<code>{
  "name": "My First Extension",
  "version": "1.0",
  "description": "The first extension that I made.",
  "browser_action": {
    "default_icon": "icon.png",
    "popup": "popup.html"
  },
  "permissions": [
    "http://search.twitter.com/"
  ]
}
</code>```

This is the link to the google example http://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/extensions/docs/examples/howto/contentscript_xhr/background.html?view=markup

答:
Looks like that permissions are related to URLs not to hosts.

Try using a wildcard

```<code>http://search.twitter.com/*
</code>```

http://code.google.com/chrome/extensions/match_patterns.html

Title: Using XMLHttpRequests in Javascript

Body:
Chrome extensions are allowed to make XMLhttpRequests outside of your own domain if you specify them in your Json file. However, after I have done this, I still get status 0 when trying to make an XMLhttpRequest. Does anyone know how to fix this?

My javascript:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
   if (xhr.readyState == 4) {
   alert(xhr.status);
       if (xhr.status == 200) {
       alert(xhr.responseText);
       }
   }
}
var url = "http://search.twitter.com/trends/current.json?exclude=hashtags";
xhr.open("GET", url, true);
xhr.send();

My Json file

{
  "name": "My First Extension",
  "version": "1.0",
  "description": "The first extension that I made.",
  "browser_action": {
    "default_icon": "icon.png",
    "popup": "popup.html"
  },
  "permissions": [
    "http://search.twitter.com/"
  ]
}

This is the link to the google example http://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/extensions/docs/examples/howto/contentscript_xhr/background.html?view=markup

Body:
Looks like that permissions are related to URLs not to hosts.

Try using a wildcard

http://search.twitter.com/*

http://code.google.com/chrome/extensions/match_patterns.html