问:
Putting values in array to create a JSON
I have the following classes:

```<code>public class Person
{
    public string typeOfPerson { get; set; }
    public string personIdentifier { get; set; }
    public Persondetails personDetails { get; set; }
    public Name[] names { get; set; }
}

public class Name
{
    public string id { get; set; }
    public string firstName { get; set; }
    public string middleNames { get; set; }
    public string surName { get; set; }
    public string nameSuffix { get; set; }
}

public class Persondetails
{
    public string dateOfBirth { get; set; }
    public string yearOfBirth { get; set; }
    public string age { get; set; }
    public string gender { get; set; }
    public string noOfDependents { get; set; }
    public string occupancyStatus { get; set; }
    public string mothersMaidenName { get; set; }
    public string spouseName { get; set; }
}
</code>```

I want to create a following JSON with that:

```<code>"contacts": [{
            "id": "APPLICANT_CONTACT_ID_1",
            "person": {
                "typeOfPerson": "",
                "personIdentifier": "",
                "personDetails": {
                    "dateOfBirth": "1990-12-09",
                    "yearOfBirth": "",
                    "age": "",
                    "gender": "",
                    "noOfDependents": "",
                    "occupancyStatus": "",
                    "mothersMaidenName": "",
                    "spouseName": ""
                },
                "names": [{
                    "id": "",
                    "firstName": "Test1",
                    "middleNames": "D",
                    "surName": "Test2",
                    "nameSuffix": ""
                }]
            }

        }]
</code>```

any help will be greatly appreciated.

答:
Have you considered building your classes like this ??
(The JsonProperty is the value in the JSON)

```<code>    public partial class Example
    {
        [JsonProperty("contacts")]
        public Contact[] Contacts { get; set; }
    }

    public partial class Contact
    {
        [JsonProperty("id")]
        public string Id { get; set; }

        [JsonProperty("person")]
        public Person Person { get; set; }
    }

    public partial class Person
    {
        [JsonProperty("typeOfPerson")]
        public string TypeOfPerson { get; set; }

        [JsonProperty("personIdentifier")]
        public string PersonIdentifier { get; set; }

        [JsonProperty("personDetails")]
        public PersonDetails PersonDetails { get; set; }

        [JsonProperty("names")]
        public Name[] Names { get; set; }
    }

    public partial class Name
    {
        [JsonProperty("id")]
        public string Id { get; set; }

        [JsonProperty("firstName")]
        public string FirstName { get; set; }

        [JsonProperty("middleNames")]
        public string MiddleNames { get; set; }

        [JsonProperty("surName")]
        public string SurName { get; set; }

        [JsonProperty("nameSuffix")]
        public string NameSuffix { get; set; }
    }

    public partial class PersonDetails
    {
        [JsonProperty("dateOfBirth")]
        public DateTimeOffset DateOfBirth { get; set; }

        [JsonProperty("yearOfBirth")]
        public string YearOfBirth { get; set; }

        [JsonProperty("age")]
        public string Age { get; set; }

        [JsonProperty("gender")]
        public string Gender { get; set; }

        [JsonProperty("noOfDependents")]
        public string NoOfDependents { get; set; }

        [JsonProperty("occupancyStatus")]
        public string OccupancyStatus { get; set; }

        [JsonProperty("mothersMaidenName")]
        public string MothersMaidenName { get; set; }

        [JsonProperty("spouseName")]
        public string SpouseName { get; set; }
    }
</code>```

and then you will serialize the object you create using:

```<code>jsonString = JsonSerializer.Serialize(yourObject);
</code>```

and you will receive the JSON you want

easy class generation with this tool
https://app.quicktype.io/?l=csharp

Serialize

Body:
I have the following classes:

public class Person
{
    public string typeOfPerson { get; set; }
    public string personIdentifier { get; set; }
    public Persondetails personDetails { get; set; }
    public Name[] names { get; set; }
}

public class Name
{
    public string id { get; set; }
    public string firstName { get; set; }
    public string middleNames { get; set; }
    public string surName { get; set; }
    public string nameSuffix { get; set; }
}

public class Persondetails
{
    public string dateOfBirth { get; set; }
    public string yearOfBirth { get; set; }
    public string age { get; set; }
    public string gender { get; set; }
    public string noOfDependents { get; set; }
    public string occupancyStatus { get; set; }
    public string mothersMaidenName { get; set; }
    public string spouseName { get; set; }
}

I want to create a following JSON with that:

"contacts": [{
            "id": "APPLICANT_CONTACT_ID_1",
            "person": {
                "typeOfPerson": "",
                "personIdentifier": "",
                "personDetails": {
                    "dateOfBirth": "1990-12-09",
                    "yearOfBirth": "",
                    "age": "",
                    "gender": "",
                    "noOfDependents": "",
                    "occupancyStatus": "",
                    "mothersMaidenName": "",
                    "spouseName": ""
                },
                "names": [{
                    "id": "",
                    "firstName": "Test1",
                    "middleNames": "D",
                    "surName": "Test2",
                    "nameSuffix": ""
                }]
            }

        }]

any help will be greatly appreciated.

Body:
Have you considered building your classes like this ??
(The JsonProperty is the value in the JSON)

    public partial class Example
    {
        [JsonProperty("contacts")]
        public Contact[] Contacts { get; set; }
    }

    public partial class Contact
    {
        [JsonProperty("id")]
        public string Id { get; set; }

        [JsonProperty("person")]
        public Person Person { get; set; }
    }

    public partial class Person
    {
        [JsonProperty("typeOfPerson")]
        public string TypeOfPerson { get; set; }

        [JsonProperty("personIdentifier")]
        public string PersonIdentifier { get; set; }

        [JsonProperty("personDetails")]
        public PersonDetails PersonDetails { get; set; }

        [JsonProperty("names")]
        public Name[] Names { get; set; }
    }

    public partial class Name
    {
        [JsonProperty("id")]
        public string Id { get; set; }

        [JsonProperty("firstName")]
        public string FirstName { get; set; }

        [JsonProperty("middleNames")]
        public string MiddleNames { get; set; }

        [JsonProperty("surName")]
        public string SurName { get; set; }

        [JsonProperty("nameSuffix")]
        public string NameSuffix { get; set; }
    }

    public partial class PersonDetails
    {
        [JsonProperty("dateOfBirth")]
        public DateTimeOffset DateOfBirth { get; set; }

        [JsonProperty("yearOfBirth")]
        public string YearOfBirth { get; set; }

        [JsonProperty("age")]
        public string Age { get; set; }

        [JsonProperty("gender")]
        public string Gender { get; set; }

        [JsonProperty("noOfDependents")]
        public string NoOfDependents { get; set; }

        [JsonProperty("occupancyStatus")]
        public string OccupancyStatus { get; set; }

        [JsonProperty("mothersMaidenName")]
        public string MothersMaidenName { get; set; }

        [JsonProperty("spouseName")]
        public string SpouseName { get; set; }
    }

and then you will serialize the object you create using:

jsonString = JsonSerializer.Serialize(yourObject);

and you will receive the JSON you want

easy class generation with this tool
https://app.quicktype.io/?l=csharp

Serialize


来源: stackexchange

问:
What is the best way to delete a component with CLI
I tried using "ng destroy component foo" and it tells me "The destroy command is not supported by Angular-CLI"

How do we properly delete components with Angular CLI?

答:
This is not supported by Angular CLI and they are in no mood to include it any time soon.

Here is the link to the actual created issue - https://github.com/angular/angular-cli/issues/1776

And a screenshot of the solution from the officials -

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY
I am trying all possible ways to create a React application. I have tried Maven, and now I am trying create-react-app from Facebook Incubators.

When I tried to run the command create-react-app my-app in npm environment, it worked on my personal system with no issues. But, when I tried the same command in my work environment, I encountered the following error on my command line:

```<code>npm ERR! node v6.10.2
npm ERR! npm  v3.10.10
npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY

npm ERR! unable to get local issuer certificate
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>
</code>```

答:
In my case, at some point I set my global config to use a cert that was meant for a project.

npm config list

```<code>/path/to/global/.npmrc
NODE_EXTRA_CA_CERTS = "./certs/chain.pem"
</code>```

I opened the file, removed the line and npm install worked again.

Body:
I am trying all possible ways to create a React application. I have tried Maven, and now I am trying create-react-app from Facebook Incubators.

When I tried to run the command create-react-app my-app in npm environment, it worked on my personal system with no issues. But, when I tried the same command in my work environment, I encountered the following error on my command line:

npm ERR! node v6.10.2
npm ERR! npm  v3.10.10
npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY

npm ERR! unable to get local issuer certificate
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

Body:
In my case, at some point I set my global config to use a cert that was meant for a project.

npm config list

/path/to/global/.npmrc
NODE_EXTRA_CA_CERTS = "./certs/chain.pem"

I opened the file, removed the line and npm install worked again.


问:
Getting a random cell from excel file using c#.net Interop framework consoleApp
Getting a random cell from excel file using c#.net framework consoleApp so I tried this but it gives me this exception:

System.Runtime.InteropServices.COMException: 'Exception from HRESULT:
  0x800A03EC'

```<code>Workbook excelBook = excelApp.Workbooks.Open(@"C:\\Projects\\ExcelSingleValue\\kTest.xlsx");
_Worksheet excelSheet = excelBook.Sheets[1];
Range excelRange = excelSheet.UsedRange;

int rows = excelRange.Rows.Count;
int cols = excelRange.Columns.Count;

Random randomName = new Random();
Console.WriteLine((excelRange.Cells[randomName.Next(rows),1].Value2.ToString()));
</code>```

答:
You are very close...

Note that randomName.Next(rows) can return zero.  If it does then .Cells[randomName.Next(rows),1] will give you the error you see.

If your sheet has nothing on it then rows will always equal 1 and you have a 50% chance of the random number being zero.

Solution: Set the minimum value to 1 like this: Next(1, rows)

```<code>Console.WriteLine((excelRange.Cells[randomName.Next(1, rows),1].Value2.ToString()));
</code>```

Body:
Getting a random cell from excel file using c#.net framework consoleApp so I tried this but it gives me this exception:

System.Runtime.InteropServices.COMException: 'Exception from HRESULT:
  0x800A03EC'

Workbook excelBook = excelApp.Workbooks.Open(@"C:\\Projects\\ExcelSingleValue\\kTest.xlsx");
_Worksheet excelSheet = excelBook.Sheets[1];
Range excelRange = excelSheet.UsedRange;

int rows = excelRange.Rows.Count;
int cols = excelRange.Columns.Count;

Random randomName = new Random();
Console.WriteLine((excelRange.Cells[randomName.Next(rows),1].Value2.ToString()));

Body:
You are very close...

Note that randomName.Next(rows) can return zero.  If it does then .Cells[randomName.Next(rows),1] will give you the error you see.

If your sheet has nothing on it then rows will always equal 1 and you have a 50% chance of the random number being zero.

Solution: Set the minimum value to 1 like this: Next(1, rows)

Console.WriteLine((excelRange.Cells[randomName.Next(1, rows),1].Value2.ToString()));


