问:
Failed to Create Component .. Type is not Marked as Serializable
I'm creating a WinForms user control using Visual C# 2008 Express Edition.

Everything was going on nicely until I found I could play with a List<> collection property from the properties window. After trying to change the collection and running the project, I started getting errors and did my best to get everything back to where it was when it was working.

Now when I try and place an instance of the control onto a form, I get the following error.

```<code>Failed to create component 'ColorPicker'.  The error message follows:
'System.Runtime.Serialization.SerializationException: Type 'WindowsFormsApplication1.ColorPicker+ColorData' in Assembly 'Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
   at System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type)
   at System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context)
   at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo()
   at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter)
   at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter)
  at System.Runtime.Serialization.Formatt...'
</code>```

After dismissing this error, I start getting the following error, usually repeatedly until I use Task Manager to shut Visual C# down.

```<code>Code generation for property 'PaletteColors' failed.  Error was: 'Type 'WindowsFormsApplication1.ColorPicker+ColorData' in Assembly 'Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.'
</code>```

I tried flagging my ColorData class as [Serializable] but then started getting other errors. I don't recall the exact details but it doesn't really matter because I don't want this data serialized.

I tried a new form and got the same error. So I created a completely new project and copied my class' code over to a new user control, and the error still occurs. Can anyone suggest what might be causing this error? I do not want this collection serialized.

Here's the collection in question (these are lines in my user control--the ColorData class is nested in my user control).

```<code>public List<ColorData> PaletteColors { get; set; }

public class ColorData
{
    public string Text { get; set; }
    public Color Color { get; set; }

    public ColorData()
    {
        Text = String.Empty;
        Color = Color.White;
    }

    public ColorData(string text, Color color)
    {
        Text = text;
        Color = color;
    }

    public ColorData(KnownColor color)
    {
        Text = Enum.GetName(typeof(KnownColor), color);
        Color = Color.FromKnownColor(color);
    }

    public override string ToString()
    {
        return Text;
    }
}
</code>```

答:
I added a comment to the accepted answer, but feel this probably deserves its own answer. While the accepted answer definitely works, it doesn't really address the root cause.

If you have a control (wincontrol) with a public property PropertyA, and you add it to a form (myForm), then the designer will add all the necessary initialization for properties into myForm.Designer.cs. Something like;

```<code>Wincontrol1.PropertyA = new List<widget>();
</code>```

It is not uncommon to need to modify a control slightly, lets say we have a new control MyWinControl

```<code>public partial class MyWinControl : WinControl
{
    public List<wodget> PropertyDer1;
    protected List<wodget> PropertyDer2;
}
</code>```

If you sub this new control for the old control in myForm.Designer.cs, then you may well encounter this issue. The reason is that PropertyDer1 has no initialization in the winforms designer. PropertyDer2 won't cause any issues because it is protected. Similarly if you had a custom component and you add a new public property after the component has been added to a form.

If however, you deleted the instance of WinControl on the form, and dragged an instance of the MyWinControl onto the form instead, the proper initialization would occur and you would not see the error. The designer will have created the new control like this

```<code>Wincontrol1.PropertyA = new List<widget>();
Wincontrol1.PropertyDer1= new List<wodget>();
</code>```

There are two easy solutions that do not require hiding the property from the designer.
1. If the property doesn't need to be public, give it the right modifier
2. If the property does need to be public, then just edit the code in the myForm.Designer.cs as in the code above to add the missing initializer

Body:
I'm creating a WinForms user control using Visual C# 2008 Express Edition.

Everything was going on nicely until I found I could play with a List<> collection property from the properties window. After trying to change the collection and running the project, I started getting errors and did my best to get everything back to where it was when it was working.

Now when I try and place an instance of the control onto a form, I get the following error.

Failed to create component 'ColorPicker'.  The error message follows:
'System.Runtime.Serialization.SerializationException: Type 'WindowsFormsApplication1.ColorPicker+ColorData' in Assembly 'Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
   at System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type)
   at System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context)
   at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo()
   at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter)
   at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter)
  at System.Runtime.Serialization.Formatt...'

After dismissing this error, I start getting the following error, usually repeatedly until I use Task Manager to shut Visual C# down.

Code generation for property 'PaletteColors' failed.  Error was: 'Type 'WindowsFormsApplication1.ColorPicker+ColorData' in Assembly 'Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.'

I tried flagging my ColorData class as [Serializable] but then started getting other errors. I don't recall the exact details but it doesn't really matter because I don't want this data serialized.

I tried a new form and got the same error. So I created a completely new project and copied my class' code over to a new user control, and the error still occurs. Can anyone suggest what might be causing this error? I do not want this collection serialized.

Here's the collection in question (these are lines in my user control--the ColorData class is nested in my user control).

public List<ColorData> PaletteColors { get; set; }

public class ColorData
{
    public string Text { get; set; }
    public Color Color { get; set; }

    public ColorData()
    {
        Text = String.Empty;
        Color = Color.White;
    }

    public ColorData(string text, Color color)
    {
        Text = text;
        Color = color;
    }

    public ColorData(KnownColor color)
    {
        Text = Enum.GetName(typeof(KnownColor), color);
        Color = Color.FromKnownColor(color);
    }

    public override string ToString()
    {
        return Text;
    }
}

Body:
I added a comment to the accepted answer, but feel this probably deserves its own answer. While the accepted answer definitely works, it doesn't really address the root cause.

If you have a control (wincontrol) with a public property PropertyA, and you add it to a form (myForm), then the designer will add all the necessary initialization for properties into myForm.Designer.cs. Something like;

Wincontrol1.PropertyA = new List<widget>();

It is not uncommon to need to modify a control slightly, lets say we have a new control MyWinControl

public partial class MyWinControl : WinControl
{
    public List<wodget> PropertyDer1;
    protected List<wodget> PropertyDer2;
}

If you sub this new control for the old control in myForm.Designer.cs, then you may well encounter this issue. The reason is that PropertyDer1 has no initialization in the winforms designer. PropertyDer2 won't cause any issues because it is protected. Similarly if you had a custom component and you add a new public property after the component has been added to a form.

If however, you deleted the instance of WinControl on the form, and dragged an instance of the MyWinControl onto the form instead, the proper initialization would occur and you would not see the error. The designer will have created the new control like this

Wincontrol1.PropertyA = new List<widget>();
Wincontrol1.PropertyDer1= new List<wodget>();

There are two easy solutions that do not require hiding the property from the designer.
1. If the property doesn't need to be public, give it the right modifier
2. If the property does need to be public, then just edit the code in the myForm.Designer.cs as in the code above to add the missing initializer


来源: stackexchange

问:
Snowflake Snowpipe - Email Alert Mechanism
I am planning to use Snowpipe to load data from Kafka, but the support team monitoring the pipe jobs needs an alert mechanism.

How can I implement an alert mechanism for Snowpipe via email/slack/etc?

答:
The interface provided by Snowflake between the database and surroundings is mainly with cloud storage.  There is no out-of-the-box integration with messaging apart from cloud storage events.

All other integration and messaging must be provided by client solutions.

Snowflake also provides scheduled tasks that can be used for monitoring purposes, but the interface limitations are the same as described above.

Snowflake is database as a service and relies on other (external) cloud services for a complete systems solution.

This is different from installing your own copy of database software on your own compute resource, where you can install any software alongside with the database.

ContentLicense: CC BY-SA 4.0


问:
How to format the number in the python?
the number eleven million one hundred and eleven thousand one hundred and eleven. If you took a pencil in your hand right now, you would write the number like this: 11,111,111, or like this: 11.111.111, or even like this: 11 111 111?

How could I wrote this in python?

答:
You can format with 'f' string python3.5 and above.</p>

```<code>num = 11111111

print(f'the number is {num}.')
</code>```

Title: How to format the number in the python?

Body:
You can format with 'f' string python3.5 and above.

num = 11111111

print(f'the number is {num}.')


问:
C/UNIX Execute a function once every x milliseconds
How do I execute a function once every 1000 milliseconds using alarm() or sleep? I want the program to do something else if the function does not execute or complete in 1000 milliseconds.

EDIT: added Pseudocode

```<code>while(true) {
alarm(1000);
execute function;
sleep(1000);
alarm(0);
}
</code>```

Now if alarm(1000) signals SIGALRM is this where I could call the other function?
I'm new to this sort of stuff so not even sure if I am using it right.

答:
I have used this function on Linux to "sleep" in milliseconds:</p>

```<code>void Sleep(unsigned int milliSeconds)
{
    struct timespec req = {0};

    time_t seconds  = (int) (milliSeconds / 1000);
    milliSeconds    = milliSeconds - (seconds * 1000);
    req.tv_sec      = seconds;
    req.tv_nsec     = milliSeconds * 1000000L;

    while (nanosleep(&req, &req) == -1)
        continue;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How do I execute a function once every 1000 milliseconds using alarm() or sleep? I want the program to do something else if the function does not execute or complete in 1000 milliseconds.

EDIT: added Pseudocode

while(true) {
alarm(1000);
execute function;
sleep(1000);
alarm(0);
}

Now if alarm(1000) signals SIGALRM is this where I could call the other function?
I'm new to this sort of stuff so not even sure if I am using it right.

Body:
I have used this function on Linux to "sleep" in milliseconds:

void Sleep(unsigned int milliSeconds)
{
    struct timespec req = {0};

    time_t seconds  = (int) (milliSeconds / 1000);
    milliSeconds    = milliSeconds - (seconds * 1000);
    req.tv_sec      = seconds;
    req.tv_nsec     = milliSeconds * 1000000L;

    while (nanosleep(&req, &req) == -1)
        continue;
}


问:
SHA1 fingerprint and debug key changes after moving my android project to another pc
So, I have a android project for which i am using google and facebook login, and for that of course i need sha1, debug key.

The scenario is i work in office pc and also in my home pc for the same project and i keep moving and copying project files day to day, but each time i replace my home pc's android project with office pc's project files the sha1, debug key changes. My google and facebook settings at server side are based on my home pc's sha1 and debug key.

How to deal with this situation (except setting up facebook and google console settings each time newly) ?

答:
Debug SHA1 key is based on pc so,it is change when you have change pc and relase SHA1 is generated base on package name and keystore so,it is never change.

So, You won't have a same debug key for each machine. And you won't have a same debug key for a machine because there is an expiry for the debug key.

For your solution you have need to add both SHA1 in your developer account.

I hope this can help you!


问:
Checking a CSV for the existence of a similar value in Python
Consider the following CSV:

```<code>date,description,amount
14/02/2020,march contract,-99.00
15/02/2020,april contract,340.00
16/02/2020,march contract,150.00
17/02/2020,april contract,-100.00
</code>```

What I'd like to do is:

Iterate through all of the rows

Total the amounts of lines which have the same description

Return the last line which has that newly-calculated amount

Applied to the above example, the CSV would look like this:

```<code>16/02/2020,march contract,51.00
17/02/2020,april contract,240.00
</code>```

So far, I've tried nesting csv.reader()s inside of each other and I'm not getting the result I am wanting.

I'd like to achieve this without any libraries and/or modules.

Here is the code I have so far, where first_row is each row in the CSV and second_row is the iteration of looking for matching descriptions:

csv_reader = csv.reader(report_file)
        for first_row in csv_reader:
            description_index = 5
            amount_index = 13
            print(first_row)
            for second_row in csv_reader:
                if second_row is not first_row:
                    print(first_row[description_index] == second_row[description_index])
                        if first_row[description_index] == second_row[description_index]:
                            first_row[amount_index] = float(first_row[amount_index]) + float(second_row[amount_index])
```