问:
SOLVED - How to generate multiple QR code in one loop using Javascript?
For example, I want to generate 10 different QR code with the same information. For now, I can generate one QR code per time only. Should I put in a loop or any solution?

    function makeCode () {

        // All inputs that contain the value
        $qrs = $('.qr_value');

        // Create a new instance of the QRCode for each input
        $qrs.each(function(index, item){

            // We cant hace same id multiple times, so, we need to create dynamic ids,
            // thats why we are concatenating the index to the id string
            let containerQr =  "qrcode_"+index;

            // Create QR
            let qrcode = new QRCode(containerQr, {
                text: item.value, // value to read on qr
                width: 500,
                height: 500,
                colorDark : "#000000",
                colorLight : "#ffffff",
                correctLevel : QRCode.CorrectLevel.H,
            });
        });
    }

    makeCode();```
<pre class="snippet-code-html lang-html prettyprint-override"><code>// loop on any technology that u use, is php on my case
foreach($values as $key => $value){
    <input type="hidden" class="qr_value" value="$value">
    <div id="qrcode_$key"></div>
}</code>```

答:
Use a simply for() loop and iterate a counter wrapped around the code that generates your QR code.

```<code>let i = 1;
while( i <= 10){
    qrcode.clear(); // clear the code.
    qrcode.makeCode(); // make another code.
}
</code>```

for(let i = 1; i <= 10; i++){
  // generate your qr code
  console.log(i)
}```

Body:
For example, I want to generate 10 different QR code with the same information. For now, I can generate one QR code per time only. Should I put in a loop or any solution?

    function makeCode () {

        // All inputs that contain the value
        $qrs = $('.qr_value');

        // Create a new instance of the QRCode for each input
        $qrs.each(function(index, item){

            // We cant hace same id multiple times, so, we need to create dynamic ids,
            // thats why we are concatenating the index to the id string
            let containerQr =  "qrcode_"+index;

            // Create QR
            let qrcode = new QRCode(containerQr, {
                text: item.value, // value to read on qr
                width: 500,
                height: 500,
                colorDark : "#000000",
                colorLight : "#ffffff",
                correctLevel : QRCode.CorrectLevel.H,
            });
        });
    }

    makeCode();

// loop on any technology that u use, is php on my case
foreach($values as $key => $value){
    <input type="hidden" class="qr_value" value="$value">

}

Body:
Use a simply for() loop and iterate a counter wrapped around the code that generates your QR code.

let i = 1;
while( i <= 10){
    qrcode.clear(); // clear the code.
    qrcode.makeCode(); // make another code.
}

for(let i = 1; i <= 10; i++){
  // generate your qr code
  console.log(i)
}


问:
SQL - simple query and join problems
I believe this is a simple task, and i have asked it here before but failed to provide enough information or my attempts at it, so i do apologise for that.

I need to create a query that displays the list of clubs that provide kids playroom as one of their facilities, showing club name, state, club phone number sorted by club state.

Just really struggling with queries atm!

My database:

Attempt at solving this:

```<code>SELECT DISTINCT BRANCH.ClubName, BRANCH.State, FACILITY.Description
FROM FACILITY_LIST
    JOIN FACILITY
        ON FACILITY_LIST.FacilityType
    JOIN BRANCH
        ON BRANCH.BranchID
WHERE FACILITY.Description LIKE '% kids %'
</code>```

This did provide the list of Facilities that provide kids playrooms, but it just repeated over and over within all the clubnames.

Any help would be appreciated!

答:
Your have incorrect join. When you use join between two tables you need to join on common key between them as following.

```<code>SELECT
    DISTINCT b.ClubName,
    b.State,
    f.Description
FROM FACILITY_LIST fl
JOIN FACILITY f
ON fl.FacilityType = f.FacilityType
JOIN BRANCH b
ON fl.BranchID = b.BranchID
WHERE f.Description LIKE '% kids %'
</code>```

Title: SQL - simple query and join problems

Body:
I believe this is a simple task, and i have asked it here before but failed to provide enough information or my attempts at it, so i do apologise for that.

I need to create a query that displays the list of clubs that provide kids playroom as one of their facilities, showing club name, state, club phone number sorted by club state.

Just really struggling with queries atm!

My database:

Attempt at solving this:

SELECT DISTINCT BRANCH.ClubName, BRANCH.State, FACILITY.Description
FROM FACILITY_LIST
    JOIN FACILITY
        ON FACILITY_LIST.FacilityType
    JOIN BRANCH
        ON BRANCH.BranchID
WHERE FACILITY.Description LIKE '% kids %'

This did provide the list of Facilities that provide kids playrooms, but it just repeated over and over within all the clubnames.

Any help would be appreciated!

Body:
Your have incorrect join. When you use join between two tables you need to join on common key between them as following.

SELECT
    DISTINCT b.ClubName,
    b.State,
    f.Description
FROM FACILITY_LIST fl
JOIN FACILITY f
ON fl.FacilityType = f.FacilityType
JOIN BRANCH b
ON fl.BranchID = b.BranchID
WHERE f.Description LIKE '% kids %'


问:
Angular/C# null body sent for POST
I've trying to do a POST in Angular, which makes a call to my C# backend. One API call works fine, but the other one doesn't exactly. I'm having a hard time figuring out what's going on, but I see that when I open the Network window in my browser's DevTools, the request payload has the JSON populated just fine. But in C#/the backend, it receives a null object, and I get a 200 code/null response from the call.

I've got the following code in Angular:

item.service.ts

```<code>private readonly _api = '...'
private postOptions = { headers: { 'Content-Type': 'application/json; charset=utf-8' }};

public addItem(formGroup: formGroup, isInactive: boolean): Observable<Item> {
    let api = ``;

    // These require different API calls depending on the flag
    if (isInactive)
        api = `${this._api}/AddInactiveItem`;
    else
        api = `${this._api}/AddItem`; // This one is the one having issues
    const body = ItemPost.parse(formGroup.value);

    return this.http.post<Item>(api, body, this.postOptions).pipe(
        this.handle(
            "POST successful",
            "Error with POST"
        )
    );
}
</code>```

item-post.ts

```<code>export class ItemPost {
    Name: string;
    Inactive: string;
    ...

    public static parse(obj: any): ItemPost {
        return !obj ? undefined : {
            Name: obj.name,
            Inactive: obj.inactive,
            ...
        };
    }
}
</code>```

My backend/POST code is in C#. Both of my POST methods are built the exact same, but with different SQL calls.

```<code>[HttpPost]
public JsonResult AddInactiveItem([FromBody] ItemBody item)
{
    if (!ModelState.IsValid)
        return Json(null);

    // Do SQL call for POST here, return JSON
}

[HttpPost]
public JsonResult AddItem([FromBody] ItemBody item) // This is where I have a breakpoint and it's passing in null
{
    if (!ModelState.IsValid)
        return Json(null);  // And this is where I find myself

    // Do SQL call for POST here, return JSON
}
</code>```

JSON Payload (sorry, unable to get a screenshot but this is what I'm seeing):

```<code>{"Name":"Test", ..., "Inactive":"N"}
</code>```

答:
I think you are having problem with: </p>

```<code>`$(this.api}/AddInactiveItem`
</code>```

<p>The right syntax for template strings is: </p>

```<code>`${this.api}/AddInactiveItem`
</code>```

Title: Angular/C# null body sent for POST

Body:
I've trying to do a POST in Angular, which makes a call to my C# backend. One API call works fine, but the other one doesn't exactly. I'm having a hard time figuring out what's going on, but I see that when I open the Network window in my browser's DevTools, the request payload has the JSON populated just fine. But in C#/the backend, it receives a null object, and I get a 200 code/null response from the call.

I've got the following code in Angular:

item.service.ts

private readonly _api = '...'
private postOptions = { headers: { 'Content-Type': 'application/json; charset=utf-8' }};

public addItem(formGroup: formGroup, isInactive: boolean): Observable<Item> {
    let api = ``;

    // These require different API calls depending on the flag
    if (isInactive)
        api = `${this._api}/AddInactiveItem`;
    else
        api = `${this._api}/AddItem`; // This one is the one having issues
    const body = ItemPost.parse(formGroup.value);

    return this.http.post<Item>(api, body, this.postOptions).pipe(
        this.handle(
            "POST successful",
            "Error with POST"
        )
    );
}

item-post.ts

export class ItemPost {
    Name: string;
    Inactive: string;
    ...

    public static parse(obj: any): ItemPost {
        return !obj ? undefined : {
            Name: obj.name,
            Inactive: obj.inactive,
            ...
        };
    }
}

My backend/POST code is in C#. Both of my POST methods are built the exact same, but with different SQL calls.

[HttpPost]
public JsonResult AddInactiveItem([FromBody] ItemBody item)
{
    if (!ModelState.IsValid)
        return Json(null);

    // Do SQL call for POST here, return JSON
}

[HttpPost]
public JsonResult AddItem([FromBody] ItemBody item) // This is where I have a breakpoint and it's passing in null
{
    if (!ModelState.IsValid)
        return Json(null);  // And this is where I find myself

    // Do SQL call for POST here, return JSON
}

JSON Payload (sorry, unable to get a screenshot but this is what I'm seeing):

{"Name":"Test", ..., "Inactive":"N"}

Body:
I think you are having problem with:

`$(this.api}/AddInactiveItem`

The right syntax for template strings is:

`${this.api}/AddInactiveItem`


问:
Inventory design approach (inheritance vs generics)
Greetings!
I am trying to decide on which is the best approach to implement a following scenario:

Vehicle and Part are both "entites" which can be an Item in an Inventory.
Vehicle has the usual VIN, Year, Make, Model, Type, etc, etc... while Part has PartNumber, QuantityOnHand, IsPartOfSet, Vendor...
When "stocked" in an Inventory as an Item, both have RetailPrice, PurchasePrice, PurchaseDate but at the same time they have a lot of other properties that are not in common
(e.g Vehicle has CurrentMileage, NewOrUsed, etc... etc.. while Part has TreshholdCount, LastCountDate, etc, etc..)
So as you can see both Part and Vehicle can be in Inventory, but they have very few properties that are share (more that they don't)...

With scenario above, I am trying to decide between several approaches:

Option 1 - Separate classes for everything (no inheritance)

Vehicle - common vehicle properties (VIN, year, make, model, etc, etc)

VehicleInventoryItem - has a reference to Vehicle and contains other inventory specific properties (pricing, warranties, status)

VehicleInventoryManager - singleton with business logic add, remove, notify, etc, etc

Part

PartInventoryItem

PartInventoryManager

I think this approach is most flexible while it suffers for some property repetition. Managers also can have very different methods...

Option 2 - Base class simple inheritance

Vehicle - same as option 1

Part - same as option 1

InventoryItem  - base class

VehicleInventoryItem - extends InventoryItem, references Vehicle

PartInventoryItem - extends InventoryItem, references Part

InventoryManager - all methods accept InventoryItem as parameters

With this approach, I am worried about InventoryManager being polluted with different operations needed for parts vs vehicles

Option 3 - Generics

Item - where T will be part or vehicle (I can even go more specific then, e.g. - VehicleItem : Item)

Inventory - holds reference to Item

InventoryManager - singleton that operates on T

In this approach, there is less classes but again I am worried about InventoryManager

Recap

Vehicle and Part share very few properties when "stocked" in Inventory.

Inventory management for Vehicle and Part will also be mostly different (parts are "reordered" when qty on hand is low, when vehicle is sold similar one may be purchased but it is unique)

In my scenario there will be no other objects/models that will be "stockable" (being in Inventory of any kind)

Questions

What does community think? Is there another approach (perhaps interfaces?)
If 2 domain objects share at least 1 property (e.g. PurchasePrice), should that warrant having some sort of inheritance (e.g. option 2 or 3)

答:
I'd create an abstract base class representing any item that is potentially held in inventory. Something like InventoryItem. It would have the basic properties you mention that everything has in common: RetailPrice, PurchasePrice, PurchaseDate, etc. And it would provide a default implementation (where appropriate) for certain properties and methods.

Then, I would inherit from this class and specialize it for each of the items you plan on stocking: Vehicle and Part. Override the methods that you need to, implement all of the methods marked as abstract, and add any additional functionality and/or business logic that is required by the specific subclasses.

There's absolutely no reason to use an interface here. As you mention, all of the things you sell share many common attributes. They have some extra ones and some of the functions might work differently, but there's a lot that is fundamentally the same. There's no reason to duplicate that functionality across multiple places. Using an abstract base class gives you the chance to provide a default implementation.

You don't need an InventoryManager class at all: you're right to be suspect of it having to be aware of the different types of subclasses. Just let the derived classes do all the work. That's what they're for.

For more on why abstract base classes are generally superior to interfaces, see the following answers:

When should I choose inheritance over an interface when designing C# class libraries?

Interface / Abstract Class Coding Standard.

And I can't imagine why generics are relevant here. They're a specific tool used to solve a specific problem, not a general design pattern. If you need generics, use them. But a well-conceived design that takes advantage of inheritance and polymorphism also makes it a lot less unlikely that you'll need them in the first place.


问:
No data is being loaded when reading tfrecord files
I am trying to train the model defined here using the function train defined in the same script. I have attempted to use a tf record file provided by the authors in this link (to do that, the only modifications that I made were changing init_path=None and writing the path to the tfrecord file in the txt file train_list=train_tfs.txt, both defined in shift_params.py's shift_v1 ).

However, even trying this simple test, I get the following error:

```<code>OutOfRangeError (see above for traceback): RandomShuffleQueue '_1_shuffle_batch_join/random_shuffle_queue' is closed and has insufficient elements (requested 15, current size 0)
         [[Node: shuffle_batch_join = QueueDequeueManyV2[component_types=[DT_UINT8, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_INT64, DT_STRING], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/device:CPU:0"](shuffle_batch_join/random_shuffle_queue, shuffle_batch_join/n)]]
</code>```

As far as I understand, this error means that no data is being loaded. So my guess is that the problem is in the function read_example in shift_dset.py, as shown below (I have kept only the part of the code that loads the images ims and the audio sound. For the complete code, please check here.)

```<code>def read_example(rec_queue, pr, input_types):
  reader = tf.TFRecordReader()
  k, serialized_example = reader.read(rec_queue)
  full = pr.full_im_dim

  feats = {}

  feats['im_0'] = tf.FixedLenFeature([], dtype=tf.string)
  feats['im_1'] = tf.FixedLenFeature([], dtype=tf.string)

  feats['sound'] = tf.FixedLenFeature([], dtype=tf.string)

  if pr.variable_frame_count:
    feats['num_frames'] = tf.FixedLenFeature([1], dtype=tf.int64)
  example = tf.parse_single_example(serialized_example, features = feats)

  total_frames = pr.total_frames if not pr.variable_frame_count \
                 else tf.cast(example['num_frames'][0], tf.int32)

  assert not pr.variable_frame_count

  def f(x):
    x.set_shape((full*total_frames/2, full, 3))
    return tf.reshape(x, (total_frames/2, full, full, 3))
  im_parts = map(f, [tf.image.decode_jpeg(example['im_0'], channels = 3, name = 'decode_im1'),
                     tf.image.decode_jpeg(example['im_1'], channels = 3, name = 'decode_im2')])

  samples = tf.decode_raw(example['sound'], tf.int16)

  samples.set_shape((pr.full_samples_len*2))
  samples = tf.reshape(samples, (pr.full_samples_len, 2))

  samples = tf.cast(samples, 'float32') / np.iinfo(np.dtype(np.int16)).max

  num_slice_frames = pr.sampled_frames
  num_samples = int(pr.samples_per_frame * float(num_slice_frames))

  if pr.do_shift:
    choices = []
    max_frame = total_frames - num_slice_frames
    frames1 = ([0] if pr.fix_frame else xrange(max_frame))
    for frame1 in frames1:
      found = False
      for frame2 in reversed(range(max_frame)):
        inv1 = xrange(frame1, frame1 + num_slice_frames)
        inv2 = xrange(frame2, frame2 + num_slice_frames)
        if len(set(inv1).intersection(inv2)) <= pr.max_intersection:
          found = True
          choices.append([frame1, frame2])
          if pr.fix_frame:
            break
      if pr.skip_notfound:
        pass
      else:
        assert found
    print 'Number of frame choices:', len(choices)
    choices = tf.constant(np.array(choices), dtype = tf.int32)
    idx = tf.random_uniform([1], 0, shape(choices, 0), dtype = tf.int64)[0]
    start_frame_gt = choices[idx, 0]
    shift_frame = choices[idx, 1]
  elif ut.hastrue(pr, 'use_first_frame'):
    shift_frame = start_frame_gt = tf.constant(0, dtype = tf.int32)
  else:
    shift_frame = start_frame_gt = tf.random_uniform(
      [1], 0, total_frames - num_slice_frames, dtype = tf.int32)[0]

  if pr.augment_ims:
    print 'Augment:', pr.augment_ims
    r = tf.random_uniform(
      [2], 0, pr.full_im_dim - pr.crop_im_dim, dtype = tf.int32)
    x, y = r[0], r[1]
  else:
    if hasattr(pr, 'resize_dims'):
      y = pr.resize_dims[0]/2 - pr.crop_im_dim/2
      x = pr.resize_dims[1]/2 - pr.crop_im_dim/2
    else:
      y = x = pr.full_im_dim/2 - pr.crop_im_dim/2

  offset = [start_frame_gt, y, x, 0]
  d = pr.crop_im_dim
  size_im = [num_slice_frames, d, d, 3]

  slice_parts = []
  for j in xrange(len(im_parts)):
    num_frames_in_part = total_frames/len(im_parts)

    part_start = j*num_frames_in_part
    frame_offset = tf.maximum(0, tf.minimum(start_frame_gt - part_start, num_frames_in_part))
    end_offset = tf.maximum(0, tf.minimum(start_frame_gt + num_slice_frames - part_start, num_frames_in_part))
    num_frames_in_part_slice = tf.maximum(0, end_offset - frame_offset)

    offset = [frame_offset, y, x, 0]
    d = pr.crop_im_dim

    size_im = [num_frames_in_part_slice, d, d, 3]
    p = tf.slice(im_parts[j], offset, size_im)
    slice_parts.append(p)
  ims_slice = tf.concat(slice_parts, 0)
  ims_slice.set_shape([num_slice_frames, pr.crop_im_dim, pr.crop_im_dim, 3])
  ims = ims_slice

  if pr.augment_ims:
    ims = tf.cond(tf.cast(tf.random_uniform([1], 0, 2, dtype = tf.int64)[0], tf.bool),
                  lambda : tf.map_fn(tf.image.flip_left_right, ims),
                  lambda : ims)

  def slice_samples(frame):
    start = round_int(pr.samples_per_frame * cast_float(frame))
    offset = [start, 0]
    size = [num_samples, 2]
    r = tf.slice(samples, offset, size, name = 'slice_sample')
    r.set_shape([num_samples] + list(shape(r)[1:]))
    return r

  if 'samples' in input_types:
    samples_gt = slice_samples(start_frame_gt)
    samples_shift = slice_samples(shift_frame)
  else:
    samples_gt = samples_shift = tf.zeros((1, 1), dtype = tf.int16)

  samples_exs = tf.concat([ed(samples_shift, 0), ed(samples_gt, 0)], 0)

  return ims, _, samples_exs, _, _, _
</code>```

I also tried loading my own tfrecords by changing this function and I got a similar error. Also, when no tfrecord paths are provided (i.e., train_list=train_tfs.txt does not contain a path to a tfrecord, thus it is impossible to load anything), I get the same error, which indicates that something is wrong with the way the data is being loaded.

Thank you in advance for any help.

How to reproduce the same test

Clone the code in here

Download the data sample in here

Change the parameters in shift_v1 of shift_params.py:
init_path=None and the content of train_tfs.txt (it should
contain the path to the downloaded tf file)

From the folder src, run the following command:

python -c "import shift_params, shift_net; shift_net.train(shift_params.shift_v1(num_gpus=3), [0, 1, 2], restore = False)"

Environment details

I am using the following packages in an anaconda environment (Linux):

Python 2.7.18

tensorflow, tensorflow-gpu and tensorflow-base 1.9.0

numpy, matplotlib, pillow and scipy

答:
I have solved the problem, so I am posting the solution that I have found here in case somebody else faces the same problem.

I have not managed to run the data loading code with the tfrecord provided (as presented in the question), so I created my own data loading function to substitute read_example, which I post here for further reference:

```<code>def new_read_example(rec_queue, pr, input_types):
  reader = tf.TFRecordReader()
  k, serialized_example = reader.read(rec_queue)
  full = pr.full_im_dim # full frame dimension

  feature_description = {
      'video':tf.FixedLenFeature([], tf.string),
      'sync_audio':tf.FixedLenFeature([], tf.string),
      'shift_audio':tf.FixedLenFeature([], tf.string),
      'label':tf.FixedLenFeature([1], tf.int64),
      'num_frames': tf.FixedLenFeature([1], tf.int64)
  }

  # parse one example
  example = tf.parse_single_example(serialized_example, feature_description)

  # get label and other variables
  label = tf.cast(example['label'], tf.int64)

  # I could not transform the total_frames from tensor to an integer
  # so I just assigned 100 to total_frames,
  # which is the number of frames that I use
  # total_frames = tf.cast(example['num_frames'], tf.int64)
  total_frames = 100

  ims = tf.image.decode_jpeg(example['video'], channels=3)
  ims.set_shape((full*total_frames, full, 3))
  ims = tf.reshape(ims, (total_frames, full, full, 3))

  # The audio stored in the tfrecords is an array of floats
  # which is encoded as binary by calling audio.tostring()
  sync_audio = tf.decode_raw(example['sync_audio'], tf.float32)
  shift_audio = tf.decode_raw(example['shift_audio'], tf.float32)

  # The audio that I am reading is mono, so I had to change the
  # dimension of the audio data
  sync_audio.set_shape((pr.full_samples_len))
  sync_audio = tf.reshape(sync_audio, (pr.full_samples_len, 1))

  shift_audio.set_shape((pr.full_samples_len))
  shift_audio = tf.reshape(shift_audio, (pr.full_samples_len, 1))

  samples_exs = tf.concat([ed(shift_audio, 0), ed(sync_audio, 0)], 0)

  return ims, samples_exs
</code>```

The conclusion that I take from here is that it is almost impossible to read a tfrecord without knowing exactly how it was created (the best is to have the code that generated the tfrecords) and, in my case, it was easier to write my own pair of tfrecords writer and reader.

Body:
I am trying to train the model defined here using the function train defined in the same script. I have attempted to use a tf record file provided by the authors in this link (to do that, the only modifications that I made were changing init_path=None and writing the path to the tfrecord file in the txt file train_list=train_tfs.txt, both defined in shift_params.py's shift_v1 ).

However, even trying this simple test, I get the following error:

OutOfRangeError (see above for traceback): RandomShuffleQueue '_1_shuffle_batch_join/random_shuffle_queue' is closed and has insufficient elements (requested 15, current size 0)
         [[Node: shuffle_batch_join = QueueDequeueManyV2[component_types=[DT_UINT8, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_INT64, DT_STRING], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/device:CPU:0"](shuffle_batch_join/random_shuffle_queue, shuffle_batch_join/n)]]

As far as I understand, this error means that no data is being loaded. So my guess is that the problem is in the function read_example in shift_dset.py, as shown below (I have kept only the part of the code that loads the images ims and the audio sound. For the complete code, please check here.)

def read_example(rec_queue, pr, input_types):
  reader = tf.TFRecordReader()
  k, serialized_example = reader.read(rec_queue)
  full = pr.full_im_dim

  feats = {}

  feats['im_0'] = tf.FixedLenFeature([], dtype=tf.string)
  feats['im_1'] = tf.FixedLenFeature([], dtype=tf.string)

  feats['sound'] = tf.FixedLenFeature([], dtype=tf.string)

  if pr.variable_frame_count:
    feats['num_frames'] = tf.FixedLenFeature([1], dtype=tf.int64)
  example = tf.parse_single_example(serialized_example, features = feats)

  total_frames = pr.total_frames if not pr.variable_frame_count \
                 else tf.cast(example['num_frames'][0], tf.int32)

  assert not pr.variable_frame_count

  def f(x):
    x.set_shape((full*total_frames/2, full, 3))
    return tf.reshape(x, (total_frames/2, full, full, 3))
  im_parts = map(f, [tf.image.decode_jpeg(example['im_0'], channels = 3, name = 'decode_im1'),
                     tf.image.decode_jpeg(example['im_1'], channels = 3, name = 'decode_im2')])

  samples = tf.decode_raw(example['sound'], tf.int16)

  samples.set_shape((pr.full_samples_len*2))
  samples = tf.reshape(samples, (pr.full_samples_len, 2))

  samples = tf.cast(samples, 'float32') / np.iinfo(np.dtype(np.int16)).max

  num_slice_frames = pr.sampled_frames
  num_samples = int(pr.samples_per_frame * float(num_slice_frames))

  if pr.do_shift:
    choices = []
    max_frame = total_frames - num_slice_frames
    frames1 = ([0] if pr.fix_frame else xrange(max_frame))
    for frame1 in frames1:
      found = False
      for frame2 in reversed(range(max_frame)):
        inv1 = xrange(frame1, frame1 + num_slice_frames)
        inv2 = xrange(frame2, frame2 + num_slice_frames)
        if len(set(inv1).intersection(inv2)) <= pr.max_intersection:
          found = True
          choices.append([frame1, frame2])
          if pr.fix_frame:
            break
      if pr.skip_notfound:
        pass
      else:
        assert found
    print 'Number of frame choices:', len(choices)
    choices = tf.constant(np.array(choices), dtype = tf.int32)
    idx = tf.random_uniform([1], 0, shape(choices, 0), dtype = tf.int64)[0]
    start_frame_gt = choices[idx, 0]
    shift_frame = choices[idx, 1]
  elif ut.hastrue(pr, 'use_first_frame'):
    shift_frame = start_frame_gt = tf.constant(0, dtype = tf.int32)
  else:
    shift_frame = start_frame_gt = tf.random_uniform(
      [1], 0, total_frames - num_slice_frames, dtype = tf.int32)[0]

  if pr.augment_ims:
    print 'Augment:', pr.augment_ims
    r = tf.random_uniform(
      [2], 0, pr.full_im_dim - pr.crop_im_dim, dtype = tf.int32)
    x, y = r[0], r[1]
  else:
    if hasattr(pr, 'resize_dims'):
      y = pr.resize_dims[0]/2 - pr.crop_im_dim/2
      x = pr.resize_dims[1]/2 - pr.crop_im_dim/2
    else:
      y = x = pr.full_im_dim/2 - pr.crop_im_dim/2

  offset = [start_frame_gt, y, x, 0]
  d = pr.crop_im_dim
  size_im = [num_slice_frames, d, d, 3]

  slice_parts = []
  for j in xrange(len(im_parts)):
    num_frames_in_part = total_frames/len(im_parts)

    part_start = j*num_frames_in_part
    frame_offset = tf.maximum(0, tf.minimum(start_frame_gt - part_start, num_frames_in_part))
    end_offset = tf.maximum(0, tf.minimum(start_frame_gt + num_slice_frames - part_start, num_frames_in_part))
    num_frames_in_part_slice = tf.maximum(0, end_offset - frame_offset)

    offset = [frame_offset, y, x, 0]
    d = pr.crop_im_dim

    size_im = [num_frames_in_part_slice, d, d, 3]
    p = tf.slice(im_parts[j], offset, size_im)
    slice_parts.append(p)
  ims_slice = tf.concat(slice_parts, 0)
  ims_slice.set_shape([num_slice_frames, pr.crop_im_dim, pr.crop_im_dim, 3])
  ims = ims_slice

  if pr.augment_ims:
    ims = tf.cond(tf.cast(tf.random_uniform([1], 0, 2, dtype = tf.int64)[0], tf.bool),
                  lambda : tf.map_fn(tf.image.flip_left_right, ims),
                  lambda : ims)

  def slice_samples(frame):
    start = round_int(pr.samples_per_frame * cast_float(frame))
    offset = [start, 0]
    size = [num_samples, 2]
    r = tf.slice(samples, offset, size, name = 'slice_sample')
    r.set_shape([num_samples] + list(shape(r)[1:]))
    return r

  if 'samples' in input_types:
    samples_gt = slice_samples(start_frame_gt)
    samples_shift = slice_samples(shift_frame)
  else:
    samples_gt = samples_shift = tf.zeros((1, 1), dtype = tf.int16)

  samples_exs = tf.concat([ed(samples_shift, 0), ed(samples_gt, 0)], 0)

  return ims, _, samples_exs, _, _, _

I also tried loading my own tfrecords by changing this function and I got a similar error. Also, when no tfrecord paths are provided (i.e., train_list=train_tfs.txt does not contain a path to a tfrecord, thus it is impossible to load anything), I get the same error, which indicates that something is wrong with the way the data is being loaded.

Thank you in advance for any help.

How to reproduce the same test

Clone the code in here

Download the data sample in here

Change the parameters in shift_v1 of shift_params.py:
init_path=None and the content of train_tfs.txt (it should
contain the path to the downloaded tf file)

From the folder src, run the following command:

python -c "import shift_params, shift_net; shift_net.train(shift_params.shift_v1(num_gpus=3), [0, 1, 2], restore = False)"

Environment details

I am using the following packages in an anaconda environment (Linux):

Python 2.7.18

tensorflow, tensorflow-gpu and tensorflow-base 1.9.0

numpy, matplotlib, pillow and scipy

Body:
I have solved the problem, so I am posting the solution that I have found here in case somebody else faces the same problem.

I have not managed to run the data loading code with the tfrecord provided (as presented in the question), so I created my own data loading function to substitute read_example, which I post here for further reference:

def new_read_example(rec_queue, pr, input_types):
  reader = tf.TFRecordReader()
  k, serialized_example = reader.read(rec_queue)
  full = pr.full_im_dim # full frame dimension

  feature_description = {
      'video':tf.FixedLenFeature([], tf.string),
      'sync_audio':tf.FixedLenFeature([], tf.string),
      'shift_audio':tf.FixedLenFeature([], tf.string),
      'label':tf.FixedLenFeature([1], tf.int64),
      'num_frames': tf.FixedLenFeature([1], tf.int64)
  }

  # parse one example
  example = tf.parse_single_example(serialized_example, feature_description)

  # get label and other variables
  label = tf.cast(example['label'], tf.int64)

  # I could not transform the total_frames from tensor to an integer
  # so I just assigned 100 to total_frames,
  # which is the number of frames that I use
  # total_frames = tf.cast(example['num_frames'], tf.int64)
  total_frames = 100

  ims = tf.image.decode_jpeg(example['video'], channels=3)
  ims.set_shape((full*total_frames, full, 3))
  ims = tf.reshape(ims, (total_frames, full, full, 3))

  # The audio stored in the tfrecords is an array of floats
  # which is encoded as binary by calling audio.tostring()
  sync_audio = tf.decode_raw(example['sync_audio'], tf.float32)
  shift_audio = tf.decode_raw(example['shift_audio'], tf.float32)

  # The audio that I am reading is mono, so I had to change the
  # dimension of the audio data
  sync_audio.set_shape((pr.full_samples_len))
  sync_audio = tf.reshape(sync_audio, (pr.full_samples_len, 1))

  shift_audio.set_shape((pr.full_samples_len))
  shift_audio = tf.reshape(shift_audio, (pr.full_samples_len, 1))

  samples_exs = tf.concat([ed(shift_audio, 0), ed(sync_audio, 0)], 0)

  return ims, samples_exs

The conclusion that I take from here is that it is almost impossible to read a tfrecord without knowing exactly how it was created (the best is to have the code that generated the tfrecords) and, in my case, it was easier to write my own pair of tfrecords writer and reader.


问:
how to solve problems with persistence mapDB?
i am doing my project with GWT and Madb. The problem is that MapDb every time it deletes the contents of the db. How can I do to keep the db persistent?</p>

答: Are you sure that your configuration uses file store? If you have something like DBMaker.newMemory...()


问:
Python Prepared Statements. Problems with SELECT IN
I'm having an issue with a prepared statement in Python I can't solve so far.

The Query, which should be execute is e.g.:

```<code> SELECT md5 FROM software WHERE software_id IN (1, 2, 4)
</code>```

So I tried to execute a Query like this:

```<code>software_id_string = "(2, 3, 4)"
cursor.execute("SELECT md5 FROM software WHERE software_id IN %s",
                software_id_string)
</code>```

The Problem is that there are '' added to the string --> '(2, 3, 4)', so that the Query will be:

```<code>SELECT md5 FROM software WHERE software_id IN ''(2, 3, 4)''
</code>```

I've also tried to rebuild the Script like this:

```<code>software_id_string = " 1 OR software_id = 2"
cursor.execute("SELECT md5 FROm software WHERE software_id = %s",
              software_id_string)
</code>```

This works only for the first id, which will be submitted (in this case 1), because the OR-part won't be interpeted as an SQL Statement...

Is there any possibility to fix the issues with the prepared statements?

答:
You want

```<code>cursor.execute("SELECT md5 FROM software WHERE software_id IN %s" % software_id_string)
</code>```

i.e. a % instead of a comma

Body:
I'm having an issue with a prepared statement in Python I can't solve so far.

The Query, which should be execute is e.g.:

 SELECT md5 FROM software WHERE software_id IN (1, 2, 4)

So I tried to execute a Query like this:

software_id_string = "(2, 3, 4)"
cursor.execute("SELECT md5 FROM software WHERE software_id IN %s",
                software_id_string)

The Problem is that there are '' added to the string --> '(2, 3, 4)', so that the Query will be:

SELECT md5 FROM software WHERE software_id IN ''(2, 3, 4)''

I've also tried to rebuild the Script like this:

software_id_string = " 1 OR software_id = 2"
cursor.execute("SELECT md5 FROm software WHERE software_id = %s",
              software_id_string)

This works only for the first id, which will be submitted (in this case 1), because the OR-part won't be interpeted as an SQL Statement...

Is there any possibility to fix the issues with the prepared statements?

Body:
You want

cursor.execute("SELECT md5 FROM software WHERE software_id IN %s" % software_id_string)

i.e. a % instead of a comma


问:
MongoDB cannot start server: The default storage engine 'wiredTiger' is not available with this build of mongod
MongoDB server failing to start with the following error:

2015-12-13T00:49:12.191+0600 I CONTROL  [initandlisten] options: {}

  2015-12-13T00:49:12.195+0600 I STORAGE  [initandlisten] exception in

initAndListen: 28663 Cannot start server. The default storage engine
  'wiredTiger' is not available with this build of mongod. Please
  specify a different storage engine explicitly, e.g.
  --storageEngine=mmapv1., terminating
        2015-12-13T00:49:12.195+0600 I CONTROL  [initandlisten] dbexit:  rc: 100

答:
I created a directory in C drive -

```<code>C:\data\db
</code>```

and ran the command as below, it worked for me.

```<code>C:\Users\USERNAME\mongodb-win32-i386-3.2.22\bin>mongod.exe --storageEngine=mmapv1
</code>```

Body:
I created a directory in C drive -

C:\data\db

and ran the command as below, it worked for me.

C:\Users\USERNAME\mongodb-win32-i386-3.2.22\bin>mongod.exe --storageEngine=mmapv1


问:
A* with reopening when heuristics is only admissible but not consistent
The A* pseudocode I follow is given here:

My question is: How are we sure that we can return when a goal state is found? As it is with all other CLOSED states, they could be reopened from new OPEN states. So, if I have a state that I got from OPEN and I see that I can take a better path to the CLOSED goal from that state, then I should update its value at least. Shouldn't we wait till all the states are closed?

答:
After reading dennis' answer, I would like to make a brief addition from my own understanding.

Let's imagine that there is another node in open_list, f(another) >= f(n).
because f(n)=g(n)+h(n), n is goal node, so h(n) = 0, then f(another) >= g(n);

Then, let's recall admissible heuristic principle as below:

Heuristics are still admissible, meaning that the heuristic cost h(n) of a node n must always be less than or equal to the true (unknown) remaining cost h*(n): h(n) <= h*(n) for all n

Next, Let's imagine that there is path connecting anothernode and goal n' node,
then f(another->n') = g(another->n') + h(n'), and h(n') = 0, so f(another->n') = g(another->n'). No doubt g(another->n') > g(another), because of positive path cost.

so we have:

```<code>condition:
1. g(another) + h(another) = f(another) >= f(n) = g(n);
2. f(another->n') = g(another->n') > g(another)
*important:  [admissible]
3. h(another) <= h*(another) = g(another->n') - g(another)

=>

conlusion:
f(another->n') >= f(another) >= f(n)
</code>```

Therefore, the node n have already the min f.
In fact, my above derivation is proof that admissible heuristic guarantees optimal. more info ref to: Admissible heuristic - Wikipedia

I hope I've made the issue clear for you.

Body:
After reading dennis' answer, I would like to make a brief addition from my own understanding.

Let's imagine that there is another node in open_list, f(another) >= f(n).
because f(n)=g(n)+h(n), n is goal node, so h(n) = 0, then f(another) >= g(n);

Then, let's recall admissible heuristic principle as below:

Heuristics are still admissible, meaning that the heuristic cost h(n) of a node n must always be less than or equal to the true (unknown) remaining cost h*(n): h(n) <= h*(n) for all n

Next, Let's imagine that there is path connecting anothernode and goal n' node,
then f(another->n') = g(another->n') + h(n'), and h(n') = 0, so f(another->n') = g(another->n'). No doubt g(another->n') > g(another), because of positive path cost.

so we have:

condition:
1. g(another) + h(another) = f(another) >= f(n) = g(n);
2. f(another->n') = g(another->n') > g(another)
*important:  [admissible]
3. h(another) <= h*(another) = g(another->n') - g(another)

=>

conlusion:
f(another->n') >= f(another) >= f(n)

Therefore, the node n have already the min f.
In fact, my above derivation is proof that admissible heuristic guarantees optimal. more info ref to: Admissible heuristic - Wikipedia

I hope I've made the issue clear for you.


问:
Swing thread safety boilerplate
For the sake of simplicity, imagine an application that downloads a file. There is a simple GUI with one label that displays progress. To avoid EDT violations, like every lawful citizen I download the file in one thread (main), and update GUI in another (EDT). So, here's the relevant chunk of pseudcode:

```<code>class Downloader {
    download() {
        progress.startDownload();
        while(hasMoreChunks()) {
            downloadChunk();
            progress.downloadedBytes(n);
        }
        progress.finishDownload();
    }
}

class ProgressDisplay extends JPanel {
    JLabel label;
    startDownload() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                label.setText("Download started");
            }
        });
    }
    downloadedBytes(int n) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                label.setText("Downloaded bytes: " + n);
            }
        });
    }
    finishDownload() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                label.setText("Download finished");
            }
        });
    }
}
</code>```

I love the fact that Java does not support closures and the code is crystal clear to me. Jokes aside, I'm wondering... Am I doing it wrong? Is it possible to eliminate all this ugly boilerplate with SwingUtilities, anonymous implementation of Runnable in every method etc.?

My case is slightly more complicated than this, but I'm trying not to overengineer by implementing proxies or something like that.

答:
There is not much you can do to avoid the boilerplate code without introducing a lot of redundant code elsewhere. But you can make it a little bit nicer with a small abstract helper class and some unusual formatting.

```<code>public abstract static class SwingTask implements Runnable
{
    public void start()
    {
         SwingUtilities.invokeLater( this );
    }
}