答:
This will work:

```<code>import csv
uniques = {}  # dictionary to store key/value pairs

with open(report_file, newline='') as f:
    reader = csv.reader(f, delimiter=',')
    next(reader, None)  # skip header row
    for data in reader:
        date = data[0]
        description = data[1]
        if description in uniques:
            cumulative_total = uniques[description][0]
            uniques[description] = [cumulative_total+float(data[2]), date]
        else:
            uniques[description] = [float(data[2]), date]

# print output
for desc, val in uniques.items():
    print(f'{val[0]}, {desc}, {val[1]}')
</code>```

I know that you've asked for a solution without pandas, but you'll save yourself a lot of time if you use it:

```<code>df = pd.read_csv(report_file)

totals = df.groupby(df['description']).sum()
print(totals)
</code>```

Body:
Consider the following CSV:

date,description,amount
14/02/2020,march contract,-99.00
15/02/2020,april contract,340.00
16/02/2020,march contract,150.00
17/02/2020,april contract,-100.00

What I'd like to do is:

Iterate through all of the rows

Total the amounts of lines which have the same description

Return the last line which has that newly-calculated amount

Applied to the above example, the CSV would look like this:

16/02/2020,march contract,51.00
17/02/2020,april contract,240.00

So far, I've tried nesting csv.reader()s inside of each other and I'm not getting the result I am wanting.

I'd like to achieve this without any libraries and/or modules.

Here is the code I have so far, where first_row is each row in the CSV and second_row is the iteration of looking for matching descriptions:

csv_reader = csv.reader(report_file)
        for first_row in csv_reader:
            description_index = 5
            amount_index = 13
            print(first_row)
            for second_row in csv_reader:
                if second_row is not first_row:
                    print(first_row[description_index] == second_row[description_index])
                        if first_row[description_index] == second_row[description_index]:
                            first_row[amount_index] = float(first_row[amount_index]) + float(second_row[amount_index])

Body:
This will work:

import csv
uniques = {}  # dictionary to store key/value pairs

with open(report_file, newline='') as f:
    reader = csv.reader(f, delimiter=',')
    next(reader, None)  # skip header row
    for data in reader:
        date = data[0]
        description = data[1]
        if description in uniques:
            cumulative_total = uniques[description][0]
            uniques[description] = [cumulative_total+float(data[2]), date]
        else:
            uniques[description] = [float(data[2]), date]

# print output
for desc, val in uniques.items():
    print(f'{val[0]}, {desc}, {val[1]}')

I know that you've asked for a solution without pandas, but you'll save yourself a lot of time if you use it:

df = pd.read_csv(report_file)

totals = df.groupby(df['description']).sum()
print(totals)


问:
MongoDB $lookup not using index
I'm writing a query that requires a $lookup between two tables and as I understand it, it's essential that the foreignField have an index in order to perform this join in a timely fashion. However, even after adding an index on the field, the query is still falling back to COLLSCAN.

```<code>db.users.aggregate([
  {$lookup:{ from: "transactions", localField: '_id', foreignField: 'uid', as: 'transaction' }},
  { $match: { transaction: { "$size" : 0} } },
  { $count: "total"},
], { explain: true })
</code>```

This returns:

```<code>"queryPlanner" : {
    "plannerVersion" : 1,
    "namespace" : "test.users",
    "indexFilterSet" : false,
    "parsedQuery" : {

    },
    "winningPlan" : {
        "stage" : "COLLSCAN",
        "direction" : "forward"
    },
    "rejectedPlans" : [ ]
}
</code>```

As I mentioned, I do have the uid field indexed in the transactions collection:

```<code>> db.transactions.getIndexes()
[
    {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "test.transactions"
    },
    {
        "v" : 1,
        "key" : {
            "uid" : 1
        },
        "name" : "uid_1",
        "ns" : "test.transactions"
    }
]
</code>```

The query takes a few minutes to run in a DB of approximately 7M documents. I'm using MongoDB v3.4.7. Any idea as to what I could be doing wrong? Thanks in advance!

答:
The "stage" : "COLLSCAN", isn't referring to the $lookup at all.

The first step in that aggregation pipeline is to fetch all of the documents from the 'users' collection.  Since there are no filters at all provided for that, collection scan is the most efficient method.

The $lookup stage should be planned like any other query, and would likely use the index.

Title: MongoDB $lookup not using index

Body:
I'm writing a query that requires a $lookup between two tables and as I understand it, it's essential that the foreignField have an index in order to perform this join in a timely fashion. However, even after adding an index on the field, the query is still falling back to COLLSCAN.

db.users.aggregate([
  {$lookup:{ from: "transactions", localField: '_id', foreignField: 'uid', as: 'transaction' }},
  { $match: { transaction: { "$size" : 0} } },
  { $count: "total"},
], { explain: true })

This returns:

"queryPlanner" : {
    "plannerVersion" : 1,
    "namespace" : "test.users",
    "indexFilterSet" : false,
    "parsedQuery" : {

    },
    "winningPlan" : {
        "stage" : "COLLSCAN",
        "direction" : "forward"
    },
    "rejectedPlans" : [ ]
}

As I mentioned, I do have the uid field indexed in the transactions collection:

> db.transactions.getIndexes()
[
    {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "test.transactions"
    },
    {
        "v" : 1,
        "key" : {
            "uid" : 1
        },
        "name" : "uid_1",
        "ns" : "test.transactions"
    }
]

The query takes a few minutes to run in a DB of approximately 7M documents. I'm using MongoDB v3.4.7. Any idea as to what I could be doing wrong? Thanks in advance!


问:
Division in verilog
I am teaching myself verilog. The book I am following stated in the introduction chapters that to perform division we use the '/' operator or '%' operator. In later chapters it's saying that division is too complex for verilog and cannot be synthesized, so to perform division it introduces a long algorithm.

So I am confused, can't verilog handle simple division? is the / operator useless?

答: if you want the synthesizable code you can use the Divison_IP or you can use the right shifting operator for some divisions like 64/8=8 same 64>>3 = 8.</p>

Title: Division in verilog


问:
Eclipse C++ build problem

I've just written a simple program in C++ in Eclipse on Ubuntu. But when I press Ctrl+B or select the build all button no binary file is build, and so when I try to run the project I receive the error message: Launch failed. binary not found.

what should I do?

thanx!

答:
You can compile and run the program in the terminal

Go to the specific directory in the terminal using the cd command and type

```<code>g++ <filename>.cpp -o <filename> # This compiles the code
./<filename> # Runs the program in the terminal
</code>```

ContentLicense: CC BY-SA 2.5

Title: Eclipse C++ build problem

Body:
You can compile and run the program in the terminal

Go to the specific directory in the terminal using the cd command and type

g++ <filename>.cpp -o <filename> # This compiles the code
./<filename> # Runs the program in the terminal


问:
How to display a text on a column data according to condition in jQuery DataTable?
The column is_active has 2 types of value, value 1 should be equal to Active and value 2 should be equal to Inactive. Now I want to display Active or Inactive in the column according to a condition. How to do this?

Table implementation

```<code>function loadTemplates() {
        template_table = $('#template-table').DataTable({
            processing: true,
            serverSide: true,
            "ajax": {
                "url": 'template-table',
                "type": "POST",
                "data": function (d) {
                    d._token = "{{ csrf_token() }}";
                }
            },
            "aaSorting": [[0, 'desc']],
            "fnDrawCallback": function (oSettings) {
                rowHighlight('template-table');
                selectRowOnTableLoad(oSettings, 'id', selectedRowID);
                dataTableRow = oSettings;
            },
            columns: [
                {data: 'id'},
                {data: 'title'},
                {data: 'start_date'},
                {data: 'end_date'},
                {data: 'is_active'},//column need to be displayed a text
                {data: 'template_content'},
                {data: 'action', orderable: false, searchable: false}
            ]
        });
    }
</code>```

答:
Use render : This property will modify the data that is used by
  DataTables for various operations as it is read from the data source

```<code> columns: [
                    {data: 'id'},
                    {data: 'title'},
                    {data: 'start_date'},
                    {data: 'end_date'},
                    {data: 'is_active',
                     render: function (data, type, row) {
                        return `<span>${row.is_active==1 ? Active : Inactive}<span>`;
                       }
                       },//column need to be displayed a text
                    {data: 'template_content'},
                    {data: 'action', orderable: false, searchable: false}

       ]
</code>```

Body:
The column is_active has 2 types of value, value 1 should be equal to Active and value 2 should be equal to Inactive. Now I want to display Active or Inactive in the column according to a condition. How to do this?

Table implementation