startDownload() {
    new SwingTask() { public void run() {
        label.setText("Download started");
    } }.start();
}
</code>```

The code formatting is meant to emphasize that all the code in this single line is basically uninteresting boilerplate code that can easily and safely be copied to other places where it is needed. We have been using this formatting style now for a while and it turned out quite useful.

Title: Swing thread safety boilerplate

Body:
For the sake of simplicity, imagine an application that downloads a file. There is a simple GUI with one label that displays progress. To avoid EDT violations, like every lawful citizen I download the file in one thread (main), and update GUI in another (EDT). So, here's the relevant chunk of pseudcode:

class Downloader {
    download() {
        progress.startDownload();
        while(hasMoreChunks()) {
            downloadChunk();
            progress.downloadedBytes(n);
        }
        progress.finishDownload();
    }
}

class ProgressDisplay extends JPanel {
    JLabel label;
    startDownload() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                label.setText("Download started");
            }
        });
    }
    downloadedBytes(int n) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                label.setText("Downloaded bytes: " + n);
            }
        });
    }
    finishDownload() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                label.setText("Download finished");
            }
        });
    }
}

I love the fact that Java does not support closures and the code is crystal clear to me. Jokes aside, I'm wondering... Am I doing it wrong? Is it possible to eliminate all this ugly boilerplate with SwingUtilities, anonymous implementation of Runnable in every method etc.?

My case is slightly more complicated than this, but I'm trying not to overengineer by implementing proxies or something like that.

Body:
There is not much you can do to avoid the boilerplate code without introducing a lot of redundant code elsewhere. But you can make it a little bit nicer with a small abstract helper class and some unusual formatting.

public abstract static class SwingTask implements Runnable
{
    public void start()
    {
         SwingUtilities.invokeLater( this );
    }
}

startDownload() {
    new SwingTask() { public void run() {
        label.setText("Download started");
    } }.start();
}

The code formatting is meant to emphasize that all the code in this single line is basically uninteresting boilerplate code that can easily and safely be copied to other places where it is needed. We have been using this formatting style now for a while and it turned out quite useful.


问:
Seed database AspNetUserRoles table in ASP.NET Core 3.1 MVC
I'm beginner and i work on a Asp.Net Core 3 MVC. I'm try to seed AspNetUserRoles table. User and role work correctly and seeded without errors, but AspNetUserRoles table null. I created seed class like this:

```<code>public class SeedData
    {
        private AppIdentityDbContext _context;

        public SeedData(AppIdentityDbContext context)
        {
            _context = context;
        }
        public async void Initialize()
        {
            var user = new ApplicationUser
            {
                UserName = "progmd@mail.ru",
                NormalizedUserName = "progmd@mail.ru",
                Email = "progmd@mail.ru",
                NormalizedEmail = "progmd@mail.ru",
                City = "SuperAdmin",
                EmailConfirmed = true,
                LockoutEnabled = false,
                SecurityStamp = Guid.NewGuid().ToString()
            };

            var roleStore = new RoleStore<IdentityRole>(_context);

            if (!_context.Roles.Any(r => r.Name == "admin"))
            {
                await roleStore.CreateAsync(new IdentityRole { Id = "b562e963-6e7e-4f42-9339-1235b1234qw5", Name = "admin", NormalizedName = "admin" });
            }

            if (!_context.Users.Any(u => u.UserName == user.UserName))
            {
                var password = new PasswordHasher<ApplicationUser>();
                var hashed = password.HashPassword(user, "111111Test");
                user.PasswordHash = hashed;

                var userStore = new UserStore<ApplicationUser>(_context);
                await userStore.CreateAsync(user);
                await userStore.AddToRoleAsync(user, "admin");
            }

            IdentityUserRole<string> ur = new IdentityUserRole<string>();
            ur.RoleId = "b562e963-6e7e-4f42-9339-1235b1234qw5";
            ur.UserId = user.Id;

            //await _context.UserRoles.AddAsync(ur);
            await _context.SaveChangesAsync();
        }
    }