function loadTemplates() {
        template_table = $('#template-table').DataTable({
            processing: true,
            serverSide: true,
            "ajax": {
                "url": 'template-table',
                "type": "POST",
                "data": function (d) {
                    d._token = "{{ csrf_token() }}";
                }
            },
            "aaSorting": [[0, 'desc']],
            "fnDrawCallback": function (oSettings) {
                rowHighlight('template-table');
                selectRowOnTableLoad(oSettings, 'id', selectedRowID);
                dataTableRow = oSettings;
            },
            columns: [
                {data: 'id'},
                {data: 'title'},
                {data: 'start_date'},
                {data: 'end_date'},
                {data: 'is_active'},//column need to be displayed a text
                {data: 'template_content'},
                {data: 'action', orderable: false, searchable: false}
            ]
        });
    }

Body:
Use render : This property will modify the data that is used by
  DataTables for various operations as it is read from the data source

 columns: [
                    {data: 'id'},
                    {data: 'title'},
                    {data: 'start_date'},
                    {data: 'end_date'},
                    {data: 'is_active',
                     render: function (data, type, row) {
                        return `<span>${row.is_active==1 ? Active : Inactive}<span>`;
                       }
                       },//column need to be displayed a text
                    {data: 'template_content'},
                    {data: 'action', orderable: false, searchable: false}

       ]


答:
There are only tow solution,

One is store both SHA key and Hash Key for both pc in both account, Also both are allowing to store multiple keys so you can store it for multiple pc.

Another one store one release key also for both using Keystore so doing this whenever you sitting on new pc you can test at least creating release APK,

As per my knowledge, there is no other mechanism to do this.

Title: SHA1 fingerprint and debug key changes after moving my android project to another pc

Body:
So, I have a android project for which i am using google and facebook login, and for that of course i need sha1, debug key.

The scenario is i work in office pc and also in my home pc for the same project and i keep moving and copying project files day to day, but each time i replace my home pc's android project with office pc's project files the sha1, debug key changes. My google and facebook settings at server side are based on my home pc's sha1 and debug key.

How to deal with this situation (except setting up facebook and google console settings each time newly) ?


问:
Visual studio shows endless messages "Code generation for property 'valueMember' failed."
After several days of happily hacking away on this C# app using Visual Studio 2008, I get struck by a barrage of error dialogs showing:

Code generation for property 'valueMember' failed.

  Error was: 'Object reference not set to an instance of an object.'

This happens now often when I make a tiny change in the designer, e.g. shift a control a few pixels, and then try to save. Several such error dialogs appear each second, keeping me busy cancelling all those by hammering the Enter key while trying to get alt-F4 to get VS to close.

Eventually I do get VS to close and to save the changes I made. After restarting VS, I do "clean" on the entire project, then "build" and everything works fine, the app runs fine, no problems.

Until I make another slight change in the form designer.

I don't know about any property valueMember in my app.

This makes me crazy, it is a real showstopper for my project. Any help is appreciated.

答:
The problem is missing initialization code for a public property on the control. This will be added for you when you add the control to the designer, but if you replace a control with a derived control, or update the component, then the designer does not know how to deal with this.

If you have a control (wincontrol) with a public property PropertyA, and you add it to a form (myForm), then the designer will add all the necessary initialization for properties into myForm.Designer.cs. Something like;

```<code>Wincontrol1.PropertyA = new List<widget>();
</code>```

It is not uncommon to need to modify a control slightly, lets say we have a new control MyWinControl

```<code>public partial class MyWinControl : WinControl
{
    public List<wodget> PropertyDer1;
    protected List<wodget> PropertyDer2;
}
</code>```

If you sub this new control for the old control in myForm.Designer.cs, then you may well encounter this issue. The reason is that PropertyDer1 has no initialization in the winforms designer. PropertyDer2 won't cause any issues because it is protected. Similarly if you had a custom component and you add a new public property after the component has been added to a form.

If however, you deleted the instance of WinControl on the form, and dragged an instance of the MyWinControl onto the form instead, the proper initialization would occur and you would not see the error. The designer will have created the new control like this

```<code>Wincontrol1.PropertyA = new List<widget>();
Wincontrol1.PropertyDer1= new List<wodget>();
</code>```

There are two easy solutions that do not require hiding the property from the designer.
1. If the property doesn't need to be public, give it the right modifier
2. If the property does need to be public, then just edit the code in the myForm.Designer.cs as in the code above to add the missing initializer

Body:
The problem is missing initialization code for a public property on the control. This will be added for you when you add the control to the designer, but if you replace a control with a derived control, or update the component, then the designer does not know how to deal with this.

If you have a control (wincontrol) with a public property PropertyA, and you add it to a form (myForm), then the designer will add all the necessary initialization for properties into myForm.Designer.cs. Something like;

Wincontrol1.PropertyA = new List<widget>();

It is not uncommon to need to modify a control slightly, lets say we have a new control MyWinControl

public partial class MyWinControl : WinControl
{
    public List<wodget> PropertyDer1;
    protected List<wodget> PropertyDer2;
}

If you sub this new control for the old control in myForm.Designer.cs, then you may well encounter this issue. The reason is that PropertyDer1 has no initialization in the winforms designer. PropertyDer2 won't cause any issues because it is protected. Similarly if you had a custom component and you add a new public property after the component has been added to a form.

If however, you deleted the instance of WinControl on the form, and dragged an instance of the MyWinControl onto the form instead, the proper initialization would occur and you would not see the error. The designer will have created the new control like this

Wincontrol1.PropertyA = new List<widget>();
Wincontrol1.PropertyDer1= new List<wodget>();

There are two easy solutions that do not require hiding the property from the designer.
1. If the property doesn't need to be public, give it the right modifier
2. If the property does need to be public, then just edit the code in the myForm.Designer.cs as in the code above to add the missing initializer


问:
Notification not received in foreground in release ipa
I have integrated firebase for push notifications in flutter. If the app is in foreground I have displayed a dialog with notification details. I am receiving notifications properly in android. Also when I run the ios application from XCode notifications are working fine. However in release ipa notifications are not received in foreground but working well in app background state. I have enabled push notifications and background fetch as well. Any solution for this? Has anybody faced such issue?</p>

答:
Please follow this link
May be it will help you
https://medium.com/@viveky259259/flutter-firebase-notifications-7954a3ad8111</p>


问:
Passing AudioQueueBufferRef data to FFT function!
I am trying to compute the frequency of a given sound process through the microphone on the iphone.

I've read all the post about FFT (including all apple code examples e.g aurioTouch,SpeakHere), but not solution to this problem.

I'm using AudioQueue, but how do I to pass the raw data "AudioQueueBufferRef" from the AudioQueue callback function (MyInputBufferHandler) inBuffer->mAudioData . To the Actual FFT "DSPSplitComplex" datatype, so I can compute it. All this using the Accelerate framework.

```<code>// AudioQueue callback function, called when an input buffers has been filled.
void AQRecorder::MyInputBufferHandler(  void      *                             inUserData,
                                     AudioQueueRef                      inAQ,
                                    AudioQueueBufferRef                 inBuffer,
                                    const AudioTimeStamp *              inStartTime,
                                    UInt32                              inNumPackets,
                                    const AudioStreamPacketDescription* inPacketDesc)
{

 for(int i=0; i<inNumPackets; i++) {
            printf("%d ",((int*)inBuffer->mAudioData)[i]);
 }
}
</code>```

The FFT function.

```<code>RealFFTUsageAndTiming(){

COMPLEX_SPLIT   A; //DSPSplitComplex datatype
FFTSetup        setupReal;
uint32_t        log2n;
uint32_t        n, nOver2;
int32_t         stride;
uint32_t        i;
float          *originalReal, *obtainedReal;
float           scale;

/* Set the size of FFT. */
log2n = N;
n = 1 << log2n;
stride = 1;
nOver2 = n / 2;

/* Allocate memory for the input operands and check its availability,
 * use the vector version to get 16-byte alignment. */

A.realp = (float *) malloc(nOver2 * sizeof(float));
A.imagp = (float *) malloc(nOver2 * sizeof(float));
originalReal = (float *) malloc(n * sizeof(float));
obtainedReal = (float *) malloc(n * sizeof(float));

//How do I pass the data from AudioQueue callback to function?
vDSP_fft_zrip(setupReal, &A, stride, log2n, FFT_FORWARD);

vDSP_fft_zrip(setupReal, &A, stride, log2n, FFT_INVERSE);
}
</code>```

I haven't find anywhere on how to do this. Please help!

答:
You have to know the C data type of the data in the audio buffer and the data types that the FFT supports.  If they are not the same (commonly 16-bit signed int versus short float), then you will have to convert while unpacking and copying the arrays of PCM data (in a for loop).  Given real data, you can zero out the imaginary array of the input to the FFT.

Also, the length of the Audio Queue buffer may not be the same as the FFT length, so you may have to save the data from the Audio Queue callback to another queue internal to your app, and have another worker thread pass that data to your analysis/FFT routines as the queue fills.

Body:
I am trying to compute the frequency of a given sound process through the microphone on the iphone.

I've read all the post about FFT (including all apple code examples e.g aurioTouch,SpeakHere), but not solution to this problem.

I'm using AudioQueue, but how do I to pass the raw data "AudioQueueBufferRef" from the AudioQueue callback function (MyInputBufferHandler) inBuffer->mAudioData . To the Actual FFT "DSPSplitComplex" datatype, so I can compute it. All this using the Accelerate framework.

// AudioQueue callback function, called when an input buffers has been filled.
void AQRecorder::MyInputBufferHandler(  void      *                             inUserData,
                                     AudioQueueRef                      inAQ,
                                    AudioQueueBufferRef                 inBuffer,
                                    const AudioTimeStamp *              inStartTime,
                                    UInt32                              inNumPackets,
                                    const AudioStreamPacketDescription* inPacketDesc)
{

 for(int i=0; i<inNumPackets; i++) {
            printf("%d ",((int*)inBuffer->mAudioData)[i]);
 }
}

The FFT function.

RealFFTUsageAndTiming(){

COMPLEX_SPLIT   A; //DSPSplitComplex datatype
FFTSetup        setupReal;
uint32_t        log2n;
uint32_t        n, nOver2;
int32_t         stride;
uint32_t        i;
float          *originalReal, *obtainedReal;
float           scale;

/* Set the size of FFT. */
log2n = N;
n = 1 << log2n;
stride = 1;
nOver2 = n / 2;

/* Allocate memory for the input operands and check its availability,
 * use the vector version to get 16-byte alignment. */

A.realp = (float *) malloc(nOver2 * sizeof(float));
A.imagp = (float *) malloc(nOver2 * sizeof(float));
originalReal = (float *) malloc(n * sizeof(float));
obtainedReal = (float *) malloc(n * sizeof(float));

//How do I pass the data from AudioQueue callback to function?
vDSP_fft_zrip(setupReal, &A, stride, log2n, FFT_FORWARD);

vDSP_fft_zrip(setupReal, &A, stride, log2n, FFT_INVERSE);
}

I haven't find anywhere on how to do this. Please help!


问:
INFO: {textract, us-east-1} was not found in region metadata
INFO: {textract, us-east-1} was not found in region metadata, trying to construct an endpoint using the standard pattern for this region: 'textract.us-east-1.amazonaws.com'.</p>

答: If we used "AmazonTextractClientBuilder.defaultClient()" For the AmazonTextract client, Textract default added or elase we can set own endpoint using standard().withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endPoint,region)). This is not any error. Just information given to the user. The endpoint for the textract is "https://textract.us-east-1.amazonaws.com".</p>


问:
How to add all the predictors at once and produce a logistic model against the response
There are 780 predictors in my data set. I want to take the combination of all the predictors and use it to create the logistic model against response.

```<code>glm(response~ predictor1+predictor2+......+ predictor780, data=mnist_train, family=binomial(), maxit=100))
</code>```

How to add all the predictors at once with a function and model against the response, without writing all the predictors' names and adding them?

答:
Another easy option is </p>

```<code>glm(response~ ., data=mnist_train, family=binomial(), maxit=100))
</code>```

Body:
There are 780 predictors in my data set. I want to take the combination of all the predictors and use it to create the logistic model against response.

glm(response~ predictor1+predictor2+......+ predictor780, data=mnist_train, family=binomial(), maxit=100))

How to add all the predictors at once with a function and model against the response, without writing all the predictors' names and adding them?

Body:
Another easy option is

glm(response~ ., data=mnist_train, family=binomial(), maxit=100))


问:
How can I locate a device which has been enrolled as a fully managed device?
I'm trying to find out how to locate an Android 9.0 device which has been enrolled using a Service Account and the Android Management API. The documentation does not seem to have any hints for my case.

Since there is apparently no way of logging in with a Service Account, I believe I cannot use https://www.google.com/android/find either.

答:
You can use the Android Management API to turn on "high accuracy" location mode but you will need to use another app to get the location of the device.

To enable "high accuracy" location mode you can use "locationMode": "HIGH_ACCURACY" and use "permissionGrants" to grant your app the permission to access the location.

```<code>policy_json = '''
{
  "applications": [
  {
    "packageName": "{your.app.packageId}",
    "installType": "FORCE_INSTALLED",
    "permissionGrants": [
    {
      "permission": "android.permission.ACCESS_FINE_LOCATION",
      "policy": "GRANT"
    }
  }
],
  "locationMode": "HIGH_ACCURACY"
}
'''
</code>```

Body:
You can use the Android Management API to turn on "high accuracy" location mode but you will need to use another app to get the location of the device.

To enable "high accuracy" location mode you can use "locationMode": "HIGH_ACCURACY" and use "permissionGrants" to grant your app the permission to access the location.

policy_json = '''
{
  "applications": [
  {
    "packageName": "{your.app.packageId}",
    "installType": "FORCE_INSTALLED",
    "permissionGrants": [
    {
      "permission": "android.permission.ACCESS_FINE_LOCATION",
      "policy": "GRANT"
    }
  }
],
  "locationMode": "HIGH_ACCURACY"
}
'''


问:
Regular Expression for Code
I am having a hard time finding a regular expression that can match these Strings:

```<code>@OSMHO:6:75
@4F0SO:5:56
@40KIR:5:15
@VDXBC:4:13
@WYRRA:6:59
@A4AUN:1118:803
</code>```

As you guys can see these strings start with an '@' followed by 5 alphanumeric characters, then a ':', then a number, then another ':', then another number.
Thanks so much for your help.

Title: Regular Expression for Code

Body:
I am having a hard time finding a regular expression that can match these Strings:

@OSMHO:6:75
@4F0SO:5:56
@40KIR:5:15
@VDXBC:4:13
@WYRRA:6:59
@A4AUN:1118:803

As you guys can see these strings start with an '@' followed by 5 alphanumeric characters, then a ':', then a number, then another ':', then another number.
Thanks so much for your help.

Body:
try

#@([a-zA-Z0-9]{5}):([0-9]+):([0-9]+)#i


问:
Invalid Syntax in Countdown and Factorial
I'm new to Python and programming in general, and I can't figure out what I'm entering incorrectly.

I am attempting to create a "Countdown and Factorial" program that allows my user to input a number that will be used as either a countdown or factorial depending on the second input entry of a 1 or 2.

If they choose 1, then the program will run a countdown of num.  If they choose 2 then it will run a factorial of num.

I believe that I have created a proper script but, every time I try to run the program in IDLE, I get an "Invalid Syntax" popup at line 13/14. Line 13 is the blank line between the two input lines.

Could anyone please help me figure out why I am getting this syntax error popup? The code is below:

```<code>import math

def countdown():
    if num == 0:
        return
    print(num)
    countdown(num-1)

def factorial():
    print(math.factorial(num))

num = int(input('Please enter an integer greater than 1.\n')

userChoice = int(input('Please enter a either 1 or 2. If 1 is entered, a countdown from that number to zero is printed. If 2 is entered, the factorial of the number is printed.\n'))

if userChoice == '1':
    countdown()
elif userChoice == '2':
    factorial()
</code>```

答:
Your problem lies on this line:

```<code>num = int(input('Please enter an integer greater than 1.\n')
#        ^_____^                                       ____^___
#        open(2)                                       close(1)
</code>```

You have two opening parentheses but only one closing one. It should be:

```<code>num = int(input('Please enter an integer greater than 1.\n'))
#                                                          _^_
#                                                          add
</code>```

Body:
I'm new to Python and programming in general, and I can't figure out what I'm entering incorrectly.

I am attempting to create a "Countdown and Factorial" program that allows my user to input a number that will be used as either a countdown or factorial depending on the second input entry of a 1 or 2.

If they choose 1, then the program will run a countdown of num.  If they choose 2 then it will run a factorial of num.

I believe that I have created a proper script but, every time I try to run the program in IDLE, I get an "Invalid Syntax" popup at line 13/14. Line 13 is the blank line between the two input lines.

Could anyone please help me figure out why I am getting this syntax error popup? The code is below:

import math

def countdown():
    if num == 0:
        return
    print(num)
    countdown(num-1)

def factorial():
    print(math.factorial(num))