</code>```

How can i fix this?

答:
Ok, i found another way. I'm removed class SeedData, and added this code in AppIdentityDbContext.cs

```<code>protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            builder.Entity<IdentityRole>().HasData(new List<IdentityRole>
            {
                new IdentityRole
                {
                    Id = "1",
                    Name = "admin",
                    NormalizedName = "ADMIN"
                }
            });

            var hasher = new PasswordHasher<ApplicationUser>();
            builder.Entity<ApplicationUser>().HasData(new ApplicationUser
            {
                Id = "1",
                UserName = "progmd@mail.ru",
                NormalizedUserName = "progmd@mail.ru",
                Email = "progmd@mail.ru",
                NormalizedEmail = "progmd@mail.ru",
                City = "SuperAdmin",
                EmailConfirmed = true,
                LockoutEnabled = false,
                PasswordHash = hasher.HashPassword(null, "111111Test"),
            });

            builder.Entity<IdentityUserRole<string>>().HasData(new IdentityUserRole<string>
            {
                RoleId = "1",
                UserId = "1"
            });
}
</code>```

Remember to add the migration and update the database.

PS Thx for Mark Deanil Vicente!

Body:
I'm beginner and i work on a Asp.Net Core 3 MVC. I'm try to seed AspNetUserRoles table. User and role work correctly and seeded without errors, but AspNetUserRoles table null. I created seed class like this:

public class SeedData
    {
        private AppIdentityDbContext _context;

        public SeedData(AppIdentityDbContext context)
        {
            _context = context;
        }
        public async void Initialize()
        {
            var user = new ApplicationUser
            {
                UserName = "progmd@mail.ru",
                NormalizedUserName = "progmd@mail.ru",
                Email = "progmd@mail.ru",
                NormalizedEmail = "progmd@mail.ru",
                City = "SuperAdmin",
                EmailConfirmed = true,
                LockoutEnabled = false,
                SecurityStamp = Guid.NewGuid().ToString()
            };

            var roleStore = new RoleStore<IdentityRole>(_context);

            if (!_context.Roles.Any(r => r.Name == "admin"))
            {
                await roleStore.CreateAsync(new IdentityRole { Id = "b562e963-6e7e-4f42-9339-1235b1234qw5", Name = "admin", NormalizedName = "admin" });
            }

            if (!_context.Users.Any(u => u.UserName == user.UserName))
            {
                var password = new PasswordHasher<ApplicationUser>();
                var hashed = password.HashPassword(user, "111111Test");
                user.PasswordHash = hashed;

                var userStore = new UserStore<ApplicationUser>(_context);
                await userStore.CreateAsync(user);
                await userStore.AddToRoleAsync(user, "admin");
            }

            IdentityUserRole<string> ur = new IdentityUserRole<string>();
            ur.RoleId = "b562e963-6e7e-4f42-9339-1235b1234qw5";
            ur.UserId = user.Id;

            //await _context.UserRoles.AddAsync(ur);
            await _context.SaveChangesAsync();
        }
    }

How can i fix this?

Body:
Ok, i found another way. I'm removed class SeedData, and added this code in AppIdentityDbContext.cs

protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            builder.Entity<IdentityRole>().HasData(new List<IdentityRole>
            {
                new IdentityRole
                {
                    Id = "1",
                    Name = "admin",
                    NormalizedName = "ADMIN"
                }
            });

            var hasher = new PasswordHasher<ApplicationUser>();
            builder.Entity<ApplicationUser>().HasData(new ApplicationUser
            {
                Id = "1",
                UserName = "progmd@mail.ru",
                NormalizedUserName = "progmd@mail.ru",
                Email = "progmd@mail.ru",
                NormalizedEmail = "progmd@mail.ru",
                City = "SuperAdmin",
                EmailConfirmed = true,
                LockoutEnabled = false,
                PasswordHash = hasher.HashPassword(null, "111111Test"),
            });

            builder.Entity<IdentityUserRole<string>>().HasData(new IdentityUserRole<string>
            {
                RoleId = "1",
                UserId = "1"
            });
}

Remember to add the migration and update the database.

PS Thx for Mark Deanil Vicente!


问:
React + Redux state deleted on page refresh
I currently have a component that pulls a deck of cards from the backend and tries to create a chart out of values from those cards. On first load, everything works and the chart populates. On refresh, however, it seems that the decks prop is undefined (although redux devtools shows it's still present).

UseEffect:

```<code>useEffect(() => {
  getDecks();                      // sets "decks"
  populateData();
}, []);
</code>```

```<code>  const populateData = () => {
    var data = [0, 0, 0, 0, 0];
    cardArray = decks[0].cards;                // crashes here on reload; decks is undef.

    ...
    createChart(data);
  };