num = int(input('Please enter an integer greater than 1.\n')

userChoice = int(input('Please enter a either 1 or 2. If 1 is entered, a countdown from that number to zero is printed. If 2 is entered, the factorial of the number is printed.\n'))

if userChoice == '1':
    countdown()
elif userChoice == '2':
    factorial()

Body:
Your problem lies on this line:

num = int(input('Please enter an integer greater than 1.\n')
#        ^_____^                                       ____^___
#        open(2)                                       close(1)

You have two opening parentheses but only one closing one. It should be:

num = int(input('Please enter an integer greater than 1.\n'))
#                                                          _^_
#                                                          add


问:
Regex - How to ignore numbers that end with a comma
I have been getting all the phrases that have numbers with words beside them by using this expression.

```<code>[\d+](?:[^a-zA-Z'-]+[a-zA-Z'-]+){0,1}
</code>```

Input:

50 cases are confirmed.

  On January 30, there are confirmed cases of the virus.

  1,300 women are suscpected.

Matches:

50 Men are involved.

  On January 30, there are confirmed cases of the virus.

  1,300 women are suscpected.

The problem is, there are cases where dates are involved, which I'm not interested in getting. So my expected output are actually just these two

Expected:

50 Men are involved.

  On January 30, there are confirmed cases of the virus.

  1,300 women are suscpected.

How do I ignore the numbers that ends with commas?

I have tried doing the following expression by adding , to ignore but it just counts the numbers individually.

Attempt:

```<code>[\d+](?:[^a-zA-Z'-,]+[a-zA-Z'-]+){0,1}
</code>```

Output:

50 Men are involved.

  On January 3 0, there are confirmed cases of the virus.

  1,300 women** are suscpected.

答:
Try \d+(?:,\d+)?\s+[a-zA-Z]+

Explanation:

\d+ - match 1+ digits

(?:...) - non-capturing group

,\d+ - match comma , and 1+ digits

? - match preceeidng pattern 0 or 1 time ({0,1} equivalent)

\s+ - match 1+ whitespaces

[a-zA-Z]+ - match 1+ lowercase or uppercase characters

Demo

Body:
I have been getting all the phrases that have numbers with words beside them by using this expression.

[\d+](?:[^a-zA-Z'-]+[a-zA-Z'-]+){0,1}

Input:

50 cases are confirmed.

  On January 30, there are confirmed cases of the virus.

  1,300 women are suscpected.

Matches:

50 Men are involved.

  On January 30, there are confirmed cases of the virus.

  1,300 women are suscpected.

The problem is, there are cases where dates are involved, which I'm not interested in getting. So my expected output are actually just these two

Expected:

50 Men are involved.

  On January 30, there are confirmed cases of the virus.

  1,300 women are suscpected.

How do I ignore the numbers that ends with commas?

I have tried doing the following expression by adding , to ignore but it just counts the numbers individually.

Attempt:

[\d+](?:[^a-zA-Z'-,]+[a-zA-Z'-]+){0,1}

Output:

50 Men are involved.

  On January 3 0, there are confirmed cases of the virus.

  1,300 women** are suscpected.


问:
D3.js: Pie graph, different color of chart separators?
Is it possible to have different colors for chart segments separators?

On the image above, I want to add different colors (only) for separators like for example green, orange and red zone. It should looks something like this

答:
It may be easiest to draw lines on top of the wedge boundaries.

Calculate

1. the location of the center of the pie,

2. the point on the circumference where the two arc's of interest meet

and draw the line between these two points.  Change the stroke color as needed.

For context, and a possible alternative, the shape of a pie wedge is a d3 arc which is actually a path.  Therefore it also has a stroke, which presumably could be controlled programmatically.  But the arc's path is the whole perimeter of the wedge, and thus it might be difficult to color only one "spoke" segment.


问:
Airbnb React Native Maps custom marker with centered text on top

When I say React Native Maps I refer to this module: https://github.com/airbnb/react-native-maps

How can I center the text on top of this marker such that it works for any screen size on both ios and android? In the screenshot above the text appears to the top left of the marker. It's a 1.

Code included below. Thanks for any guidance!

```<code> <MapView.Marker
  style ={{zIndex: this.state.selectedMarker === marker ? 1 : 0}}
  key={marker.id}
  image={require('../../assets/marker-with-label/marker-with-label.png')}
  coordinate={marker.coordinate}
  >
  <Text>1</Text>
</MapView.Marker>
</code>```

答:
To change the size of the circle whilst zooming in or out, you could adjust it in the onRegionChange and onRegionChangeComplete methods of the MapView, something like this:

```<code>onRegionChange={({longitudeDelta, latitudeDelta})=>{
     let markerSize = Math.round(((longitudeDelta + latitudeDelta) / 2) * 2500);
     this.setState({markerSize});
}}
</code>```

and then use the markersize as the height and width of the marker.

Note: modify the * 2500 to whatever size you need

Body:
When I say React Native Maps I refer to this module: https://github.com/airbnb/react-native-maps

How can I center the text on top of this marker such that it works for any screen size on both ios and android? In the screenshot above the text appears to the top left of the marker. It's a 1.

Code included below. Thanks for any guidance!

 <MapView.Marker
  style ={{zIndex: this.state.selectedMarker === marker ? 1 : 0}}
  key={marker.id}
  image={require('../../assets/marker-with-label/marker-with-label.png')}
  coordinate={marker.coordinate}
  >
  <Text>1</Text>
</MapView.Marker>

Body:
To change the size of the circle whilst zooming in or out, you could adjust it in the onRegionChange and onRegionChangeComplete methods of the MapView, something like this:

onRegionChange={({longitudeDelta, latitudeDelta})=>{
     let markerSize = Math.round(((longitudeDelta + latitudeDelta) / 2) * 2500);
     this.setState({markerSize});
}}

and then use the markersize as the height and width of the marker.

Note: modify the * 2500 to whatever size you need


问:
How to list names of all pods serving traffic behind a service in kubernetes
I want to list names of all pods which are actually serving traffic behind a kubernetes service.My question is how to achieve this by executing a single kubectl command.</p>

答:
This should work, "-o=name" is for displaying only pod name.

kubectl get pods -o=name --all-namespaces | grep {service-name}

Replace {service-name} with your service name


问:
What can I replace here since I can't have a lambda function with implicit variable in C#?
I'm trying to implement a tile-based platforming system for a 2D game demo from this C++ code into C#,

This is what I have written, It doesn't compile though due to the var variable usage.

```<code> class GameLogic
{
    // Level storage
    String sLevel;
    int nLevelWidth;
    int nLevelHeight;

    // Player Properties
    float fPlayerPosX = 1.0f;
    float fPlayerPosY = 1.0f;
    float fPlayerVelX = 0.0f;
    float fPlayerVelY = 0.0f;
    bool bPlayerOnGround = false;

    // Camera properties
    float fCameraPosX = 0.0f;
    float fCameraPosY = 0.0f;

    public GameLogic()
    {
         var GetTile = (ref int x, ref int y) =>
        {
            if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
                return sLevel[y * nLevelWidth + x];
            else
                return "";
        };

        var SetTile = (ref int x, ref int y, string c)=>
        {
            if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
                sLevel[y * nLevelWidth + x] = c;
        };

    }
}
</code>```

What do you suggest I should do here, to implement this functionality. Thank you for your time.

答:
It doesn´t compile because of the var statement.
When you use LambdaExpressions and you want to save it to a variable you have to define the delegate Type.
But you can´t use ref variables here. But that is ok, because you don´t change the value of x or y.

You need a Delegate that describes the type of your function.
You could build you own delegate type but in C# there are two built in types for that case.

Action & Action<T1-16> -> always returns void

Func<T1-17> you can define the return type

The GetTile function takes two int and returns a string.

So you can use Func<int, int, string>.

The SetTitle function has one string parameter more but no return type.

That would be Action<int, int, string>.

internal class GameObject
{
    private int nLevelWidth;
    private int nLevelHeight;

    public GameLogic()
    {
        Func<int, int, string> GetTile = (int x, int y) =>
        {
            if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
                return sLevel[y * nLevelWidth + x];
            else
                return "";
        };

        Action<int, int, string> SetTile = (int x, int y, string c)=>
        {
            if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
                sLevel[y * nLevelWidth + x] = c;
        };
    }
}
```

That´s a good article about delegates.

Body:
I'm trying to implement a tile-based platforming system for a 2D game demo from this C++ code into C#,

This is what I have written, It doesn't compile though due to the var variable usage.

 class GameLogic
{
    // Level storage
    String sLevel;
    int nLevelWidth;
    int nLevelHeight;

    // Player Properties
    float fPlayerPosX = 1.0f;
    float fPlayerPosY = 1.0f;
    float fPlayerVelX = 0.0f;
    float fPlayerVelY = 0.0f;
    bool bPlayerOnGround = false;

    // Camera properties
    float fCameraPosX = 0.0f;
    float fCameraPosY = 0.0f;

    public GameLogic()
    {
         var GetTile = (ref int x, ref int y) =>
        {
            if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
                return sLevel[y * nLevelWidth + x];
            else
                return "";
        };

        var SetTile = (ref int x, ref int y, string c)=>
        {
            if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
                sLevel[y * nLevelWidth + x] = c;
        };

    }
}

What do you suggest I should do here, to implement this functionality. Thank you for your time.

Body:
It doesn´t compile because of the var statement.
When you use LambdaExpressions and you want to save it to a variable you have to define the delegate Type.
But you can´t use ref variables here. But that is ok, because you don´t change the value of x or y.

You need a Delegate that describes the type of your function.
You could build you own delegate type but in C# there are two built in types for that case.

Action & Action<T1-16> -> always returns void

Func<T1-17> you can define the return type

The GetTile function takes two int and returns a string.

So you can use Func<int, int, string>.

The SetTitle function has one string parameter more but no return type.

That would be Action<int, int, string>.

internal class GameObject
{
    private int nLevelWidth;
    private int nLevelHeight;

    public GameLogic()
    {
        Func<int, int, string> GetTile = (int x, int y) =>
        {
            if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
                return sLevel[y * nLevelWidth + x];
            else
                return "";
        };

        Action<int, int, string> SetTile = (int x, int y, string c)=>
        {
            if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
                sLevel[y * nLevelWidth + x] = c;
        };
    }
}

That´s a good article about delegates.


问:
Docker - Update fusionauth to latest version
I have a question regarding the update of fusionauth if i use the docker container (fusionauth-app, auth-search, auth-db). I am actually using version 1.13.2 of the fusionauth app. But i have specified the @latest in docker compose

```<code>fusionauth:
    image: fusionauth/fusionauth-app:latest

auth-search:
    image: docker.elastic.co/elasticsearch/elasticsearch:6.3.1

  auth-db:
    image: postgres:9.6
</code>```

But how to handle if the new updates comes with changes regarding the database schema or search topic? How to hold all in sync? How are the db migrations handled in that case?

Thank you!

答:
The FusionAuth maintenance mode will handle db schema updates. When this occurs you will be prompted in the web UI to complete the upgrade.

There is an example of the FusionAuth maintenance mode in action in the FusionAuth 5 minute guide that may be helpful for you to review.

This may not be desired in production with a multi node environment, in this case you can perform the schema updates outside of FusionAuth as part of your upgrade process.

There is an advanced FusionAuth installation guide to help you through this process.

If you are using kubernetes or helm, there are also some advanced configurations that have been contributed by the community to manage schema upgrades automatically. See helm and k8s configurations in our GitHub repo.

Body:
I have a question regarding the update of fusionauth if i use the docker container (fusionauth-app, auth-search, auth-db). I am actually using version 1.13.2 of the fusionauth app. But i have specified the @latest in docker compose

fusionauth:
    image: fusionauth/fusionauth-app:latest

auth-search:
    image: docker.elastic.co/elasticsearch/elasticsearch:6.3.1

  auth-db:
    image: postgres:9.6

But how to handle if the new updates comes with changes regarding the database schema or search topic? How to hold all in sync? How are the db migrations handled in that case?

Thank you!


问:
pygame help error message "pygame.error: Text has zero width"
Okay so this is my code and the error I am getting is this

and am wondering if you can see any problems with my code. It has something to do with pygame quitting before the game as quit. Thanks, Alex.
The code has other external things but you just need to have a look through it if u can.

import pygame
import random
import time
pygame.init()
pygame.font.init()
pygame.mixer.init()
width = 1920
height = 1080
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
light_blue = (0,0,255)
blue = (0,0,200)
grey = (200,200,200)
dark_grey = (220,220,220)
greenBlue = (25,252,180)
menucolours = (0,0,255)
rollover_greenBlue = (190,50,200)
rollover_menucolours = (190,50,200)
buttonSound = pygame.mixer.Sound("button_click_s.wav")
clock = pygame.time.Clock()
background = pygame.image.load('background.jpg')
window = pygame.display.set_mode((width,height))
window.blit(background, (0,0))
pygame.display.update()

font =  pygame.font.Font('FFFFORWA.TTF',20)
smallText =  pygame.font.Font('FFFFORWA.TTF',20)

win = pygame.display.set_mode((1920,1080))
outline=True
def text_objects(text, font, colour = None):
    if colour == None:
        textSurf = font.render(text, True, black)
    else:
        textSurf = font.render(text, True, colour)
    return textSurf, textSurf.get_rect()
def button(x,y,width,height,ac,ic,msg, act=None, msgColour=None, font = None):
    global List
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    if x+width > mouse[0] > x and y+height > mouse[1] > y:
        pygame.draw.rect(window, ac, (x,y,width,height))
        if click[0] == 1 and act != None:
            buttonSound.play()
            if act == 'rule':
                function.rules()
            elif act == 'new':
                function.game()
            elif act == 'end':
                function.end()
            elif act == 'menu':
                function.menu()
            elif act == 'play1':
                List = 0
                function.place()
            elif act == 'play2':
                List = 1
                function.place()
            elif act == 'play3':
                List = 2
                function.place()
            elif act == 'play4':
                List = 3
                function.place()
            elif act == 'play5':
                List = 4
                function.place()
    else:
        pygame.draw.rect(window, ic, (x,y,width,height))
    if msgColour == None:
        textSurf, textRect = text_objects(msg, smallText, dark_grey)
    else:
        textSurf, textRect = text_objects(msg, smallText, msgColour)
    textRect.center = ((x+(width/2)), (y+(height/2)))
    window.blit(textSurf, textRect)

class function():
    def game():
        global win
        global letters2
        global Letters
        global sen1
        global sen2
        global sen3
        global sen4
        global sen5
        global sen6
        global gameLoop
        global wordLoop
        global finalLoop
        global number
        global sen
        global guesses
        words = ['ABOUT','ABOVE','ABUSE','AUDIO','BEGAN','BASIC','JAZZY','FIZZY','PIZZA','JAKEY','JERKY','CHIPS','CHEWS','CHOMP','CLEAN','DRYER','EIGHT','EQUAL','FLANK','STEAK','FLONG','FOOLS','FOOTY','GUARD']
        gameLoop = True
        pygame.display.update()
        window.blit(background, (0,0))
        word = []
        win = []
        randomWord = random.randint(0,13)
        word.append(words[randomWord])
        letters = list(word[0])
        Letters = list(word[0])
        letters2 = []
        y = 0
        for letter in letters:
            y = y + 1
        for letter in range(0,y):
            letter = random.choice(letters)
            letters.remove(letter)
            letters2.append(letter)
        sen = ['_ ' + '_ ' + '_ ' + '_ ' + '_ ', Letters[0] + ' _ ' + '_ ' + '_ ' + '_ ', Letters[0] + ' ' + Letters[1] + ' _ ' + '_ ' + '_ ',
                Letters[0] + ' ' + Letters[1] + ' ' + Letters[2] + ' _ ' + '_ ', Letters[0] + ' ' + Letters[1] + ' ' + Letters[2] + ' '+ Letters[3] + ' _ ',
                Letters[0] + ' ' + Letters[1] + ' ' + Letters[2] + ' '+ Letters[3] + ' ' + Letters[4]]
        gameLoop = True
        number = 0
        guesses = 5
        text.title(sen[number])
        while gameLoop:
            if len(Letters) == 0:
                finalLoop = True
                while finalLoop:
                    window.blit(background, (0,0))
                    text.title('YOU WIN!')
                    button(550,500,250,100, rollover_menucolours, menucolours, 'Play Again', 'new', black, smallText)
                    button(1250,500,250,100, rollover_menucolours, menucolours, 'Main Menu', 'menu', black, smallText)
                    pygame.display.update()
                    for event in pygame.event.get():
                        if event.type == pygame.QUIT:
                            pygame.quit()

            elif guesses == 0:
                finalLoop = True
                while finalLoop:
                    window.blit(background, (0,0))
                    text.title('YOU LOSE')
                    button(550,500,250,100, rollover_menucolours, menucolours, 'Play Again', 'new', black, smallText)
                    button(1250,500,250,100, rollover_menucolours, menucolours, 'Main Menu', 'menu', black, smallText)
                    pygame.display.update()

                    for event in pygame.event.get():
                        if event.type == pygame.QUIT:

                            pygame.quit()

            button(width/2-220, height/2+50, 50, 50 ,rollover_menucolours, menucolours, letters2[0], 'play1', (black), smallText)
            button(width/2-120, height/2+50, 50, 50, rollover_menucolours, menucolours, letters2[1], 'play2', (black), smallText)
            button(width/2-20, height/2+50, 50, 50, rollover_menucolours, menucolours, letters2[2], 'play3', (black), smallText)
            button(width/2+70, height/2+50, 50, 50, rollover_menucolours, menucolours, letters2[3], 'play4', (black), smallText)
            button(width/2+170, height/2+50, 50, 50, rollover_menucolours, menucolours, letters2[4], 'play5', (black), smallText)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:

                    pygame.quit()
    def menu():

        pygame.mixer.music.load("menu_music.mp3")
        pygame.mixer.music.play()
        mainLoop = True
        clock.tick(1)
        while mainLoop:

            window.blit(background, (0,0))

            text.title('lettermatcher.edu')

            button(550, 500, 250, 100, rollover_menucolours, menucolours, 'START', 'new', black, smallText)
            button(900, 500, 250, 100, rollover_menucolours, menucolours, 'INSTRUCTIONS', 'rule', black, smallText)
            button(1250, 500, 250, 100, rollover_menucolours, menucolours, 'QUIT', 'end', black, smallText)

            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    mainLoop = False
                    pygame.quit()
    def rules():
        global ruleLoop
        ruleLoop = True
        while ruleLoop:
            window.blit(background, (0,0))
            text.title('How to Play')
            text.display_message('The program will give you 5 letters', white, -50)
            text.display_message('You have to click on the letters in order to create the word', white, 0)
            text.display_message('If you pick the wrong letter five times you lose.', white, 50)
            button(1550, 800, 250, 100, rollover_menucolours, menucolours, 'Main Menu', 'menu', black)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:

                    pygame.quit()

    def place():
        global number
        global guesses
        if len(Letters) == 0:
                window.blit(background, (0,0))
                wordLoop = False
                text.title('YOU WIN')
                time.sleep(1)
                ruleLoop = False
        elif letters2[List] == Letters[0]:
            if len(Letters) == 5:
                window.blit(background, (0,0))
                number += 1
                text.title(sen[number])
                Letters.remove(Letters[0])
            elif len(Letters) == 4:
                window.blit(background, (0,0))
                number += 1
                text.title(sen[number])
                Letters.remove(Letters[0])
            elif len(Letters) == 3:
                window.blit(background, (0,0))
                number += 1
                text.title(sen[number])
                Letters.remove(Letters[0])
            elif len(Letters) == 2:
                window.blit(background, (0,0))
                number += 1
                text.title(sen[number])
                Letters.remove(Letters[0])
            elif len(Letters) == 1:
                window.blit(background, (0,0))
                number += 1
                text.title(sen[number])
                Letters.remove(Letters[0])
        elif letters2[List] not in Letters:
            time.sleep(0.1)
        else:
            guesses -= 1
            window.blit(background, (0,0))
            text.title(sen[number])
            gSen = 'Try again. you have ' + str(guesses) + ' left'
            text.display_message(gSen, red)
            time.sleep(0.1)

    def end():
        pygame.quit()

class text():

    def display_message(text, colour = None,y = None, x = None):
        screenText = pygame.font.Font('FFFFORWA.ttf',25)
        if colour == None:
            textSurf, textRect = text_objects(text, screenText)
        else:
            textSurf, textRect = text_objects(text, screenText, colour)
        if y != None:
            if x != None:
                textRect.center = ((width/2+x),(height/2+y))
            else:
                textRect.center = ((width/2),(height/2+y))
        else:
            textRect.center = ((width/2),(height/2))
        window.blit(textSurf, textRect)

    def title(text):
        screenText = pygame.font.Font('FFFFORWA.ttf',80)
        textSurf, textRect = text_objects(text, screenText)
        textRect.center = ((960),(200))
        window.blit(textSurf, textRect)

function.menu()
```

答:
The error is causes be the call of pygame.quit() in end:

def end():
   pygame.quit()
```

Note, pygame.quit() uninitialize all pygame modules.

The real problem, however, is the design of your application. Every time when a button is clicked, then you step into the next function and level of the game. You never return from a function, you always get deeper and deeper on the call stack.

A button click event should not invoke a function directly. A button click changes a game state. The main application operates dependent on the game state and draw the scene dependent on the current state of the game.

Body:
The error is causes be the call of pygame.quit() in end:

def end():
   pygame.quit()

Note, pygame.quit() uninitialize all pygame modules.

The real problem, however, is the design of your application. Every time when a button is clicked, then you step into the next function and level of the game. You never return from a function, you always get deeper and deeper on the call stack.

A button click event should not invoke a function directly. A button click changes a game state. The main application operates dependent on the game state and draw the scene dependent on the current state of the game.


问:
How to trust all my self-signed certificates in my app
I have an Android app that communicates with my host server. The app and the server communicates thru SSL. Every year, I have to renew the (self-signed) certificate in the host server. Every time that cert expires, I have to update my Android app accordingly by creating my own TrustManager and trusting the new certificate directly. This is working perfectly.

The thing is, I don't want to modify my Android app every time my cert expires. So the question is, how do I trust all the self-signed certificates that I issue? Again, only the self-signed certificates from me.

These are the restrictions:

Only self-signed certs can be used

I can only create new certs valid for 12 months max

This is how I generate the cert:

```<code>openssl req -newkey rsa:4096 \
        -x509 \
        -sha256 \
        -days 365 \
        -nodes \
        -out selfSignedCert.crt \
        -keyout newPrivate.key
</code>```

Would appreciate your help.

答: First, it is unclear why exactly you have a limit of one year and how exactly you issue a new certificate and why you are restricted to self-signed certificates only. But the common way to do a pinning/trusting which still works with a renewed certificate is to pin against the public key of the certificate and not against the certificate itself. Then make sure that the key stays the same when renewing the certificate.</p>

Body:
I have an Android app that communicates with my host server. The app and the server communicates thru SSL. Every year, I have to renew the (self-signed) certificate in the host server. Every time that cert expires, I have to update my Android app accordingly by creating my own TrustManager and trusting the new certificate directly. This is working perfectly.

The thing is, I don't want to modify my Android app every time my cert expires. So the question is, how do I trust all the self-signed certificates that I issue? Again, only the self-signed certificates from me.

These are the restrictions:

Only self-signed certs can be used

I can only create new certs valid for 12 months max

This is how I generate the cert:

openssl req -newkey rsa:4096 \
        -x509 \
        -sha256 \
        -days 365 \
        -nodes \
        -out selfSignedCert.crt \
        -keyout newPrivate.key

Would appreciate your help.


问:
This code for Web Scraping using python returning None. Why? Any help would be appreciated
```<code>from bs4 import BeautifulSoup

import requests

headers = {'Use-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/79.0.3945.130 Safari/537.36'}

url = 'https://www.amazon.com/Sony-Alpha-a6400-Mirrorless-Camera/dp/B07MV3P7M8/ref=sr_1_4?keywords=sony+alpha&qid=1581656953&s=electronics&sr=1-4'

page = requests.get(url,headers=headers)

soup = BeautifulSoup(page.content, 'html.parser')

title = soup.find(id="productTitle").get_text()

price = soup.find(id="priceblock_ourprice").get_text()

print(title)

print(price)
</code>```

答:
Your code works fine but there is a robot check before the product page so your request looks for the span tag in that robot check page, fails and returns None.

Here is a link which may help you: python requests & beautifulsoup bot detection


问:
Get and close browser tabs that match my domain on logout
My project has single-sign-on to multiple apps and once signed on, people may be clicking bookmarks or links in notification emails to open tabs to our various and sundry applications.  HOWEVER, when they sign out, this means all that stuff is open, even though the session it connects to on the server is dead.

Analysis has requested that we be able to close all browser tabs going to our app when the user hits logout. I have told them that I don't think we can, but was sufficiently unsure that I am being asked to research it. After all, people do some bonkers stuff in javascript nowadays.

So my questions are, in Chrome, Edge, and IE 11, and without adding extensions, can we:

Detect what windows are open to our domain?

Close said windows forcibly?

I of course know that I could collect window handles for each window opened from our portal page, but as indicated above, I can't depend on all of them having been opened by my portal.

答:
-- Get and close browser tabs that match my domain on logout

-- Detect what windows are open to our domain?

-- Close said windows forcibly?

By using JavaScript, we could only close the tab/window that your code performed window.open() on. also if the window/tab navigates, the window handle is no longer valid and you can’t close it. You could check this thread.

Besides, we could also use selenium webdriver to loop through the tabs and close it. But using this method, we have to use the Edge webdriver, Internet Explorer webdriver and Chrome WebDriver. here are some related threads, you could refer to them:

Is there a way to close a tab in WebDriver or Protractor?

Python and Selenium - Close all tabs without closing the browser

Generally, after login success via SSO, we will get an access token. It contain login user information and the access information, and it also has the start time and expired time. Then, use session or cookie to store this token. After user logout, we should clear the session and cookie, and make the token expired, so next time when user click the website, need to enter user account again. So, in my opinion, I think there is no need to close the related tabs, you could use this method.


问:
How to assign i unique ID or key to SwitchListTile and retrieve/get its value in onChanged in flutter mobile app
I am building 9 SwitchListTile using for loop, as now the button contains same code so am having trouble
in its onChanged as my each button will have specific event to perform, how should i achieve it? Is it possible to send the button text/id or anything unique based on which i can perform the specific tasks?

Here _onChanged(value, counter); 'counter' is nothing but you can assume a variable in for loop assigning values 1-9 for each button. So Onchange i should know which button was pressed!.

I tried assigning // key: ValueKey(counter), to SwitchListTile constructor but was unable to retrieve that value in onChanged.

```<code>class MySwitchListTilesContainer extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[800],
      body: ListView(
        children: List.generate(20, (i)=>MySwitchListTile(

        )),
      ),
    );
  }
}
class MySwitchListTile extends StatefulWidget {

  @override
  _MySwitchListTileState createState() => new _MySwitchListTileState();
}

class _MySwitchListTileState extends State<MySwitchListTile> {
  bool _v = false;
  @override
  Widget build(BuildContext context) {
    return  SwitchListTile(
      value:_v,
      onChanged: (value) {
          _onChanged(value, counter);
        },

    );
  }
}

void _onChanged(bool _v, int index) {
    setState(() {
      _v = _v;
      if (index == 1) {

        print(index);

      } else {
       print(index +1);
      }
    });
  }
</code>```

答:
You can copy paste run full code below

You can pass callback to use in onChanged

code snippet

```<code>ListView(
        children: List.generate(
            20,
            (i) => MySwitchListTile(
                  v: false,
                  callback: () {
                    print("index is $i");
                    setState(() {
                    });
                  },
                )),
      )
...
class MySwitchListTile extends StatefulWidget {
  final bool v;
  final VoidCallback callback;

...
return SwitchListTile(
      value: widget.v,
      onChanged: (value) {
        widget.callback();
      },
    );
</code>```

working demo

output of working demo

```<code>I/flutter ( 6597): index is 0
I/flutter ( 6597): index is 2
I/flutter ( 6597): index is 6
</code>```

full code

```<code>import 'package:flutter/material.dart';

class MySwitchListTilesContainer extends StatefulWidget {
  @override
  _MySwitchListTilesContainerState createState() => _MySwitchListTilesContainerState();
}

class _MySwitchListTilesContainerState extends State<MySwitchListTilesContainer> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[800],
      body: ListView(
        children: List.generate(
            20,
            (i) => MySwitchListTile(
                  v: false,
                  callback: () {
                    print("index is $i");
                    setState(() {
                    });
                  },
                )),
      ),
    );
  }
}