</code>```

```<code>export const getDecks = () => async (dispatch) => {
  try {
    const res = await axios.get("/api/decks");
    dispatch({
      type: GET_DECKS,
      payload: res.data,
    });
  } catch (err) {
    dispatch({
      type: DECK_ERROR,
      payload: { msg: err.response.statusText, status: err.response.status },
    });
  }
};
</code>```

Initial state in deck reducer:

```<code>const initialState = {
  decks: [],
  currentCard: 0,
  loading: true,
  error: {},
  isFlipped: false,
};
</code>```

I've looked at similar posts that suggest that I store decks in localstorage, but I have other components that call getDecks display data from them similar to this one without any issues. Does anybody have any tips or possible reasons why this might be doing this? Thanks.

答: Found the issue. It's common apparently for redux stores to disappear on refresh, so wrapping your app in a persistent store (such as redux-persist) automatically fixes the problem for me. Thanks for everyone's suggestions.</p>

Body:
I currently have a component that pulls a deck of cards from the backend and tries to create a chart out of values from those cards. On first load, everything works and the chart populates. On refresh, however, it seems that the decks prop is undefined (although redux devtools shows it's still present).

UseEffect:

useEffect(() => {
  getDecks();                      // sets "decks"
  populateData();
}, []);

  const populateData = () => {
    var data = [0, 0, 0, 0, 0];
    cardArray = decks[0].cards;                // crashes here on reload; decks is undef.

    ...
    createChart(data);
  };

export const getDecks = () => async (dispatch) => {
  try {
    const res = await axios.get("/api/decks");
    dispatch({
      type: GET_DECKS,
      payload: res.data,
    });
  } catch (err) {
    dispatch({
      type: DECK_ERROR,
      payload: { msg: err.response.statusText, status: err.response.status },
    });
  }
};

Initial state in deck reducer:

const initialState = {
  decks: [],
  currentCard: 0,
  loading: true,
  error: {},
  isFlipped: false,
};

I've looked at similar posts that suggest that I store decks in localstorage, but I have other components that call getDecks display data from them similar to this one without any issues. Does anybody have any tips or possible reasons why this might be doing this? Thanks.


问:
I am new to python i tried to run this fancy decorators code
```<code>class Square:
    def _init_(self,side):
        self._side = side
    @property
    def side(self):
        return self._side
    @side.setter
    def side(self,value):
        if value >= 0:
            self._side = value
        else:
            print("error")
    @property
    def area(self):
        return self._side **2
    @classmethod
    def unit_square(cls):
        return cls(1)
s = Square(5)
print(s.side)
print(s.area)
</code>```

but i am getting error ( s = Square(5) TypeError: Square() takes no arguments) i am not able to figure it out

答:
The init method should have double underscores(__). Change the method to __init__

```<code>def __init__(self, side):
    self._side = side
</code>```

Reference: https://dbader.org/blog/python-dunder-methods

Body:
class Square:
    def _init_(self,side):
        self._side = side
    @property
    def side(self):
        return self._side
    @side.setter
    def side(self,value):
        if value >= 0:
            self._side = value
        else:
            print("error")
    @property
    def area(self):
        return self._side **2
    @classmethod
    def unit_square(cls):
        return cls(1)
s = Square(5)
print(s.side)
print(s.area)

but i am getting error ( s = Square(5) TypeError: Square() takes no arguments) i am not able to figure it out

Body:
The init method should have double underscores(__). Change the method to __init__

def __init__(self, side):
    self._side = side

Reference: https://dbader.org/blog/python-dunder-methods


问:
.htacess adding pagination to the a file S_NSW.php
currently in the directory example.com.au/directory1/nsw/ I have below .htaccess

```<code>   RewriteEngine On
       RewriteRule ^([a-zA-Z0-9_-]+)$ S_NSW.php?p=$1
       RewriteRule ^([a-zA-Z0-9_-]+)/$ S_NSW.php?p=$1
</code>```

the filename is S_NSW.php
current .htaccess is

In order to make the url look like

```<code>example.com.au/directory1/suburb-nsw
</code>```

the above code works, however I need extra by adding pagination and make the url look like

example.com.au/directory1/suburb-nsw/1/

example.com.au/directory1/suburb-nsw/2/

example.com.au/directory1/suburb-nsw/3/

答:
Resolved, too easy.
by adding the following line into the root .htaccss file:

```<code>RewriteRule ^([^/]+)/([^/]+)-([^/]+)/([^/]+)/?$ /$1/$3/S_NSW.php?p=$2&pi=$4 [L,NC,QSA,NE]
</code>```

also by adding the following code into example.com.au/directory1/suburb-nsw

```<code>RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ S_NSW.php?p=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ S_NSW.php?p=$1
RewriteRule ^([a-zA-Z0-9_-]+)/([0-9]+)/$ S_NSW.php?p=$1&pi=$2 [NC,L]
RewriteRule ^nsw/([a-zA-Z0-9_-]+)/([0-9]+)/$ S_NSW.php?p=$1&pi=$2 [NC,L]
RewriteRule ^([a-zA-Z0-9_-]+)-^nsw/([0-9]+)/$ S_NSW.php?p=$1&pi=$2 [NC,L]
</code>```

Body:
currently in the directory example.com.au/directory1/nsw/ I have below .htaccess

   RewriteEngine On
       RewriteRule ^([a-zA-Z0-9_-]+)$ S_NSW.php?p=$1
       RewriteRule ^([a-zA-Z0-9_-]+)/$ S_NSW.php?p=$1

the filename is S_NSW.php
current .htaccess is

In order to make the url look like

example.com.au/directory1/suburb-nsw

the above code works, however I need extra by adding pagination and make the url look like

example.com.au/directory1/suburb-nsw/1/

example.com.au/directory1/suburb-nsw/2/

example.com.au/directory1/suburb-nsw/3/

Body:
Resolved, too easy.
by adding the following line into the root .htaccss file:

RewriteRule ^([^/]+)/([^/]+)-([^/]+)/([^/]+)/?$ /$1/$3/S_NSW.php?p=$2&pi=$4 [L,NC,QSA,NE]

also by adding the following code into example.com.au/directory1/suburb-nsw

RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ S_NSW.php?p=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ S_NSW.php?p=$1
RewriteRule ^([a-zA-Z0-9_-]+)/([0-9]+)/$ S_NSW.php?p=$1&pi=$2 [NC,L]
RewriteRule ^nsw/([a-zA-Z0-9_-]+)/([0-9]+)/$ S_NSW.php?p=$1&pi=$2 [NC,L]
RewriteRule ^([a-zA-Z0-9_-]+)-^nsw/([0-9]+)/$ S_NSW.php?p=$1&pi=$2 [NC,L]


问:
Use X509Certificate2 with Windows certificate store, HSM, and Azure Key Vault
I have many methods like the below which uses X509Certificate2.PrivateKey

```<code>    public SomeValue DoSomething(X509Certificate2 cert)
    {
        // do something that needs the cert.PrivateKey
    }