class MySwitchListTile extends StatefulWidget {
  final bool v;
  final VoidCallback callback;

  const MySwitchListTile({Key key, this.v, this.callback}) : super(key: key);

  @override
  _MySwitchListTileState createState() => new _MySwitchListTileState();
}

class _MySwitchListTileState extends State<MySwitchListTile> {
  @override
  Widget build(BuildContext context) {
    return SwitchListTile(
      value: widget.v,
      onChanged: (value) {
        widget.callback();
      },
    );
  }
}

/*void _onChanged(bool _v, int index) {
  setState(() {
    _v = _v;
    if (index == 1) {
      print(index);
    } else {
      print(index + 1);
    }
  });
}*/

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MySwitchListTilesContainer(),
    );
  }
}
</code>```

Body:
I am building 9 SwitchListTile using for loop, as now the button contains same code so am having trouble
in its onChanged as my each button will have specific event to perform, how should i achieve it? Is it possible to send the button text/id or anything unique based on which i can perform the specific tasks?

Here _onChanged(value, counter); 'counter' is nothing but you can assume a variable in for loop assigning values 1-9 for each button. So Onchange i should know which button was pressed!.

I tried assigning // key: ValueKey(counter), to SwitchListTile constructor but was unable to retrieve that value in onChanged.

class MySwitchListTilesContainer extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[800],
      body: ListView(
        children: List.generate(20, (i)=>MySwitchListTile(

        )),
      ),
    );
  }
}
class MySwitchListTile extends StatefulWidget {

  @override
  _MySwitchListTileState createState() => new _MySwitchListTileState();
}

class _MySwitchListTileState extends State<MySwitchListTile> {
  bool _v = false;
  @override
  Widget build(BuildContext context) {
    return  SwitchListTile(
      value:_v,
      onChanged: (value) {
          _onChanged(value, counter);
        },

    );
  }
}

void _onChanged(bool _v, int index) {
    setState(() {
      _v = _v;
      if (index == 1) {

        print(index);

      } else {
       print(index +1);
      }
    });
  }

Body:
You can copy paste run full code below

You can pass callback to use in onChanged

code snippet

ListView(
        children: List.generate(
            20,
            (i) => MySwitchListTile(
                  v: false,
                  callback: () {
                    print("index is $i");
                    setState(() {
                    });
                  },
                )),
      )
...
class MySwitchListTile extends StatefulWidget {
  final bool v;
  final VoidCallback callback;

...
return SwitchListTile(
      value: widget.v,
      onChanged: (value) {
        widget.callback();
      },
    );

working demo

output of working demo

I/flutter ( 6597): index is 0
I/flutter ( 6597): index is 2
I/flutter ( 6597): index is 6

full code

import 'package:flutter/material.dart';

class MySwitchListTilesContainer extends StatefulWidget {
  @override
  _MySwitchListTilesContainerState createState() => _MySwitchListTilesContainerState();
}

class _MySwitchListTilesContainerState extends State<MySwitchListTilesContainer> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[800],
      body: ListView(
        children: List.generate(
            20,
            (i) => MySwitchListTile(
                  v: false,
                  callback: () {
                    print("index is $i");
                    setState(() {
                    });
                  },
                )),
      ),
    );
  }
}

class MySwitchListTile extends StatefulWidget {
  final bool v;
  final VoidCallback callback;

  const MySwitchListTile({Key key, this.v, this.callback}) : super(key: key);

  @override
  _MySwitchListTileState createState() => new _MySwitchListTileState();
}

class _MySwitchListTileState extends State<MySwitchListTile> {
  @override
  Widget build(BuildContext context) {
    return SwitchListTile(
      value: widget.v,
      onChanged: (value) {
        widget.callback();
      },
    );
  }
}

/*void _onChanged(bool _v, int index) {
  setState(() {
    _v = _v;
    if (index == 1) {
      print(index);
    } else {
      print(index + 1);
    }
  });
}*/

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MySwitchListTilesContainer(),
    );
  }
}


问:
Combine object and delete a property
Supposed I have an array of objects structured like this

```<code>"err": [
    {
        "chk" : true,
        "name": "test"
    },
    {
        "chk" :true
        "post": "test"
    }
]
</code>```

How can I re-structure it like this:

```<code>"err": [
    {
        "post": "test"
        "name": "test"
    }
]
</code>```

I tried

```<code>arr.filter(obj => delete obj.chk);
</code>```

It can successfully delete the chk property, but how can I combine the two objects?

答:
You can spread them into Object.assign to create a new object, then remove the chk property from that object:

const err = [
    {
        "chk" : true,
        "name": "test"
    },
    {
        "chk" :true,
        "post": "test"
    }
];
const newObj = Object.assign({}, ...err);
delete newObj.chk;
console.log([newObj]);```
</div>
</div>
</p>

<p>Another method, without deleting, would be to destructure <code>chk</code> on the left-hand side, and use rest syntax:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const err = [
    {
        "chk" : true,
        "name": "test"
    },
    {
        "chk" :true,
        "post": "test"
    }
];
const { chk: _, ...newObj } = Object.assign({}, ...err);
console.log([newObj]);</code>```

Title: Combine object and delete a property

Body:
Supposed I have an array of objects structured like this

"err": [
    {
        "chk" : true,
        "name": "test"
    },
    {
        "chk" :true
        "post": "test"
    }
]

How can I re-structure it like this:

"err": [
    {
        "post": "test"
        "name": "test"
    }
]

I tried

arr.filter(obj => delete obj.chk);

It can successfully delete the chk property, but how can I combine the two objects?

Body:
You can spread them into Object.assign to create a new object, then remove the chk property from that object:

const err = [
    {
        "chk" : true,
        "name": "test"
    },
    {
        "chk" :true,
        "post": "test"
    }
];
const newObj = Object.assign({}, ...err);
delete newObj.chk;
console.log([newObj]);

Another method, without deleting, would be to destructure chk on the left-hand side, and use rest syntax:

const err = [
    {
        "chk" : true,
        "name": "test"
    },
    {
        "chk" :true,
        "post": "test"
    }
];
const { chk: _, ...newObj } = Object.assign({}, ...err);
console.log([newObj]);


问:
How to crack SHA-256 whose preimage consists of multiple words?
I want to crack the preimage of a SHA-256 hash, it is an exercise and my only hint is: Concatenation of four visible words.

I have tried to google the hash and put it into several online crackers / rainbow tables already. I think bruteforce is not an option because four words should be too long in sum, even if each word on its own is short.

So the only thing left would be a dictionary attack, right? But four word dictionaries should be too large to search through, I have tried to generate some via hashcat-utils/combinator.bin and got a RAM overflow at about 50GB even for a short input dictionary. For more popular English nouns (top100) I have created small dictionaries of 4 words with no success either.

Any ideas how to approach this further?

PS: visiblevisiblevisiblevisible is unfortunately not the answer - I tried these puns as well. :-)

答:
You should try shorter wordlists like google-10000-english.txt or wordlists relating to hints from the exercise.
Have a look at this article too: https://www.netmux.com/blog/cracking-12-character-above-passwords</p>


问:
Laravel set id to the other table at the DB transaction
Here's my DB transaction...

public function store(Request $request)
{
    DB::beginTransaction();
    try {
        $superdoc = SuperDoc::create([
            'user_id' => $request->user_id,
            'project_name' => $request->project_name,
            'status' => $request->status,
            'start_date' => $request->start_date,
            'end_date' => $request->end_date,
            'lines' => $request->lines,
            'words' => $request->words,
        ]);
        $lastInsertedId = DB::select('SELECT MAX(ID) FROM super_docs');
    } catch (ValidationException $e) {
        DB::rollBack();
        return redirect()->back();
    } catch (\Exception $e) {
        DB::rollback();
        throw $e;
    }
    try {
        $document = Document::create([
            'superD_id' => $request->superD_id,
            'url' => $request->url,
            'status' => $request->status,
            'text' => $request->text,
            'doc_type' => $request->doc_type,
            'language' => $request->language,
            'date' => $request->date,
        ]);
        return response()->json($superdoc, 201);
    } catch (ValidationException $e) {
        DB::rollBack();
        return redirect()->back();
    } catch (\Exception $e) {
        DB::rollback();
        throw $e;
    }
    DB::commit();
}
```

I want to set the super_doc to auto-generated last id into the document table superD_id in the above transaction. Can anyone help me?

答:
I don't have Knowledge about laravel bu i can give an idea, After inserting into SuperDoc table , you can get that model and the model will give you the model superD_id , that superD_id you can use in the Document Table.

So i think your code will look like this:

public function store(Request $request)
    {

```<code>    DB::beginTransaction();
    try {
        $superdoc = SuperDoc::create([

            'user_id' => $request->user_id,
            'project_name' => $request->project_name,
            'status' => $request->status,
            'start_date' => $request->start_date,
            'end_date' => $request->end_date,
            'lines' => $request->lines,
            'words' => $request->words,

        ]);

        //$lastInsertedId=DB::select('SELECT MAX(ID) FROM super_docs');

    } catch (ValidationException $e) {
        DB::rollBack();
        return redirect()->back();
    } catch (\Exception $e) {
        DB::rollback();
        throw $e;
    }
    try {

        $document = Document::create([
            //$superdoc will have object of saved data which will also have SuperD_id
            'superD_id' => $superdoc->superD_id,
            'url' => $request->url,
            'status' => $request->status,
            'text' => $request->text,
            'doc_type' => $request->doc_type,
            'language' => $request->language,
            'date' => $request->date,

        ]);
       return response()->json($superdoc, 201);

    } catch (ValidationException $e) {
        DB::rollBack();
        return redirect()->back();
    } catch (\Exception $e) {
        DB::rollback();
        throw $e;
    }
    DB::commit();
}
</code>```

Body:
Here's my DB transaction...

public function store(Request $request)
{
    DB::beginTransaction();
    try {
        $superdoc = SuperDoc::create([
            'user_id' => $request->user_id,
            'project_name' => $request->project_name,
            'status' => $request->status,
            'start_date' => $request->start_date,
            'end_date' => $request->end_date,
            'lines' => $request->lines,
            'words' => $request->words,
        ]);
        $lastInsertedId = DB::select('SELECT MAX(ID) FROM super_docs');
    } catch (ValidationException $e) {
        DB::rollBack();
        return redirect()->back();
    } catch (\Exception $e) {
        DB::rollback();
        throw $e;
    }
    try {
        $document = Document::create([
            'superD_id' => $request->superD_id,
            'url' => $request->url,
            'status' => $request->status,
            'text' => $request->text,
            'doc_type' => $request->doc_type,
            'language' => $request->language,
            'date' => $request->date,
        ]);
        return response()->json($superdoc, 201);
    } catch (ValidationException $e) {
        DB::rollBack();
        return redirect()->back();
    } catch (\Exception $e) {
        DB::rollback();
        throw $e;
    }
    DB::commit();
}

I want to set the super_doc to auto-generated last id into the document table superD_id in the above transaction. Can anyone help me?

Body:
I don't have Knowledge about laravel bu i can give an idea, After inserting into SuperDoc table , you can get that model and the model will give you the model superD_id , that superD_id you can use in the Document Table.

So i think your code will look like this:

public function store(Request $request)
    {

    DB::beginTransaction();
    try {
        $superdoc = SuperDoc::create([

            'user_id' => $request->user_id,
            'project_name' => $request->project_name,
            'status' => $request->status,
            'start_date' => $request->start_date,
            'end_date' => $request->end_date,
            'lines' => $request->lines,
            'words' => $request->words,

        ]);

        //$lastInsertedId=DB::select('SELECT MAX(ID) FROM super_docs');

    } catch (ValidationException $e) {
        DB::rollBack();
        return redirect()->back();
    } catch (\Exception $e) {
        DB::rollback();
        throw $e;
    }
    try {

        $document = Document::create([
            //$superdoc will have object of saved data which will also have SuperD_id
            'superD_id' => $superdoc->superD_id,
            'url' => $request->url,
            'status' => $request->status,
            'text' => $request->text,
            'doc_type' => $request->doc_type,
            'language' => $request->language,
            'date' => $request->date,

        ]);
       return response()->json($superdoc, 201);

    } catch (ValidationException $e) {
        DB::rollBack();
        return redirect()->back();
    } catch (\Exception $e) {
        DB::rollback();
        throw $e;
    }
    DB::commit();
}


问:
How to solve the network error on axios api call?
I am not sure why the network error occurs for some of the users  I got this error on sentry and some users email me about this.

Few other errors are too on the sentry for the same API call.

Error: Request aborted

Error: timeout of 0ms exceeded

Here is the code that fetches IP Address

```<code>const getIp = async () => {
        const getIpAddr = await axios.get('https://api.ipify.org?format=json');
        setIp(getIpAddr.data.ip);
};
</code>```

Is this issue related to CORS or any way to solve this error? For some of the users, it works fine.

答:
It's typical CORS issue. Server doesn't allow your client to gather information directly.

try this

```<code>const getIpAddr  = await axios.get('https://cors-anywhere.herokuapp.com/https://api.ipify.org?format=json');
</code>```

Body:
I am not sure why the network error occurs for some of the users  I got this error on sentry and some users email me about this.

Few other errors are too on the sentry for the same API call.

Error: Request aborted

Error: timeout of 0ms exceeded

Here is the code that fetches IP Address

const getIp = async () => {
        const getIpAddr = await axios.get('https://api.ipify.org?format=json');
        setIp(getIpAddr.data.ip);
};

Is this issue related to CORS or any way to solve this error? For some of the users, it works fine.

Body:
It's typical CORS issue. Server doesn't allow your client to gather information directly.

try this

const getIpAddr  = await axios.get('https://cors-anywhere.herokuapp.com/https://api.ipify.org?format=json');


答:
Lambda Expressions doesn't have a compile time type, but is convertible to any matching delegate or expression type. That's why according to MSDN lambda expressions can't be implicitly typed (also check this answer by Eric Lippert

So:

Func<int, int, string> GetTile = (int x, int y) =>
{
    if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
        return sLevel[y * nLevelWidth + x];
    else
        return "";
};

Action<int, int, string> SetTile = (int x, int y, string c)=>
{
   if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
       sLevel[y * nLevelWidth + x] = c;
};
```

Title: What can I replace here since I can't have a lambda function with implicit variable in C#?