</code>```

They are working well so far with certificates that are stored in the Windows certificate store whose private keys are accessible. Problem now is that I need to support certificates stored in HSM devices and Azure Key Vault HSM where the private keys can't be loaded into memory (and thus the PrivateKey property is null).

I'm looking for a way to avoid changing signatures of my public methods. If the PrivateKey property is virtual, I would be easily make sub classes and return appropriate AsymmetricAlgorithm implementation for each store type (to be clear, for example in Azure Key Vault HSM, the AsymmetricAlgorithm will be an implementation that calls Azure Key Vault to do signing). Btw, the setter of the PrivateKey property doesn't allow me to set my custom AsymmetricAlgorithm.

Another problem is that the PrivateKey property is out of favor now and the GetRSAPrivateKey extension method is recommended.

Is there any trick that I can use to let an X509Certificate2.PrivateKey or the GetRSAPrivateKey extension method returns an AsymmetricAlgorithm of a type that I want?

答: When using KV, RSA Private Keys don't leave KV, when you get a 'key' back from KV, you really get a key ID, not the key. You will need to export the cert as a PFX file.   </p>

Body:
I have many methods like the below which uses X509Certificate2.PrivateKey

    public SomeValue DoSomething(X509Certificate2 cert)
    {
        // do something that needs the cert.PrivateKey
    }

They are working well so far with certificates that are stored in the Windows certificate store whose private keys are accessible. Problem now is that I need to support certificates stored in HSM devices and Azure Key Vault HSM where the private keys can't be loaded into memory (and thus the PrivateKey property is null).

I'm looking for a way to avoid changing signatures of my public methods. If the PrivateKey property is virtual, I would be easily make sub classes and return appropriate AsymmetricAlgorithm implementation for each store type (to be clear, for example in Azure Key Vault HSM, the AsymmetricAlgorithm will be an implementation that calls Azure Key Vault to do signing). Btw, the setter of the PrivateKey property doesn't allow me to set my custom AsymmetricAlgorithm.

Another problem is that the PrivateKey property is out of favor now and the GetRSAPrivateKey extension method is recommended.

Is there any trick that I can use to let an X509Certificate2.PrivateKey or the GetRSAPrivateKey extension method returns an AsymmetricAlgorithm of a type that I want?


问:
Github: Configure username
In Github, when someone in the team push some changes, we can see his/her username with a link to their Github account, like the green one here:

In my case (red) it is just the text of my username.

I configured the user name and email with:

```<code>git config user.name "pmirandaarias"
git config user.email "myemail@example.com"
</code>```

What should I do?

答:
Its a simple 3 steps approach/

Step-1:

Clone your Work repository and Private repository to your laptop/desktop.
We will use different username and email for each repository.

Step-2:

Go to repository

Click on hidden folder .git

Open config file

Step-3:
Add [user] tag with username and email info. Here is a sample.

```<code>[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    ignorecase = true
    precomposeunicode = true
[remote "origin"]
    url = https://github.com/bla/bla/bla/bla
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
[user]
    name = YourName, LLC
    email = email [at] site.com
</code>```

Using command line also you could to change the file.

Open macOS Terminal.

Change the current working directory to the local repository

This is a repository where you want to configure the name that is
associated with your Git commits.

Execute command: git config user.email "email [at] site.com"

Execute command: git config user.name "YourName, LLC"

Title: Github: Configure username

Body:
In Github, when someone in the team push some changes, we can see his/her username with a link to their Github account, like the green one here:

In my case (red) it is just the text of my username.

I configured the user name and email with:

git config user.name "pmirandaarias"
git config user.email "myemail@example.com"

What should I do?

Body:
Its a simple 3 steps approach/

Step-1:

Clone your Work repository and Private repository to your laptop/desktop.
We will use different username and email for each repository.

Step-2:

Go to repository

Click on hidden folder .git

Open config file

Step-3:
Add [user] tag with username and email info. Here is a sample.

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    ignorecase = true
    precomposeunicode = true
[remote "origin"]
    url = https://github.com/bla/bla/bla/bla
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
[user]
    name = YourName, LLC
    email = email [at] site.com

Using command line also you could to change the file.

Open macOS Terminal.

Change the current working directory to the local repository

This is a repository where you want to configure the name that is
associated with your Git commits.

Execute command: git config user.email "email [at] site.com"

Execute command: git config user.name "YourName, LLC"


问:
JavaScript: Use variable (argument) as property
I'm making a function that will count through data food amount.

```<code>const countFood = (foodType) => {
  let foodNeeded = 0;

  if (animal.food.type === foodType) {
    foodNeeded += +animal.food.amount;
  };

  const food = foodType;

  if (foodNeeded > (pavilion.food[food] - 1)) return true;

  countFood(foodType);
}

countFood('meat');
</code>```

It's a piece of code in for loop.

I need use this argument to request it like pavilion.food.meat

答:
You can access an object property using the bracket notation.

Example:

const pavillon = {
  food: {
    meat: 3
  }
}

function getFood(foodType) {
  const food = pavillon.food[foodType]

  console.log(food)

  return food
}

getFood('meat');```

Body:
I'm making a function that will count through data food amount.

const countFood = (foodType) => {
  let foodNeeded = 0;

  if (animal.food.type === foodType) {
    foodNeeded += +animal.food.amount;
  };

  const food = foodType;

  if (foodNeeded > (pavilion.food[food] - 1)) return true;

  countFood(foodType);
}

countFood('meat');

It's a piece of code in for loop.

I need use this argument to request it like pavilion.food.meat


问:
Multiple condition on same column inside Linq where
How can I write a linq query to match two condition on same column in the table?

Here one person can be assigned to multiple types of works and it is store in PersonWorkTypes table containing the details of persons and their worktypes.

So I need to get the list of persons who have both fulltime and freelance works.

I have tried

```<code>people.where(w => w.worktype == "freelance" && w.worktype == "fulltime")
</code>```

But it returns an empty result.

答:
```<code>w.worktype=="freelance"
w.worktype=="fulltime"
</code>```

These are mutually exclusive to each other, and therefore cannot both be true to ever satisfy your AND(&&) operator.

I am inferring that you have two (or more) different rows in your table per person, one for each type of work they do. If so, the Where() method is going to check your list line-by-line individually and won't be able to check two different elements of a list to see if Alice (for example) both has en entry for "freelance" and an entry for "fulltime" as two different elements in the list. Unfortuantely, I can't think of an easy way to do this in a single query, but something like this might work:

```<code>var fulltimeWorkers = people.Where(w=>w.worktype=="fulltime");
var freelanceWorkers = people.Where(w=>w.worktype=="freelance");
List<Person> peopleWhoDoBoth = new List<Person>();
foreach (var worker in fulltimeWorkers)
{
   if (freelanceWorkers.Contains(worker)
      peopleWhoDoBoth.Add(worker);
}
</code>```

This is probably not the most efficient way possible of doing it, but for small data sets, it shouldn't matter.

Body:
How can I write a linq query to match two condition on same column in the table?

Here one person can be assigned to multiple types of works and it is store in PersonWorkTypes table containing the details of persons and their worktypes.

So I need to get the list of persons who have both fulltime and freelance works.

I have tried

people.where(w => w.worktype == "freelance" && w.worktype == "fulltime")

But it returns an empty result.

Body:
w.worktype=="freelance"
w.worktype=="fulltime"

These are mutually exclusive to each other, and therefore cannot both be true to ever satisfy your AND(&&) operator.

I am inferring that you have two (or more) different rows in your table per person, one for each type of work they do. If so, the Where() method is going to check your list line-by-line individually and won't be able to check two different elements of a list to see if Alice (for example) both has en entry for "freelance" and an entry for "fulltime" as two different elements in the list. Unfortuantely, I can't think of an easy way to do this in a single query, but something like this might work:

var fulltimeWorkers = people.Where(w=>w.worktype=="fulltime");
var freelanceWorkers = people.Where(w=>w.worktype=="freelance");
List<Person> peopleWhoDoBoth = new List<Person>();
foreach (var worker in fulltimeWorkers)
{
   if (freelanceWorkers.Contains(worker)
      peopleWhoDoBoth.Add(worker);
}

This is probably not the most efficient way possible of doing it, but for small data sets, it shouldn't matter.


问:
Floating point of fixed point division using Shift Operator in Verilog HDL
I want to ask if it is possible to divide the floating-point or fixed number using the shift operators. I want to divide the floating-point or fixed number in the power of 2? I know for decimal numbers we can use shift operators in Verilog HDL for division and multiplication.</p>

答:
If you really want to divide (bit-shift) a float number, you could use a method called fixed-point.

Say you will (say) hold the number 1.45 (and bit-shift it later). You would store 145 in an integer, and every time you accessed the variable you would divide the value by 2 using shift right operation.


问:
Swift - Get file size from url
i am using documentPicker to get url path of any document and then uploaded to the database. I am choosing file (pdf, txt ..) , the upload is working but i want to limit the size of the file .

```<code> public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {

        self.file = url //url
        self.path = String(describing: self.file!) // url to string
        self.upload = true //set upload to true
        self.attachBtn.setImage(UIImage(named: "attachFilled"), for: .normal)//set image
        self.attachBtn.tintColor = UIColor.black //set color tint
        sendbtn.tintColor = UIColor.white //

        do
        {
            let fileDictionary = try FileManager.default.attributesOfItem(atPath: self.path!)
            let fileSize = fileDictionary[FileAttributeKey.size]
            print ("\(fileSize)")
        }
        catch{
            print("Error: \(error)")
        }

    }
</code>```

I get the error message , this file does not exist , where does the document picker save the file and how to get his attributes.

答:
```<code>extension URL {
    func fileSize() -> Double {
        var fileSize: Double = 0.0
        var fileSizeValue = 0.0
        try? fileSizeValue = (self.resourceValues(forKeys: [URLResourceKey.fileSizeKey]).allValues.first?.value as! Double?)!
        if fileSizeValue > 0.0 {
            fileSize = (Double(fileSizeValue) / (1024 * 1024))
        }
        return fileSize
    }
}
</code>```

Title: Swift - Get file size from url

Body:
i am using documentPicker to get url path of any document and then uploaded to the database. I am choosing file (pdf, txt ..) , the upload is working but i want to limit the size of the file .

 public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {

        self.file = url //url
        self.path = String(describing: self.file!) // url to string
        self.upload = true //set upload to true
        self.attachBtn.setImage(UIImage(named: "attachFilled"), for: .normal)//set image
        self.attachBtn.tintColor = UIColor.black //set color tint
        sendbtn.tintColor = UIColor.white //

        do
        {
            let fileDictionary = try FileManager.default.attributesOfItem(atPath: self.path!)
            let fileSize = fileDictionary[FileAttributeKey.size]
            print ("\(fileSize)")
        }
        catch{
            print("Error: \(error)")
        }

    }

I get the error message , this file does not exist , where does the document picker save the file and how to get his attributes.


问:
Regex for replacing specific numbers of a sentence
I have a sentence something like below

```<code>test_str = r'Mr.X has 23 apples and 59 oranges, his business partner from Colorado staying staying in hotel with phone number +188991234 and his wife and kids are staying away from him'
</code>```

I would like to replace all digits in the above sentence with '0' and phone number should only have the first digit which is +1.

```<code>result = r'Mr.X has 00 apples and 00 oranges, his business partner from Colorado staying staying in hotel with phone number +1******** and his wife and kids are staying away from him'
</code>```

I have the following regex to replace the phone number pattern (which always has a consistent number of digits).

```<code>result = re.sub(r'(.*)?(+1)(\d{8})', r'\1\2********', test_str)
</code>```

Could i replace other digits with 0  except phone number in one single regex?

答:
we could use re.sub with function

for replacing the phone number, could use regex below.
all digits follow by +1 will be replace to the equivalant number of *

```<code>result = re.sub(r'(?<!\w)(\+1)(\d+)', lambda x:x.group(1) + '*'*len(x.group(2)), test_str)
</code>```

for replacing other number to 0, can use regex below, all digits not precede with + or digit will be replace by equivalant number of 0

```<code>result = re.sub(r'(?<![\+\d])(\d+)', lambda x:'0'*len(x.group(1)), test_str)
</code>```

example

```<code>>>> test_str = r'Mr.X has 23 apples and 59 oranges, his phone number +188991234'
>>> result = re.sub(r'(?<!\w)(\+1)(\d+)', lambda x:x.group(1) + '*'*len(x.group(2)), test_str)
>>> result = re.sub(r'(?<![\+\d])(\d+)', lambda x:'0'*len(x.group(1)), result)
>>> result
'Mr.X has 00 apples and 00 oranges, his phone number +1********'
</code>```

addon for the follow up question in comment to retain 3 digits of number, we could just modify the 1st regex for the +1 portion, while 2nd regex remains the same

```<code>>>> test_str = r'Mr.X has 23 apples and 59 oranges, his phone number +188991234'
>>> result = re.sub(r'(?<!\w)(\+\d{3})(\d+)', lambda x:x.group(1) + '*'*len(x.group(2)), test_str)
>>> result = re.sub(r'(?<![\+\d])(\d+)', lambda x:'0'*len(x.group(1)), result)
>>> result
'Mr.X has 00 apples and 00 oranges, his phone number +188******'
</code>```

Body:
I have a sentence something like below

test_str = r'Mr.X has 23 apples and 59 oranges, his business partner from Colorado staying staying in hotel with phone number +188991234 and his wife and kids are staying away from him'

I would like to replace all digits in the above sentence with '0' and phone number should only have the first digit which is +1.

result = r'Mr.X has 00 apples and 00 oranges, his business partner from Colorado staying staying in hotel with phone number +1******** and his wife and kids are staying away from him'

I have the following regex to replace the phone number pattern (which always has a consistent number of digits).

result = re.sub(r'(.*)?(+1)(\d{8})', r'\1\2********', test_str)

Could i replace other digits with 0  except phone number in one single regex?

Body:
we could use re.sub with function

for replacing the phone number, could use regex below.
all digits follow by +1 will be replace to the equivalant number of *

result = re.sub(r'(?<!\w)(\+1)(\d+)', lambda x:x.group(1) + '*'*len(x.group(2)), test_str)

for replacing other number to 0, can use regex below, all digits not precede with + or digit will be replace by equivalant number of 0

result = re.sub(r'(?<![\+\d])(\d+)', lambda x:'0'*len(x.group(1)), test_str)

example

>>> test_str = r'Mr.X has 23 apples and 59 oranges, his phone number +188991234'
>>> result = re.sub(r'(?<!\w)(\+1)(\d+)', lambda x:x.group(1) + '*'*len(x.group(2)), test_str)
>>> result = re.sub(r'(?<![\+\d])(\d+)', lambda x:'0'*len(x.group(1)), result)
>>> result
'Mr.X has 00 apples and 00 oranges, his phone number +1********'

addon for the follow up question in comment to retain 3 digits of number, we could just modify the 1st regex for the +1 portion, while 2nd regex remains the same

>>> test_str = r'Mr.X has 23 apples and 59 oranges, his phone number +188991234'
>>> result = re.sub(r'(?<!\w)(\+\d{3})(\d+)', lambda x:x.group(1) + '*'*len(x.group(2)), test_str)
>>> result = re.sub(r'(?<![\+\d])(\d+)', lambda x:'0'*len(x.group(1)), result)
>>> result
'Mr.X has 00 apples and 00 oranges, his phone number +188******'


问:
How to update a MVC Form before Submit
So i have 2 Viewbags, they each have a list of values from a database table, the first Viewbag have all possible values of a database column, while the other have only the values corresponding to the selected  value in the first Viewbag.
I have the logic for the search.
but i need to have the form update after selecting one value, since they both need to be in the same form, it is not searching for the second value.

OBS:i am only using the controllers, and cshtml views, not razor pages.

答:
The problem is, that the .cshtml file is completely rendered before its send to your browser. Therefore you cannot change it with C# code after its sent to the browser.

You could use blazor if you want to do it with c#, or you could do it with javascript.

Title: How to update a MVC Form before Submit


问:
Best JPA ID Generation Strategy for Batch Insertion
I am facing an issue while inserting 100 000 records at once using spring data JPA repository. When we execute repo.save(List<Objs>) it is taking a lot of time if we use Sequence generator as it queries the database for the nextval. I am using Oracle, which ID generation is best here?

答:
allocationSize=1 is  the real issue here. With this configuration hibernate will call nextVal() for each insert so if you have 1000 inserts then hibernate  will call nextVal() a 1000 times.

For more information refer to this article by Vlad Mihalcea


问:
Error:SSL peer shut down incorrectly In Android studio 3.0.1
When I build the project I receive the following error
Error:SSL peer shut down incorrectly please let me know how to fix this error</p>

答:
This may not be a generic answer, but I was able to solve it this way.
If you're using the security software Kaspersky, try closing it and then running it.</p>


答:
If you have:

```<code>{
  pavilion: {
    food: {
      meat: {...}
    }
  }
}
</code>```

Then you can use pavilion.food['meat'] to reference the inner object.

More generally, pavilion.food[foodType].

Title: JavaScript: Use variable (argument) as property

Body:
If you have:

{
  pavilion: {
    food: {
      meat: {...}
    }
  }
}

Then you can use pavilion.food['meat'] to reference the inner object.

More generally, pavilion.food[foodType].


问:
ERROR: Could not build wheels for cvxpy which use PEP 517 and cannot be installed directly
I have encountered below issue when installing the CVXPY, I have also downloaded the lasted version of visual studio but seems not working either.</p>

```<code>    >       C:\Anaconda3\lib\site-packages\numpy\distutils\system_info.py:1730:
    > UserWarning:
    >           Lapack (http://www.netlib.org/lapack/) sources not found.
    >           Directories to search for the sources can be specified in the
    >           numpy/distutils/site.cfg file (section [lapack_src]) or by setting
    >           the LAPACK_SRC environment variable.
    >         return getattr(self, '_calc_info_{}'.format(name))()
    >       error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio":
    > https://visualstudio.microsoft.com/downloads/
    >       {}
    >       {}
    >       ----------------------------------------
    >       ERROR: Failed building wheel for scs
    >       Running setup.py clean for scs
    >     Failed to build cvxpy ecos scs
    >     ERROR: Could not build wheels for cvxpy which use PEP 517 and cannot be installed directly
</code>```

答:
I faced the same issue. I had to create a new environment and install for it to work. Go to Anaconda Prompt, and do:

conda create your_env_name

conda activate your_env_name

conda install -c conda-forge cvxpy

conda install spyder

I use Spyder for my work. I had to install Spyder in the new environment as in step 4. I could not find a work around to use the existing Spyder to work for both environments.

Body:
I have encountered below issue when installing the CVXPY, I have also downloaded the lasted version of visual studio but seems not working either.

    >       C:\Anaconda3\lib\site-packages\numpy\distutils\system_info.py:1730:
    > UserWarning:
    >           Lapack (http://www.netlib.org/lapack/) sources not found.
    >           Directories to search for the sources can be specified in the
    >           numpy/distutils/site.cfg file (section [lapack_src]) or by setting
    >           the LAPACK_SRC environment variable.
    >         return getattr(self, '_calc_info_{}'.format(name))()
    >       error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio":
    > https://visualstudio.microsoft.com/downloads/
    >       {}
    >       {}
    >       ----------------------------------------
    >       ERROR: Failed building wheel for scs
    >       Running setup.py clean for scs
    >     Failed to build cvxpy ecos scs
    >     ERROR: Could not build wheels for cvxpy which use PEP 517 and cannot be installed directly


问:
Create a view which joins on a comma separated value
I request help for my homework in SQL.

I have a table with musical instruments:

```<code>id  instrument_name         instrument_at_shops
-----------------------------------------------
1   Electric Guitar         1;2;3;4;
2   Midi Keyboard           1;3;
3   Tom Drum                2;
4   Electric Guitar         1;
5   Electric Guitar         0;
</code>```

And a table with shops:

```<code>shop_id  shop_name  shop_address
-----------------------------------------------
1        Shop1      City1 Street 1, building 1
2        Shop2      City1 Street 5, building 4
3        Shop3      City2 Street 4, building 4
4        Shop4      City3 Street 10, building 7
</code>```

In my musical instruments table I have several numbers which represent id's of the shops that have the particular instrument.

The problem is: how to create a view which contains a shop name and an instrument which is in this shop?

The logic is this:

```<code>SELECT shop_name, instrument_name
FROM Shop
CROSS JOIN Instrument
WHERE instrumet_at_shops CONTAINS shop_id
</code>```

But I cannot create an appropriate query or view design.

Thank you in advance!

答:
As suggested by @Gordon Linoff, you have problems in your data model, with multi-value attributes. But, with your current schema, below code will get you the result you need.

Go for normalized design, which will help in easier queries and better performance.

dbfiddle for reference

DECLARE @instrument table(id int, instrument_name varchar(50), instrument_at_shops varchar(100))

INSERT INTO @instrument values
(1   ,'Electric Guitar',         '1;2;3;4;'),
(2   ,'Midi Keyboard',           '1;3;'),
(3   ,'Tom Drum',                '2;'),
(4   ,'Electric Guitar',         '1;'),
(5   ,'Electric Guitar',         '0;');

DECLARE @Shops table(shop_id int, shop_name varchar(20))

INSERT INTO @shops
values (1,'shop1'), (2,'shop2'), (3,'shop3'), (4,'shop4');

SELECT s.shop_name, STRING_AGG(instrument_Name,',') as instruments
FROM @instrument
CROSS APPLY STRING_SPLIT(instrument_at_shops,';') as t
INNER JOIN @Shops as s
on s.shop_Id = t.value
group by shop_name
```

```+-----------+-----------------------------------------------+
| shop_name |                  instruments                  |
+-----------+-----------------------------------------------+
| shop1     | Electric Guitar,Midi Keyboard,Electric Guitar |
| shop2     | Tom Drum,Electric Guitar                      |
| shop3     | Electric Guitar,Midi Keyboard                 |
| shop4     | Electric Guitar                               |
+-----------+-----------------------------------------------+
```

Body:
I request help for my homework in SQL.

I have a table with musical instruments:

id  instrument_name         instrument_at_shops
-----------------------------------------------
1   Electric Guitar         1;2;3;4;
2   Midi Keyboard           1;3;
3   Tom Drum                2;
4   Electric Guitar         1;
5   Electric Guitar         0;

And a table with shops:

shop_id  shop_name  shop_address
-----------------------------------------------
1        Shop1      City1 Street 1, building 1
2        Shop2      City1 Street 5, building 4
3        Shop3      City2 Street 4, building 4
4        Shop4      City3 Street 10, building 7

In my musical instruments table I have several numbers which represent id's of the shops that have the particular instrument.

The problem is: how to create a view which contains a shop name and an instrument which is in this shop?

The logic is this:

SELECT shop_name, instrument_name
FROM Shop
CROSS JOIN Instrument
WHERE instrumet_at_shops CONTAINS shop_id

But I cannot create an appropriate query or view design.

Thank you in advance!

Body:
As suggested by @Gordon Linoff, you have problems in your data model, with multi-value attributes. But, with your current schema, below code will get you the result you need.

Go for normalized design, which will help in easier queries and better performance.

dbfiddle for reference

DECLARE @instrument table(id int, instrument_name varchar(50), instrument_at_shops varchar(100))

INSERT INTO @instrument values
(1   ,'Electric Guitar',         '1;2;3;4;'),
(2   ,'Midi Keyboard',           '1;3;'),
(3   ,'Tom Drum',                '2;'),
(4   ,'Electric Guitar',         '1;'),
(5   ,'Electric Guitar',         '0;');

DECLARE @Shops table(shop_id int, shop_name varchar(20))

INSERT INTO @shops
values (1,'shop1'), (2,'shop2'), (3,'shop3'), (4,'shop4');

SELECT s.shop_name, STRING_AGG(instrument_Name,',') as instruments
FROM @instrument
CROSS APPLY STRING_SPLIT(instrument_at_shops,';') as t
INNER JOIN @Shops as s
on s.shop_Id = t.value
group by shop_name

+-----------+-----------------------------------------------+
| shop_name |                  instruments                  |
+-----------+-----------------------------------------------+
| shop1     | Electric Guitar,Midi Keyboard,Electric Guitar |
| shop2     | Tom Drum,Electric Guitar                      |
| shop3     | Electric Guitar,Midi Keyboard                 |
| shop4     | Electric Guitar                               |
+-----------+-----------------------------------------------+