问:
Use Async function to print value in ejs view Express js
I passed the model from controller to use it in view, but it seems like printing values using Async functions is not possible in a view. what could be the suitable way to use a model to print inside an async function in a view?

I need to get the userImage from user table.
(ps: use of console.log(userImage) in the same place is working, it's driving me crazy. please help me)

```<code>        <img src="<% userModel.findById(postData.uid,function(err,user) {%>   <%=user.userImage%>  <% }) %>" class="mx-2"><a href="#" class="mx-2">Anmol D. Pradhan</a>
</code>```

答:
At first, that's absolutely not the best practice.

You should do something like that:

    // ...
    const userModel = require('/your-path-to/userModel');
    app.get('/your/url', async (req, res) => {
        const user = await userModel.findById(uid);
        res.render('/youpage.html', {
            user: user
        });
    });
```

<pre class="lang-html prettyprint-override"><code><!-- Here's your EJS template -->

<img src="<%= user.userImage %>" class="mx-2">Anmol D. Pradhan
</code>```

That's just an example. I don't know how actually your routes structured, but I hope that will help.

Body:
I passed the model from controller to use it in view, but it seems like printing values using Async functions is not possible in a view. what could be the suitable way to use a model to print inside an async function in a view?

I need to get the userImage from user table.
(ps: use of console.log(userImage) in the same place is working, it's driving me crazy. please help me)

        <img src="<% userModel.findById(postData.uid,function(err,user) {%>   <%=user.userImage%>  <% }) %>" class="mx-2">Anmol D. Pradhan

Body:
At first, that's absolutely not the best practice.

You should do something like that:

    // ...
    const userModel = require('/your-path-to/userModel');
    app.get('/your/url', async (req, res) => {
        const user = await userModel.findById(uid);
        res.render('/youpage.html', {
            user: user
        });
    });

<!-- Here's your EJS template -->

<img src="<%= user.userImage %>" class="mx-2"><a href="#" class="mx-2">Anmol D. Pradhan</a>

That's just an example. I don't know how actually your routes structured, but I hope that will help.


来源: stackexchange

问:
Excel VBA PasteSpecial xlPasteValues Syntax error
I'm trying to copy data from one .xlsx file to my .xlsm file, but without the formatting. When I try to use the following code line an unspecified Syntax error appears.

TargetSheet.Range("A" & TargetLastRow).PasteSpecial xlPasteValues (or various other forms)

```<code>Sub Import_Click()

'Set the target workbook for import.'
Dim TargetWorkbook As Workbook
Set TargetWorkbook = Application.ActiveWorkbook

'Prompt window for user to select and import file.'
Dim UserFilename As String
UserFilename = Application.GetOpenFilename

Dim UserWorkbook As Workbook
Set UserWorkbook = Application.Workbooks.Open(UserFilename)

'Copy data from source to target sheet.'
Dim SourceSheet As Worksheet
Set SourceSheet = UserWorkbook.Worksheets(1)

Dim TargetSheet As Worksheet
Set TargetSheet = TargetWorkbook.Worksheets(1)

Dim SourceLastRow As Long
SourceLastRow = SourceSheet.Cells(SourceSheet.Rows.Count, "A").End(xlUp).Row

Dim TargetLastRow As Long
TargetLastRow = TargetSheet.Cells(TargetSheet.Rows.Count, "A").End(xlUp).Offset(1).Row

SourceSheet.Range("A2:S" & SourceLastRow).Copy _
TargetSheet.Range("A" & TargetLastRow)

'Close import workbook.'
UserWorkbook.Close

End Sub
</code>```

答:
I would try to avoid using Copy and Paste, replacing of the lines

```<code>SourceSheet.Range("A2:S" & SourceLastRow).Copy _
TargetSheet.Range("A" & TargetLastRow)
</code>```

With the next code

```<code>TargetSheet.Range("A" & TargetLastRow).Resize(SourceLastRow - 1, _
        SourceSheet.Range("A2:S" & SourceLastRow).Columns.count) = _
                        SourceSheet.Range("A2:S" & SourceLastRow)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to copy data from one .xlsx file to my .xlsm file, but without the formatting. When I try to use the following code line an unspecified Syntax error appears.

TargetSheet.Range("A" & TargetLastRow).PasteSpecial xlPasteValues (or various other forms)

Sub Import_Click()

'Set the target workbook for import.'
Dim TargetWorkbook As Workbook
Set TargetWorkbook = Application.ActiveWorkbook

'Prompt window for user to select and import file.'
Dim UserFilename As String
UserFilename = Application.GetOpenFilename

Dim UserWorkbook As Workbook
Set UserWorkbook = Application.Workbooks.Open(UserFilename)

'Copy data from source to target sheet.'
Dim SourceSheet As Worksheet
Set SourceSheet = UserWorkbook.Worksheets(1)

Dim TargetSheet As Worksheet
Set TargetSheet = TargetWorkbook.Worksheets(1)

Dim SourceLastRow As Long
SourceLastRow = SourceSheet.Cells(SourceSheet.Rows.Count, "A").End(xlUp).Row

Dim TargetLastRow As Long
TargetLastRow = TargetSheet.Cells(TargetSheet.Rows.Count, "A").End(xlUp).Offset(1).Row

SourceSheet.Range("A2:S" & SourceLastRow).Copy _
TargetSheet.Range("A" & TargetLastRow)

'Close import workbook.'
UserWorkbook.Close

End Sub

Body:
I would try to avoid using Copy and Paste, replacing of the lines

SourceSheet.Range("A2:S" & SourceLastRow).Copy _
TargetSheet.Range("A" & TargetLastRow)

With the next code

TargetSheet.Range("A" & TargetLastRow).Resize(SourceLastRow - 1, _
        SourceSheet.Range("A2:S" & SourceLastRow).Columns.count) = _
                        SourceSheet.Range("A2:S" & SourceLastRow)


问:
Practicing linked lists
So we learned about lists in class lately and I wanted to practice them. The program doesn't run. Did I fail in filling the nodes? I'm too dizzy to focus on finding the missing key. Sorry for posting such triviality!</p>

```<code>#include <stdio.h>
#include <stdlib.h>

typedef struct node{
    int val;
    struct node *next;
}node_t;

node_t* create_node(int value,node_t *nextnode) {
    node_t *newnode=(node_t*)malloc(sizeof(node_t));
    if(newnode==NULL) {
        printf("ERROR ALLOCATING");
        exit(0);
    }
    newnode->val=value;
    newnode->next=nextnode;
    return newnode;
}

void fill_list(node_t *head) {
    int i=1;
    node_t *current;
    for(;i<21;i++) {
        current=create_node(i,head);
        head=current;
    }
}

void print_list(node_t *head) {
    node_t *current=head;
    while(current) {
        printf("%d",current->val);
        current=current->next;
    }
}

int main() {
    node_t *head=NULL;
    fill_list(head);
    print_list(head);
    return 0;
}
</code>```

答:
Your problem is that fill_list never returns the new head. Thus, head in  main remains NULL.

An easy way of changing that behaviour would be to have fill_list return the new head:

```<code>node_t* fill_list(node_t *head) {
    int i=1;
    node_t *current;
    for(;i<21;i++) {
        current=create_node(i,head);
        head=current;
    }
    return head;
}
</code>```

Title: Practicing linked lists

Body:
So we learned about lists in class lately and I wanted to practice them. The program doesn't run. Did I fail in filling the nodes? I'm too dizzy to focus on finding the missing key. Sorry for posting such triviality!

#include <stdio.h>
#include <stdlib.h>

typedef struct node{
    int val;
    struct node *next;
}node_t;

node_t* create_node(int value,node_t *nextnode) {
    node_t *newnode=(node_t*)malloc(sizeof(node_t));
    if(newnode==NULL) {
        printf("ERROR ALLOCATING");
        exit(0);
    }
    newnode->val=value;
    newnode->next=nextnode;
    return newnode;
}

void fill_list(node_t *head) {
    int i=1;
    node_t *current;
    for(;i<21;i++) {
        current=create_node(i,head);
        head=current;
    }
}

void print_list(node_t *head) {
    node_t *current=head;
    while(current) {
        printf("%d",current->val);
        current=current->next;
    }
}

int main() {
    node_t *head=NULL;
    fill_list(head);
    print_list(head);
    return 0;
}

Body:
Your problem is that fill_list never returns the new head. Thus, head in  main remains NULL.

An easy way of changing that behaviour would be to have fill_list return the new head:

node_t* fill_list(node_t *head) {
    int i=1;
    node_t *current;
    for(;i<21;i++) {
        current=create_node(i,head);
        head=current;
    }
    return head;
}


问:
error in Selenium UI tests with Internet explorer
Hi I am running some UI selenium tests that connect to Browserstack for each run. I am getting some sort of session error and I do not know how to resolve this. see error and config below:

i have just added config for IE as below:

testng xml file

```<code>  <test name="Test - Internet Explorer">
        <parameter name="browser" value="IE"/>
        <parameter name="browserVersion" value="11.0"/>
        <parameter name="os" value="Windows"/>
        <parameter name="osVersion" value="10"/>
        <parameter name="resolution" value="1024x768"/>
        <classes>
            <class name="com.bookinggo.ticketed.uiendtoend.TicketedSingleJourneyTest"/>
        </classes>
    </test>
</code>```

capabilities

```<code>  @BeforeMethod (alwaysRun = true)
@Parameters({"browser", "browserVersion", "os", "osVersion", "resolution"})
public void setUp(String browser, String browserVersion, String os, String osVersion, String resolution)
        throws Exception {
    capability = new DesiredCapabilities();
    capability.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
    capability.setCapability(CapabilityType.SUPPORTS_NETWORK_CONNECTION, "true");
    capability.setCapability(CapabilityType.ACCEPT_INSECURE_CERTS, true);
    capability.setCapability("browser", browser);
    capability.setCapability("browser_version", browserVersion);
    capability.setCapability("os", os);
    capability.setCapability("os_version", osVersion);
    capability.setCapability("resolution", resolution);
    capability.setCapability("browserstack.local", "true");
    capability.setCapability("browserstack.localIdentifier", "Test123");
    capability.setCapability("project", "Ticketed Transport");
    capability.setCapability("build", "Selenium Ticketed End To End UI Tests");
    capability.setCapability("name", "Ticketed book flow journey");
    capability.setCapability("browserstack.networkLogs", "true");
    capability.setCapability("ie.ensureCleanSession", "true");
    URL = new URL(URL_STRING);
    setupScreenshot();
}
</code>```

i am getting this error just for IE, with Chrome and Firefox there is no issue:

```<code> org.openqa.selenium.WebDriverException: Command not found: GET /session/7624397802b5dced4edafe3032da36ea577ecb91/local_storage/key/sessionState
    Command duration or timeout: 0 milliseconds
    Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
    System info: host: 'C02XW09XJHD5', ip: 'fe80:0:0:0:1049:76ca:412a:58dc%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.14.6', java.version: '11.0.2'
    Driver info: org.openqa.selenium.remote.RemoteWebDriver
    Capabilities {browserAttachTimeout: 0, browserName: internet explorer, cssSelectorsEnabled: true, elementScrollBehavior: 0, enableElementCacheCleanup: true, enablePersistentHover: true, handlesAlerts: true, ie.browserCommandLineSwitches: , ie.ensureCleanSession: false, ie.forceCreateProcessApi: false, ie.usePerProcessProxy: false, ignoreProtectedModeSettings: false, ignoreZoomSetting: false, initialBrowserUrl: about:blank, javascriptEnabled: true, nativeEvents: true, platform: WINDOWS, platformName: WINDOWS, requireWindowFocus: false, takesScreenshot: true, unexpectedAlertBehaviour: dismiss, unhandledPromptBehavior: dismiss, version: 11, webdriver.remote.sessionid: 7624397802b5dced4edafe3032d...}
    Session ID: 7624397802b5dced4edafe3032da36ea577ecb91
</code>```

any idea what is wrong and how to solve it?

答: Try to put value not browser name not "IE" , but: "Internet Explorer"</p>

Body:
Hi I am running some UI selenium tests that connect to Browserstack for each run. I am getting some sort of session error and I do not know how to resolve this. see error and config below:

i have just added config for IE as below:

testng xml file

  <test name="Test - Internet Explorer">
        <parameter name="browser" value="IE"/>
        <parameter name="browserVersion" value="11.0"/>
        <parameter name="os" value="Windows"/>
        <parameter name="osVersion" value="10"/>
        <parameter name="resolution" value="1024x768"/>
        <classes>
            <class name="com.bookinggo.ticketed.uiendtoend.TicketedSingleJourneyTest"/>
        </classes>
    </test>

capabilities

  @BeforeMethod (alwaysRun = true)
@Parameters({"browser", "browserVersion", "os", "osVersion", "resolution"})
public void setUp(String browser, String browserVersion, String os, String osVersion, String resolution)
        throws Exception {
    capability = new DesiredCapabilities();
    capability.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
    capability.setCapability(CapabilityType.SUPPORTS_NETWORK_CONNECTION, "true");
    capability.setCapability(CapabilityType.ACCEPT_INSECURE_CERTS, true);
    capability.setCapability("browser", browser);
    capability.setCapability("browser_version", browserVersion);
    capability.setCapability("os", os);
    capability.setCapability("os_version", osVersion);
    capability.setCapability("resolution", resolution);
    capability.setCapability("browserstack.local", "true");
    capability.setCapability("browserstack.localIdentifier", "Test123");
    capability.setCapability("project", "Ticketed Transport");
    capability.setCapability("build", "Selenium Ticketed End To End UI Tests");
    capability.setCapability("name", "Ticketed book flow journey");
    capability.setCapability("browserstack.networkLogs", "true");
    capability.setCapability("ie.ensureCleanSession", "true");
    URL = new URL(URL_STRING);
    setupScreenshot();
}

i am getting this error just for IE, with Chrome and Firefox there is no issue:

 org.openqa.selenium.WebDriverException: Command not found: GET /session/7624397802b5dced4edafe3032da36ea577ecb91/local_storage/key/sessionState
    Command duration or timeout: 0 milliseconds
    Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
    System info: host: 'C02XW09XJHD5', ip: 'fe80:0:0:0:1049:76ca:412a:58dc%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.14.6', java.version: '11.0.2'
    Driver info: org.openqa.selenium.remote.RemoteWebDriver
    Capabilities {browserAttachTimeout: 0, browserName: internet explorer, cssSelectorsEnabled: true, elementScrollBehavior: 0, enableElementCacheCleanup: true, enablePersistentHover: true, handlesAlerts: true, ie.browserCommandLineSwitches: , ie.ensureCleanSession: false, ie.forceCreateProcessApi: false, ie.usePerProcessProxy: false, ignoreProtectedModeSettings: false, ignoreZoomSetting: false, initialBrowserUrl: about:blank, javascriptEnabled: true, nativeEvents: true, platform: WINDOWS, platformName: WINDOWS, requireWindowFocus: false, takesScreenshot: true, unexpectedAlertBehaviour: dismiss, unhandledPromptBehavior: dismiss, version: 11, webdriver.remote.sessionid: 7624397802b5dced4edafe3032d...}
    Session ID: 7624397802b5dced4edafe3032da36ea577ecb91

any idea what is wrong and how to solve it?


问:
What is the proper way to flatten a dictionary in Python, so that each key and list element is paired up?
I have a dictionary object that looks like:

```<code>my_dict = {
    first_key: [{},{}],
    second_key: [{},{}],
    n_key: [{},{}, etc...]
}
</code>```

I would like to flatten the object so that it now looks like:

```<code>{first_key: {object_1}, first_key: {object_2}; second_key, {object_1}, etc...}
</code>```

Any suggestions on how to do this is greatly appreciated.

答:
You can't have duplicate keys in a dictionary. You can turn it until a flat list of key-value objects with nested loops:

```<code>result = []
for key, l in my_dict.items():
    for obj in l:
        result.append({"key": key, "value": obj})
</code>```

The result will look like:

```<code>[{"key": "first_key", "value": {}},
 {"key": "first_key", "value": {}},
 {"key": "second_key", "value": {}},
 ...
]
</code>```

Body:
I have a dictionary object that looks like:

my_dict = {
    first_key: [{},{}],
    second_key: [{},{}],
    n_key: [{},{}, etc...]
}

I would like to flatten the object so that it now looks like:

{first_key: {object_1}, first_key: {object_2}; second_key, {object_1}, etc...}

Any suggestions on how to do this is greatly appreciated.

Body:
You can't have duplicate keys in a dictionary. You can turn it until a flat list of key-value objects with nested loops:

result = []
for key, l in my_dict.items():
    for obj in l:
        result.append({"key": key, "value": obj})

The result will look like:

[{"key": "first_key", "value": {}},
 {"key": "first_key", "value": {}},
 {"key": "second_key", "value": {}},
 ...
]


问:
MSAccess use of special character

I have got a very strange problem.

In the earlier version of programm i have found the following statement inside a query.

```<code>table1!field1 > table2!Field2
</code>```

I ma not able to understand the meaning of the ! sign here.

Can any one able to help me in this regard

thank you in advance

答: ! means default property with String parameter type in VB/VBA. Apparently Table object has default property Field("fieldname") and Field object has default property Value, thereby instead of table1.Field("field1").Value you can use shortcut notation table1!field1.

ContentLicense: CC BY-SA 3.0

Title: MSAccess use of special character

Body:
I have got a very strange problem.

In the earlier version of programm i have found the following statement inside a query.

table1!field1 > table2!Field2

I ma not able to understand the meaning of the ! sign here.

Can any one able to help me in this regard

thank you in advance


问:
How to call an async function synchronized without blocking the main thread?
I wrote a simple console application to test ConfigureAwait(false) for fixing the problem of calling an async function in a synchronized way. This is how I simulate an event and trying to call an async function in a sync way.

 public static class Test2
    {
        private static EventHandler<int> _somethingEvent;

        public static void Run()
        {
            _somethingEvent += OnSomething;
            _somethingEvent(null, 10);
            Console.WriteLine("fetch some other resources");
            Console.ReadLine();
        }

        private static void OnSomething(object sender, int e)
        {
            Console.WriteLine($"passed value : {e}");
            FakeAsync().Wait();
        }

        private static async Task FakeAsync()
        {
            await Task.Delay(2000).ConfigureAwait(false);
            Console.WriteLine($"task completed");
        }
    }
```

<p>the output of the code is like this:</p>

<pre class="lang-sh prettyprint-override"><code>passed value : 10
task completed
fetch some other resources
</code>```

And when I change the OnSomething function to async void like this:

private static async void OnSomething(object sender, int e)
{
    Console.WriteLine($"passed value : {e}");
    await FakeAsync();
}
```

<p>The output will change to this:</p>

<pre class="lang-sh prettyprint-override"><code>passed value : 10
fetch some other resources
task completed
</code>```

You can see fetch some other resources is occurred before task completed section and this is my desired result.

My question is how can I achieve the same result by calling the async function synchronized like the first signature  I wrote for the OnSomething function?

How could I use ConfigureAwait(false) to help me in this situation? Or maybe I am not using it properly.

答:
It's because when you call _somethingEvent(null, 10);, OnSomething isn't being awaited, so the following Console.WriteLine("fetch some other resources"); will be allowed to run straight after await FakeAsync(); is executed.

If you don't need to await the completion of OnSomething before continuing, just do a fire and forget:

```<code>private static void OnSomething(object sender, int e)
{
    Console.WriteLine($"passed value : {e}");
    Task.Run(() => FakeAsync());
}
</code>```

Body:
I wrote a simple console application to test ConfigureAwait(false) for fixing the problem of calling an async function in a synchronized way. This is how I simulate an event and trying to call an async function in a sync way.

 public static class Test2
    {
        private static EventHandler<int> _somethingEvent;

        public static void Run()
        {
            _somethingEvent += OnSomething;
            _somethingEvent(null, 10);
            Console.WriteLine("fetch some other resources");
            Console.ReadLine();
        }

        private static void OnSomething(object sender, int e)
        {
            Console.WriteLine($"passed value : {e}");
            FakeAsync().Wait();
        }

        private static async Task FakeAsync()
        {
            await Task.Delay(2000).ConfigureAwait(false);
            Console.WriteLine($"task completed");
        }
    }

the output of the code is like this:

passed value : 10
task completed
fetch some other resources

And when I change the OnSomething function to async void like this:

private static async void OnSomething(object sender, int e)
{
    Console.WriteLine($"passed value : {e}");
    await FakeAsync();
}

The output will change to this:

passed value : 10
fetch some other resources
task completed

You can see fetch some other resources is occurred before task completed section and this is my desired result.

My question is how can I achieve the same result by calling the async function synchronized like the first signature  I wrote for the OnSomething function?

How could I use ConfigureAwait(false) to help me in this situation? Or maybe I am not using it properly.

Body:
It's because when you call _somethingEvent(null, 10);, OnSomething isn't being awaited, so the following Console.WriteLine("fetch some other resources"); will be allowed to run straight after await FakeAsync(); is executed.

If you don't need to await the completion of OnSomething before continuing, just do a fire and forget:

private static void OnSomething(object sender, int e)
{
    Console.WriteLine($"passed value : {e}");
    Task.Run(() => FakeAsync());
}


问:
Can't give default value to database text field in laravel app (mysql)
in my laravel app I have a Post "body" field of text type, I'm trying to give the field a default value like "This sis the default text for a blog post, feel free to change it" but mysql is throwing an error.

```<code>$table->text('body')->default('This is the default text for a blog post, feel free to change it.');
</code>```

This isn't working...

According to docs BLOB/TEXT fields CAN'T have default values, this is pretty weird tbh.

https://dev.mysql.com/doc/refman/5.7/en/blob.html

I guess I could change the field type from text to string but afaik string won't have as many characters as string type and I knpw for certain that my Blog posts will be loooong. How could I approach this?

Thanks in advance.

答:
You can use Accessors & Mutators

Here is an example for setting default value for body

What it does is that every time your model is going to save in database it checks if value is null then it sets your default value

Just put below code into your model.

public function setBodyAttribute($value = null)
    {
        if (null === $value) {
            $this->attributes['body'] = 'default value';
        }

        $this->attributes['body'] = $value;
    }
```

Body:
in my laravel app I have a Post "body" field of text type, I'm trying to give the field a default value like "This sis the default text for a blog post, feel free to change it" but mysql is throwing an error.

$table->text('body')->default('This is the default text for a blog post, feel free to change it.');

This isn't working...

According to docs BLOB/TEXT fields CAN'T have default values, this is pretty weird tbh.

https://dev.mysql.com/doc/refman/5.7/en/blob.html

I guess I could change the field type from text to string but afaik string won't have as many characters as string type and I knpw for certain that my Blog posts will be loooong. How could I approach this?

Thanks in advance.


问:
Control with treeView with Columns
Does any control support Treeview with columns and checkboxes in C#(Winforms)?

Can you please let me know which control do the above requirement.

答: ObjectListView will make you happy if you target for desktop app. See http://objectlistview.sourceforge.net/cs/index.html</p>

Title: Control with treeView with Columns


问:
Short circuit evaluation in JavaScript - SyntaxError: Unexpected token 'return'
I would like to use short circuit evaluation syntax (with && operator) as described by example in the article:

Say, I have this situation:

```<code>function externalFunction() {

    id == ...
    text == ...

    // OK: Standard if syntax is fine

    if ( aFunction(id, text) ) return

    // KO: Short circuit evaluation generate a RUN-TIME ERROR:
    // SyntaxError: Unexpected token 'return'
    // anotherFunction(id, text) && return
    //                              ^^^^^^

    anotherFunction(id, text) && return

}
</code>```

Why I have the error?
Maybe I can't use a single statement with language keyword (return)?

答:
The right hand side of && needs to be an expression. You're trying to put a statement there.

The && has to evaluate as something but return x doesn't give you a value. It exits the function and passes its RHS to the calling function.

Body:
I would like to use short circuit evaluation syntax (with && operator) as described by example in the article:

Say, I have this situation:

function externalFunction() {

    id == ...
    text == ...

    // OK: Standard if syntax is fine

    if ( aFunction(id, text) ) return

    // KO: Short circuit evaluation generate a RUN-TIME ERROR:
    // SyntaxError: Unexpected token 'return'
    // anotherFunction(id, text) && return
    //                              ^^^^^^

    anotherFunction(id, text) && return

}

Why I have the error?
Maybe I can't use a single statement with language keyword (return)?


问:
Maven Fatal alert: protocol_version
I have a problem with Maven. I use as environment

Windows 10

Java SE JDK Version 8 update 80

Eclipse Mars 2 with M2Eclipse

Maven 3.5.4

I try to use any of the two but the protocol_version error arises.
enable TLS 1.2 in the java application. But it does not work.

I was looking at this solution:

Why am I getting "Received fatal alert: protocol_version" or "peer not authenticated" from Maven Central?

but I do not understand how to make the addition of -Dhttps.protocols = TLSv1.2. no where is it made.

thank you very much for your time, excuse my english

答:
but I do not understand how to make the addition of -Dhttps.protocols = TLSv1.2. no where is it made

This depends on how you're building your Application.

A : if you're building with Eclipse Run button, you'll have to edit Run Configuration (of maven build) as shown below.
(nb. you will NOT enter -D here)

B :  If you're running build command line on your windows console, you can run argument right after your maven build goals

mvn clean install -Dhttps.protocols = TLSv1.2

See this link for more details on Command line arguments for maven build

Title: Maven Fatal alert: protocol_version


问:
Transform table into column
I am trying to get the results of a basketball season. This is the table I have with random values:

What I want is transform that into something like this:

I am currently using this formula =A19 & " - " & C18 and in this case the results I get from it is:

And then I just copy the results and past it as Transpose.

I don't know if I was clear, something you need tell me and I will update the question.

答:
You can try the following formulas (edited to make formulas work from the second row) -

For the first team:

```<code>=INDEX($B$1:$E$1;1;INT((ROW()+2)/(ROWS($A$2:$A$5))))
</code>```

For the second team:

```<code>=INDEX($A$2:$A$5;ROW()-1-ROWS($A$2:$A$5)*INT((ROW()-2)/ROWS($A$2:$A$5));1)
</code>```

For result:

```<code>=INDEX($B$2:$E$5;MATCH(INDEX($A$2:$A$5;ROW()-1-ROWS($A$2:$A$5)*INT((ROW()-2)/ROWS($A$2:$A$5));1);$A$2:$A$5;0);MATCH(INDEX($B$1:$E$1;1;INT((ROW()+2)/(ROWS($A$2:$A$5))));$B$1:$E$1;0))
</code>```

The tournament table must be symmetrical.

If the first two formulas are in separate columns (as in my example), in the third formula, the inner INDEX (...) functions can be replaced by a reference to the corresponding column.

Title: Transform table into column

Body:
You can try the following formulas (edited to make formulas work from the second row) -

For the first team:

=INDEX($B$1:$E$1;1;INT((ROW()+2)/(ROWS($A$2:$A$5))))

For the second team:

=INDEX($A$2:$A$5;ROW()-1-ROWS($A$2:$A$5)*INT((ROW()-2)/ROWS($A$2:$A$5));1)

For result:

=INDEX($B$2:$E$5;MATCH(INDEX($A$2:$A$5;ROW()-1-ROWS($A$2:$A$5)*INT((ROW()-2)/ROWS($A$2:$A$5));1);$A$2:$A$5;0);MATCH(INDEX($B$1:$E$1;1;INT((ROW()+2)/(ROWS($A$2:$A$5))));$B$1:$E$1;0))

The tournament table must be symmetrical.

If the first two formulas are in separate columns (as in my example), in the third formula, the inner INDEX (...) functions can be replaced by a reference to the corresponding column.


问:
Selected Rows in QTableView, copy to QClipboard
I have a SQLite-Database and I did it into a QSqlTableModel.
To show the Database, I put that Model into a QTableView.

Now I want to create a Method where the selected Rows (or the whole Line) will be copied into the QClipboard. After that I want to insert it into my OpenOffice.Calc-Document.

But I have no Idea what to do with the Selected SIGNAL and the QModelIndex and how to put this into the Clipboard.

答:
If anybody is interested, this web page provide a working code project on this topic, it's working pretty well.
Copy / paste functionality implementation for QAbstractTableModel / QTableView</p>


问:
A simple "javac" style command-line C/C++ compiler for Windows 7
Over the last couple of months I practiced console programming with Java just with the help of JDK and a text editor of my choice (Notepad++). And I loved the simplicity as a program can be compiled from the command line plainly using javac and run using java.

Now, I'm looking for similar compiler for C/C++, such that I create a .c or .cpp file and compile it in the command prompt, and all it does is create a "native" executable that can be run directly from the command prompt. Thus, without any need of bloated IDE. The reason I'm looking for such simple compiler is because it is going to be used by high-school students so I'm advised to avoid any IDE as far as possible, so students can practice all the concepts of C/C++ languages without having to go for IDE. Which compiler can I use that does this job? also, I must work across all the versions Windows starting from Windows XP.

答: http://gcc.gnu.org/gcc is a multi platform c/c++ compiler


问:
Sort a linked list, handling pairs as a single item
I am working on this challenge:

Sort a Linked list in increasing order by considering two nodes as a two digit number. (in place sorting)

4 ≤ n ≤ 1000

The length of the linked list is always even.

Example 1:

Input

  1→3→4→2→1→2

Output

  1→2→1→3→4→2

Explanation:

  12 > 13 > 42

Example 2:

Input

  1→3→0→3

Output

  0→3→1→3

Here is my linked list template implementation; which anyone can start coding:

```<code> class Node():
    def __init__(self,val):
        self.data = val
        self.next = None

 class Linkedlist():
    def __init__(self):
        self.head = None

    def add(self,x):
        t = Node(x)
        t.next = self.head
        self.head = t

    def display(self):
        p = self.head
        while p != None:
            print(p.data)
            p=p.next

    def sort(self):
        curr = self.head
        # your logic here

m = Linkedlist()
m.add(1)
m.add(3)
m.add(4)
m.add(2)
m.add(1)
m.add(2)
m.display()
</code>```

Which is the algorithm to sort the pairs in a linked list (in place), and how can I code it?

答:
First of all, your current code will not generate list 1→3→4→2→1→2, but its inverse. This is because your definition of the add method will prepend the given value to the list.

To make add work correctly, it should first find the last node in the list, and append the new node after it. As this is not a very efficient method to add many values to a list, I would suggest to also define add as a Node method, and to allow chaining add calls. That way you can add many values in one chained expression without being inefficient.

Also, as you will need to compare values of pairs, it makes sense to make a method on Node that will return the value of the pair formed by that node and the next in the list.

Finally, for the sort algorithm itself, you could reduce the list to its first pair only (which is then obviously sorted), and treat the rest as a separate list of unsorted nodes. Then extract a pair at a time from the unsorted list, and find the right place to inject it in the main list, so that it remains sorted.

This process represents O(n²) time complexity on average and in the worst case. The best case is O(n), which occurs when the list is originally sorted in reverse order.

Here is how that could look:

```<code>class Node():
    def __init__(self, val):
        self.data = val
        self.next = None

    # Easy chaining: defining this method on a Node as well
    def add(self, val):
        node = Node(val)
        node.next = self.next
        self.next = node
        return node

    # Define how the value of a pair is calculated
    def pairvalue(self):
        return self.data * 10 + self.next.data

class Linkedlist():
    def __init__(self):
        self.head = None

    def add(self, val):
        # Corrected method: addition should be at the end of the list
        node = Node(val)
        if not self.head:
            self.head = node
        else: # Look for the last node in the list
            curr = self.head
            while curr.next:
                curr = curr.next
            # ...and append the new node after it
            curr.next = node
        return node # Allow for chaining

    def display(self):
        p = self.head
        while p:
            print(p.data,  end= "→")
            p = p.next
        print("NIL")

    def sort(self):
        if not self.head:
            return
        # Reduce list to just its first pair
        # The remainder is a temporary "todo" list
        todo = self.head.next.next
        self.head.next.next = None

        while todo:
            pair = todo # The pair that will be added to the sorted list
            todo = todo.next.next
            val = pair.pairvalue()
            if val < self.head.pairvalue():
                # The pair is a minimum: prepend it
                pair.next.next = self.head
                self.head = pair
            else:
                curr = self.head.next # odd index
                # Find insertion point in sorted list
                while curr.next and curr.next.pairvalue() < val:
                    curr = curr.next.next
                # Perform insertion
                pair.next.next = curr.next
                curr.next = pair

m = Linkedlist()
m.add(1).add(3).add(4).add(2).add(1).add(2)
m.display() # original list
m.sort()
m.display() # final list
</code>```

The output:

```<code>1→3→4→2→1→2→NIL
1→2→1→3→4→2→NIL
</code>```

Body:
I am working on this challenge:

Sort a Linked list in increasing order by considering two nodes as a two digit number. (in place sorting)

4 ≤ n ≤ 1000

The length of the linked list is always even.

Example 1:

Input

  1→3→4→2→1→2

Output

  1→2→1→3→4→2

Explanation:

  12 > 13 > 42

Example 2:

Input

  1→3→0→3

Output

  0→3→1→3

Here is my linked list template implementation; which anyone can start coding:

 class Node():
    def __init__(self,val):
        self.data = val
        self.next = None

 class Linkedlist():
    def __init__(self):
        self.head = None

    def add(self,x):
        t = Node(x)
        t.next = self.head
        self.head = t

    def display(self):
        p = self.head
        while p != None:
            print(p.data)
            p=p.next

    def sort(self):
        curr = self.head
        # your logic here

m = Linkedlist()
m.add(1)
m.add(3)
m.add(4)
m.add(2)
m.add(1)
m.add(2)
m.display()

Which is the algorithm to sort the pairs in a linked list (in place), and how can I code it?

Body:
First of all, your current code will not generate list 1→3→4→2→1→2, but its inverse. This is because your definition of the add method will prepend the given value to the list.

To make add work correctly, it should first find the last node in the list, and append the new node after it. As this is not a very efficient method to add many values to a list, I would suggest to also define add as a Node method, and to allow chaining add calls. That way you can add many values in one chained expression without being inefficient.

Also, as you will need to compare values of pairs, it makes sense to make a method on Node that will return the value of the pair formed by that node and the next in the list.

Finally, for the sort algorithm itself, you could reduce the list to its first pair only (which is then obviously sorted), and treat the rest as a separate list of unsorted nodes. Then extract a pair at a time from the unsorted list, and find the right place to inject it in the main list, so that it remains sorted.

This process represents O(n²) time complexity on average and in the worst case. The best case is O(n), which occurs when the list is originally sorted in reverse order.

Here is how that could look:

class Node():
    def __init__(self, val):
        self.data = val
        self.next = None

    # Easy chaining: defining this method on a Node as well
    def add(self, val):
        node = Node(val)
        node.next = self.next
        self.next = node
        return node

    # Define how the value of a pair is calculated
    def pairvalue(self):
        return self.data * 10 + self.next.data

class Linkedlist():
    def __init__(self):
        self.head = None

    def add(self, val):
        # Corrected method: addition should be at the end of the list
        node = Node(val)
        if not self.head:
            self.head = node
        else: # Look for the last node in the list
            curr = self.head
            while curr.next:
                curr = curr.next
            # ...and append the new node after it
            curr.next = node
        return node # Allow for chaining

    def display(self):
        p = self.head
        while p:
            print(p.data,  end= "→")
            p = p.next
        print("NIL")

    def sort(self):
        if not self.head:
            return
        # Reduce list to just its first pair
        # The remainder is a temporary "todo" list
        todo = self.head.next.next
        self.head.next.next = None

        while todo:
            pair = todo # The pair that will be added to the sorted list
            todo = todo.next.next
            val = pair.pairvalue()
            if val < self.head.pairvalue():
                # The pair is a minimum: prepend it
                pair.next.next = self.head
                self.head = pair
            else:
                curr = self.head.next # odd index
                # Find insertion point in sorted list
                while curr.next and curr.next.pairvalue() < val:
                    curr = curr.next.next
                # Perform insertion
                pair.next.next = curr.next
                curr.next = pair

m = Linkedlist()
m.add(1).add(3).add(4).add(2).add(1).add(2)
m.display() # original list
m.sort()
m.display() # final list

The output:

1→3→4→2→1→2→NIL
1→2→1→3→4→2→NIL


问:
Flink SQL Client environment configuration to read CSV file as source streaming table
I want to try out the Match_Recognize operator in Flink SQL from the SQL client. For this, I have done the following setup for the source table

```<code># A typical table source definition looks like:
 - name: TaxiRides
   type: source
   update-mode: append
   connector:
       type: filesystem
       path: "/home/bitnami/Match_Recognize/TaxiRide.csv"
   format:
       type: csv
       fields:
           - name: rideId
             type: LONG
           - name: taxiId
             type: LONG
           - name: isStart
             type: BOOLEAN
           - name: lon
             type: FLOAT
           - name: lat
             type: FLOAT
           - name: rideTime
             type: TIMESTAMP
           - name: psgCnt
             type: INT
       line-delimiter: "\n"
       field-delimiter: ","

   schema:
    - name: rideId
      type: LONG
    - name: taxiId
      type: LONG
    - name: isStart
      type: BOOLEAN
    - name: lon
      type: FLOAT
    - name: lat
      type: FLOAT
    - name: rideTime
      type: TIMESTAMP
      rowtime:
        timestamps:
          type: "from-field"
          from: "eventTime"
        watermarks:
          type: "periodic-bounded"
          delay: "60000"
    - name: psgCnt
      type: INT
</code>```

When I start the session, I get the following error

```<code>Exception in thread "main" org.apache.flink.table.client.SqlClientException: The configured environment is invalid. Please check your environment files again.
        at org.apache.flink.table.client.SqlClient.validateEnvironment(SqlClient.java:147)
        at org.apache.flink.table.client.SqlClient.start(SqlClient.java:99)
        at org.apache.flink.table.client.SqlClient.main(SqlClient.java:194)
Caused by: org.apache.flink.table.client.gateway.SqlExecutionException: Could not create execution context.
        at org.apache.flink.table.client.gateway.local.LocalExecutor.getOrCreateExecutionContext(LocalExecutor.java:562)
        at org.apache.flink.table.client.gateway.local.LocalExecutor.validateSession(LocalExecutor.java:382)
        at org.apache.flink.table.client.SqlClient.validateEnvironment(SqlClient.java:144)
        ... 2 more
Caused by: org.apache.flink.table.api.NoMatchingTableFactoryException: Could not find a suitable table factory for 'org.apache.flink.table.factories.TableSourceFactory' in
the classpath.

Reason: No factory supports all properties.
</code>```

So, my question is: Is it possible to read the source stream as a table from a file or does it have to be from Kafka?

UPDATE: I am using Flink version 1.9.1

答:
Unfortunately you are hitting a limitation of the csv filesystem connector. This connector does not support rowtime attributes.

In 1.10 we started work on expressing watermarks and time attributes in a slightly different way. See for a reference: https://issues.apache.org/jira/browse/FLINK-14320.

You can try creating a Table from DDL with a WATERMARK declaration as described here: https://ci.apache.org/projects/flink/flink-docs-release-1.10/dev/table/sql/create.html#create-table It works for the blink planner only though (blink planner is the default implementation in sql-client starting from the 1.10 release).

Another option you have is reading from Kafka with a CSV format.

BTW this particular exception message was improved in FLINK 1.10. Since now Flink will tell the problematic properties.

Body:
I want to try out the Match_Recognize operator in Flink SQL from the SQL client. For this, I have done the following setup for the source table

# A typical table source definition looks like:
 - name: TaxiRides
   type: source
   update-mode: append
   connector:
       type: filesystem
       path: "/home/bitnami/Match_Recognize/TaxiRide.csv"
   format:
       type: csv
       fields:
           - name: rideId
             type: LONG
           - name: taxiId
             type: LONG
           - name: isStart
             type: BOOLEAN
           - name: lon
             type: FLOAT
           - name: lat
             type: FLOAT
           - name: rideTime
             type: TIMESTAMP
           - name: psgCnt
             type: INT
       line-delimiter: "\n"
       field-delimiter: ","

   schema:
    - name: rideId
      type: LONG
    - name: taxiId
      type: LONG
    - name: isStart
      type: BOOLEAN
    - name: lon
      type: FLOAT
    - name: lat
      type: FLOAT
    - name: rideTime
      type: TIMESTAMP
      rowtime:
        timestamps:
          type: "from-field"
          from: "eventTime"
        watermarks:
          type: "periodic-bounded"
          delay: "60000"
    - name: psgCnt
      type: INT

When I start the session, I get the following error

Exception in thread "main" org.apache.flink.table.client.SqlClientException: The configured environment is invalid. Please check your environment files again.
        at org.apache.flink.table.client.SqlClient.validateEnvironment(SqlClient.java:147)
        at org.apache.flink.table.client.SqlClient.start(SqlClient.java:99)
        at org.apache.flink.table.client.SqlClient.main(SqlClient.java:194)
Caused by: org.apache.flink.table.client.gateway.SqlExecutionException: Could not create execution context.
        at org.apache.flink.table.client.gateway.local.LocalExecutor.getOrCreateExecutionContext(LocalExecutor.java:562)
        at org.apache.flink.table.client.gateway.local.LocalExecutor.validateSession(LocalExecutor.java:382)
        at org.apache.flink.table.client.SqlClient.validateEnvironment(SqlClient.java:144)
        ... 2 more
Caused by: org.apache.flink.table.api.NoMatchingTableFactoryException: Could not find a suitable table factory for 'org.apache.flink.table.factories.TableSourceFactory' in
the classpath.

Reason: No factory supports all properties.

So, my question is: Is it possible to read the source stream as a table from a file or does it have to be from Kafka?

UPDATE: I am using Flink version 1.9.1


问:
SQLite3 Create Table Unexpected "(" Error

Set up

Ubuntu 18.04 on Google VM

Objective

I'm trying to create a for loop to create multiple tables based on my list of clients

Issue

I can create a table just fine if I run

```<code>user@sql-server:~$ sqlite3 mydatabase.db
SQLite version 3.22.0 2018-01-22 18:45:57
Enter ".help" for usage hints.
sqlite> create table client (Date integer, cheese integer, id1 integer, id2 integer, id3 integer, id4 integer, id5 integer, id6 integer, id7 integer, id8 integer, id9 integer, id10 integer, id11 integer, id12 integer, id13 integer, id14 integer, id15 integer, id16 integer, id17 integer, id18 integer, id19 integer, id20 integer);
sqlite> .tables
client  test
</code>```

but when I try to create a script "test.sh" like below:

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

set -eu

sqlite3 adloox.db create table test2 (test2 string, testno2 integer);

exit
</code>```

I get the following error:

```<code>user@sql-server:~$ sh -x test.sh
+ set -eu
test.sh: 5: test.sh: Syntax error: "(" unexpected
</code>```

I can see if I input sqlite3 adloox.db .tables I can get a response from the terminal, so I believe I need to have this on one line as opposed to across multiple lines in my script, as it will then request the manual input. But I find it strange that the error I get relates to the "(" as there I don't see what the difference is. Can someone confirm what I'm missing with how what I'm doing in the script differs from the manual input? I've tried googling for an answer but everything I find keeps pointing to manual inputs. Appreciate any help on this one.

答:
Simply add quotes around your sqlite3 command this way : </p>

```<code>sqlite3 adloox.db 'create table test2 (test2 string, testno2 integer);'
</code>```

Body:
Set up

Ubuntu 18.04 on Google VM

Objective

I'm trying to create a for loop to create multiple tables based on my list of clients

Issue

I can create a table just fine if I run

user@sql-server:~$ sqlite3 mydatabase.db
SQLite version 3.22.0 2018-01-22 18:45:57
Enter ".help" for usage hints.
sqlite> create table client (Date integer, cheese integer, id1 integer, id2 integer, id3 integer, id4 integer, id5 integer, id6 integer, id7 integer, id8 integer, id9 integer, id10 integer, id11 integer, id12 integer, id13 integer, id14 integer, id15 integer, id16 integer, id17 integer, id18 integer, id19 integer, id20 integer);
sqlite> .tables
client  test

but when I try to create a script "test.sh" like below:

#!/bin/bash

set -eu

sqlite3 adloox.db create table test2 (test2 string, testno2 integer);

exit

I get the following error:

user@sql-server:~$ sh -x test.sh
+ set -eu
test.sh: 5: test.sh: Syntax error: "(" unexpected

I can see if I input sqlite3 adloox.db .tables I can get a response from the terminal, so I believe I need to have this on one line as opposed to across multiple lines in my script, as it will then request the manual input. But I find it strange that the error I get relates to the "(" as there I don't see what the difference is. Can someone confirm what I'm missing with how what I'm doing in the script differs from the manual input? I've tried googling for an answer but everything I find keeps pointing to manual inputs. Appreciate any help on this one.

Body:
Simply add quotes around your sqlite3 command this way :

sqlite3 adloox.db 'create table test2 (test2 string, testno2 integer);'


问:
ASP.Net MVC Routing with HTTP Action Verbs
I am writing a implementing a ASP.NET web app, and when I call against a particular url, I want to call a different action method depending on whether the request is a GET or a POST.

I've tried two different approaches - first of all I start with a controller with the following action methods:

```<code><HttpGet>
Public Function Index() as ActionResult
...
End Function

<HttpPost>
Public Function Index() as ActionResult
...
End Function
</code>```

... and then registering a Route which sets .action to "Index" for the Url. This doesn't compile, because the two functions have the same signature.

Next I tried changing the name of the Post routine to "Subscribe", but of course that would require me to supply two different routes to the routing table (so as to specify the new action method name). If I do that, I find that the second one is cancelled out by the first.

I'm now thinking of going back to my original idea, but supplying a dummy parameter to it, and specifying it as UrlParameter.Optional. By having this as an argument in the post routine, this will create a new method signature, which I would expect would be ok.

It smells a bit of a dirty hack though - so I was wondering how other people would go about it?

Martin.

Ps. I have now tried the dirty hack, and it does work. Still interested in hearing the views of others though.

答:
Rename actions and use ActionNameAttribute

```<code><HttpGet>
<ActionName("Index")>
Public Function IndexGet() as ActionResult
...
End Function

<HttpPost>
<ActionName("Index")>
Public Function IndexPost() as ActionResult
...
End Function
</code>```

But I don't know what your POST method will do because it doesn't get any data. POST actions usually get some post data to process, so it would probably need some parameters as well. When you'd add them your two methods could share the same name since their signatures would differ (one would be without parameters, and one with them).

Body:
I am writing a implementing a ASP.NET web app, and when I call against a particular url, I want to call a different action method depending on whether the request is a GET or a POST.

I've tried two different approaches - first of all I start with a controller with the following action methods:

<HttpGet>
Public Function Index() as ActionResult
...
End Function

<HttpPost>
Public Function Index() as ActionResult
...
End Function

... and then registering a Route which sets .action to "Index" for the Url. This doesn't compile, because the two functions have the same signature.

Next I tried changing the name of the Post routine to "Subscribe", but of course that would require me to supply two different routes to the routing table (so as to specify the new action method name). If I do that, I find that the second one is cancelled out by the first.

I'm now thinking of going back to my original idea, but supplying a dummy parameter to it, and specifying it as UrlParameter.Optional. By having this as an argument in the post routine, this will create a new method signature, which I would expect would be ok.

It smells a bit of a dirty hack though - so I was wondering how other people would go about it?

Martin.

Ps. I have now tried the dirty hack, and it does work. Still interested in hearing the views of others though.

Body:
Rename actions and use ActionNameAttribute

<HttpGet>
<ActionName("Index")>
Public Function IndexGet() as ActionResult
...
End Function

<HttpPost>
<ActionName("Index")>
Public Function IndexPost() as ActionResult
...
End Function

But I don't know what your POST method will do because it doesn't get any data. POST actions usually get some post data to process, so it would probably need some parameters as well. When you'd add them your two methods could share the same name since their signatures would differ (one would be without parameters, and one with them).


答:
This answer is similar to @PaulMcG's answer but doesn't require sorting the input.

For those into functional programming, groupBy can be written in one line (not including imports!), and unlike itertools.groupby it doesn't require the input to be sorted:

from functools import reduce # import needed for python3; builtin in python2
from collections import defaultdict

def groupBy(key, seq):
 return reduce(lambda grp, val: grp[key(val)].append(val) or grp, seq, defaultdict(list))
```

<p>(The reason for <code>... or grp</code> in the <code>lambda</code> is that for this <code>reduce()</code> to work, the <code>lambda</code> needs to return its first argument; because <code>list.append()</code> always returns <code>None</code> the <code>or</code> will always return <code>grp</code>.  I.e. it's a hack to get around python's restriction that a lambda can only evaluate a single expression.)</p>

<p>This returns a dict whose keys are found by evaluating the given function and whose values are a list of the original items in the original order.  For the OP's example, calling this as <code>groupBy(lambda pair: pair[1], input)</code> will return this dict:</p>

<pre class="lang-py prettyprint-override"><code>{'KAT': [('11013331', 'KAT'), ('9843236', 'KAT')],
 'NOT': [('9085267', 'NOT'), ('11788544', 'NOT')],
 'ETH': [('5238761', 'ETH'), ('5349618', 'ETH'), ('962142', 'ETH'), ('7795297', 'ETH'), ('7341464', 'ETH'), ('5594916', 'ETH'), ('1550003', 'ETH')]}
</code>```

And as per @PaulMcG's answer the OP's requested format can be found by wrapping that in a list comprehension.  So this will do it:

result = {key: [pair[0] for pair in values],
          for key, values in groupBy(lambda pair: pair[1], input).items()}
```

Title: Python group by

Body:
Assume that I have a set of data pair where index 0 is the value and index 1 is the type:

input = [
          ('11013331', 'KAT'),
          ('9085267',  'NOT'),
          ('5238761',  'ETH'),
          ('5349618',  'ETH'),
          ('11788544', 'NOT'),
          ('962142',   'ETH'),
          ('7795297',  'ETH'),
          ('7341464',  'ETH'),
          ('9843236',  'KAT'),
          ('5594916',  'ETH'),
          ('1550003',  'ETH')
        ]

I want to group them by their type (by the 1st indexed string) as such:

result = [
           {
             'type': 'KAT',
             'items': ['11013331', '9843236']
           },
           {
             'type': 'NOT',
             'items': ['9085267', '11788544']
           },
           {
             'type': 'ETH',
             'items': ['5238761', '962142', '7795297', '7341464', '5594916', '1550003']
           }
         ]

How can I achieve this in an efficient way?

Body:
This answer is similar to @PaulMcG's answer but doesn't require sorting the input.

For those into functional programming, groupBy can be written in one line (not including imports!), and unlike itertools.groupby it doesn't require the input to be sorted:

from functools import reduce # import needed for python3; builtin in python2
from collections import defaultdict

def groupBy(key, seq):
 return reduce(lambda grp, val: grp[key(val)].append(val) or grp, seq, defaultdict(list))

(The reason for ... or grp in the lambda is that for this reduce() to work, the lambda needs to return its first argument; because list.append() always returns None the or will always return grp.  I.e. it's a hack to get around python's restriction that a lambda can only evaluate a single expression.)

This returns a dict whose keys are found by evaluating the given function and whose values are a list of the original items in the original order.  For the OP's example, calling this as groupBy(lambda pair: pair[1], input) will return this dict:

{'KAT': [('11013331', 'KAT'), ('9843236', 'KAT')],
 'NOT': [('9085267', 'NOT'), ('11788544', 'NOT')],
 'ETH': [('5238761', 'ETH'), ('5349618', 'ETH'), ('962142', 'ETH'), ('7795297', 'ETH'), ('7341464', 'ETH'), ('5594916', 'ETH'), ('1550003', 'ETH')]}

And as per @PaulMcG's answer the OP's requested format can be found by wrapping that in a list comprehension.  So this will do it:

result = {key: [pair[0] for pair in values],
          for key, values in groupBy(lambda pair: pair[1], input).items()}


问:
How to maximize browser window using puppeteer?
I am trying to maximize the browser window using puppeteer. I tried below code but the browser is not maximized to full mode. I also did not find any function available in puppeteer library to maximize the window.

(async () => {
  const browser = await puppeteer.launch({headless: false , slowMo: 100, rgs: ['--start-fullscreen', '--window-size=1920,1080'], executablePath: 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe' });
  const page = await browser.newPage();

  await page.setViewport({ width: 1920, height: 1080 });
```

答:
This works fine for me.</p>
```<code>await puppeteer.launch({
      headless: false,
      defaultViewport: null,
      args: ['--start-maximized']
});
</code>```

Body:
This works fine for me.

await puppeteer.launch({
      headless: false,
      defaultViewport: null,
      args: ['--start-maximized']
});


问:
Change order of blocks for mobile and desktop both vertically and horizontally
I am trying to create a layout which allows me change the order of elements between mobile and desktop as demonstrated by the diagram bellow:

I have ordered them in the DOM within a single container in the order as they are numbered. I'm trying to get the second item to display to the left as shown. I tried with flex but couldn't get it right. I also tried floating the second div to the left and the rest to the right, but this is messy, especially if the 4th element in right column overlaps the 3rd.

Can somebody help me with this?

Thanks

答:
This might be better suited to CSS Grid Layout and media queries.

.container {
  display: grid;
  grid-template-columns: repeat(1, 1fr);
}

@media(min-width: 375px) {
  .container {
    grid-template-rows: repeat(3, 100px);
    grid-template-columns: repeat(2, 1fr);
  }

  .child2 {
    grid-row-start: 1;
    grid-row-end: 4;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div>1</div>
  <div class="child2">2</div>
  <div>3</div>
  <div>4</div>
</div></code>```

Body:
This might be better suited to CSS Grid Layout and media queries.

.container {
  display: grid;
  grid-template-columns: repeat(1, 1fr);
}

@media(min-width: 375px) {
  .container {
    grid-template-rows: repeat(3, 100px);
    grid-template-columns: repeat(2, 1fr);
  }

  .child2 {
    grid-row-start: 1;
    grid-row-end: 4;
  }
}

<div class="container">
  <div>1</div>
  <div class="child2">2</div>
  <div>3</div>
  <div>4</div>
</div>


问:
I want to delete record from GridView.Before to this ask for confirmation like "Are you sure to delete?"
I want to delete record from GridView.Before to this ask for confirmation like "Are you sure to delete?"

I used command field in GridView,

```<code><asp:CommandField HeaderText="Delete" ShowDeleteButton="True" />
</code>```

I wrote a function in javascript

```<code>function confirm_Delete()
{
    var r = confirm("Are you sure you want to Remove this Record!");

    if (r == true)
    {
        alert("Record Deleted");
        return true;
    }
    else
    {
        return false;
    }
}
</code>```

How I will call this on delete click.
Kindly suggest !

答:
```<code>protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        ((LinkButton)e.Row.Cells[0].Controls[0]).Attributes.Add("onclick", "return Conformation();");
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I want to delete record from GridView.Before to this ask for confirmation like "Are you sure to delete?"

I used command field in GridView,

<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" />

I wrote a function in javascript

function confirm_Delete()
{
    var r = confirm("Are you sure you want to Remove this Record!");

    if (r == true)
    {
        alert("Record Deleted");
        return true;
    }
    else
    {
        return false;
    }
}

How I will call this on delete click.
Kindly suggest !


问:
How to import specific css files to components in Angular
I have a website which running on angular.But I need to declare my css files in some of components not all of them.When I import them in components some of my files does not load.Here is my file structure

---home

--components

--home

-home-footer

-home-navbar

-home-invest

--network

Im pretty sure about importing @import '../../../assets/css/responsive.css';

Im using home-footer navbar in home.component.html(in ---home)

答:
Just use styleUrls in component. you can use multiple stylesheet in style URL's</p>

```<code>@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: [ './home.component.css',
'../../../assets/css/responsive.css'
],
encapsulation: ViewEncapsulation.None })
</code>```

Body:
Just use styleUrls in component. you can use multiple stylesheet in style URL's

@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: [ './home.component.css',
'../../../assets/css/responsive.css'
],
encapsulation: ViewEncapsulation.None })


问:
Chef Elementory OS (Error executing action `install` on resource 'package[apache2]')
```<code> * package[tree] action install[2020-02-18T15:27:02+05:30] INFO: Processing package[tree] action install (starter::default line 8)

    ================================================================================
    Error executing action `install` on resource 'package[tree]'
    ================================================================================

    Chef::Exceptions::ProviderNotFound
    ----------------------------------
    Cannot find a provider for package[tree] on elementary version 5.1.2

    Resource Declaration:
    ---------------------
    # In /home/mrunknown/Downloads/chef-repo/.chef/local-mode-cache/cache/cookbooks/starter/recipes/default.rb

      8: package "tree"
      9:

    Compiled Resource:
    ------------------
    # Declared in /home/mrunknown/Downloads/chef-repo/.chef/local-mode-cache/cache/cookbooks/starter/recipes/default.rb:8:in `from_file'
</code>```

Code:

```<code>package("tree") do
  package_name "tree"
  action [:install]
  default_guard_interpreter :default
  declared_type :package
  cookbook_name "starter"
  recipe_name "default"
end
</code>```

System Info:

```<code>chef_version=15.7.32
platform=elementary
platform_version=5.1.2
ruby=ruby 2.6.5p114 (2019-10-01 revision 67812) [x86_64-linux]
program_name=/usr/bin/chef-client
executable=/opt/chef-workstation/bin/chef-client
</code>```

答:
A quick search shows that Elementary OS uses apt, so you definitely need to use apt_package.

```<code>apt_package 'tree' do
  action :install
end
</code>```

But you said it didn't work for you. I guess you encountered some apt error that said that it couldn't find a candidate for package tree. That was because you needed to run apt update before installing packages. You can do this by prepending your package resource with apt_update resource.

```<code>apt_update 'update' do
  action :update
end

apt_package 'tree' do
  action :install
end
</code>```

Body:
 * package[tree] action install[2020-02-18T15:27:02+05:30] INFO: Processing package[tree] action install (starter::default line 8)

    ================================================================================
    Error executing action `install` on resource 'package[tree]'
    ================================================================================

    Chef::Exceptions::ProviderNotFound
    ----------------------------------
    Cannot find a provider for package[tree] on elementary version 5.1.2

    Resource Declaration:
    ---------------------
    # In /home/mrunknown/Downloads/chef-repo/.chef/local-mode-cache/cache/cookbooks/starter/recipes/default.rb

      8: package "tree"
      9:

    Compiled Resource:
    ------------------
    # Declared in /home/mrunknown/Downloads/chef-repo/.chef/local-mode-cache/cache/cookbooks/starter/recipes/default.rb:8:in `from_file'

Code:

package("tree") do
  package_name "tree"
  action [:install]
  default_guard_interpreter :default
  declared_type :package
  cookbook_name "starter"
  recipe_name "default"
end

System Info:

chef_version=15.7.32
platform=elementary
platform_version=5.1.2
ruby=ruby 2.6.5p114 (2019-10-01 revision 67812) [x86_64-linux]
program_name=/usr/bin/chef-client
executable=/opt/chef-workstation/bin/chef-client

Body:
A quick search shows that Elementary OS uses apt, so you definitely need to use apt_package.

apt_package 'tree' do
  action :install
end

But you said it didn't work for you. I guess you encountered some apt error that said that it couldn't find a candidate for package tree. That was because you needed to run apt update before installing packages. You can do this by prepending your package resource with apt_update resource.

apt_update 'update' do
  action :update
end

apt_package 'tree' do
  action :install
end


问:
How to use the cadata argument in load_verify_locations?
I need to make an ssl context with an in-memory CA root certificate. I assume this is done by using the method load_verify_locations(cadata=). But whatever I try I'm getting the error "nested asn1 error (_ssl.c:2903)".

Can somebody enlighten me as to what I am doing wrong ?

It works when providing a file name. However, the file contains the very same data as the string PEM variable.

The Python script will run on an environment w/o writing access to the local file system. So I can't write the PEM string into a temporary file. Hence my requirement to pass the root certificate as a string variable. It must run on Python 2.7, using only the standard libraries.

I've tried various ways of encoding/decoding, but that didn't work out either.

The script runs on Python 2.7, on Linux Mint 19.1 amd64. openssl-python 17.5.0 is installed. openssl 1.1.1 is installed.

I've made a proof of concept script to test different cases.

First, the CA_STRING string is used for the cadata argument. Which fails.

Second, the CA_STRING string is written into cadata.pem, read back into another string variable and used for the cadata argument. Which also fails.

Third, the name of the file previously created is used for the cafile argument. Which doesn't fail.

Fourth, the strings for the first and second test are compared. Maybe there is some kind of encoding issue here.

# Proof of concept code to investigate the difference between using the cadata and cafile arguments.

import ssl

# Copy/paste from the cadata.pem file
CA_STRING = "-----BEGIN CERTIFICATE-----\n" \
            "MIIDpTCCAo2gAwIBAgIUBdwEtNtRkxog9YXLx73rcUaqwQgwDQYJKoZIhvcNAQEL" \
            "BQAwYjELMAkGA1UEBhMCQkUxETAPBgNVBAgMCEZsYW5kZXJzMRAwDgYDVQQHDAdh" \
            "bnR3ZXJwMQwwCgYDVQQKDANzc2wxDzANBgNVBAsMBnB5dGhvbjEPMA0GA1UEAwwG" \
            "Y2FkYXRhMB4XDTE5MDcxMjA2NDQwOVoXDTM5MDcwNzA2NDQwOVowYjELMAkGA1UE" \
            "BhMCQkUxETAPBgNVBAgMCEZsYW5kZXJzMRAwDgYDVQQHDAdhbnR3ZXJwMQwwCgYD" \
            "VQQKDANzc2wxDzANBgNVBAsMBnB5dGhvbjEPMA0GA1UEAwwGY2FkYXRhMIIBIjAN" \
            "BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA37p+/2uMgnaisgfxUUUPkPKLU48Q" \
            "O+Bhuyrhfb6hacCsPf6vHmGxqKrLnBA9TH/3Qi6dsMeu5AHvhFu6Y3WlnWXWRw0j" \
            "lHCOhWiFcUYxWfp1XMl2VSV5Z0dikgKQAU3H054gngQyLLPCSBtDIFQOktnD4fRc" \
            "BdmJrvxL3ebOksC5BzR3p/UqufhBDjGGZ0PKnWP2IyQUaruhWFGFJNU20GPySq0u" \
            "TLDWbuq+COzgbyEPMyuLAouOyEEC4SOKYgyWKKTvZjxQTjaKgOFGXrl1I2JNHliv" \
            "kJyT0Rdh4swqeK0PgxBDOc0TQk3i8mnOv+5xSvalSRmEfMnihUvpHAiY4QIDAQAB" \
            "o1MwUTAdBgNVHQ4EFgQUgao3ocJMrxC9eNzsJKkiNPoHxRQwHwYDVR0jBBgwFoAU" \
            "gao3ocJMrxC9eNzsJKkiNPoHxRQwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0B" \
            "AQsFAAOCAQEAZH4fiCx1whQcb9lMcWPUpfJHmE6ITs43yIijaqHI8zHoQdi3yiE8" \
            "AEVgWN2SL0O5FgeOiY0t5mRSRHoVZ409bVF60i6CrrsDsic7IQr4HjPXOs9auabT" \
            "UqqDPeZQyVrIpwYQp5Oof8DEugo39su/zOYfBnVB0bzU442RZGkp12EareBZBYdN" \
            "tLta5f1aZxyREbBy+afiY0vX6hk5PUywUvFCiSDWVcMALInMB/NmdpeCIKbeFnfC" \
            "pJ2CqLw1S2P3q1jzuu0pjre3VVlcafj0Y/FOjV1Xks0S6qzCOuvlFPil0rvEczuA" \
            "dIRqYWtpL1KtHCrIT+hijnGLaMnriJ5CDA==\n" \
            "-----END CERTIFICATE-----"

def create_ssl_context():
    context = ssl.create_default_context()
    context.verify_mode = ssl.CERT_REQUIRED
    return context

# Use the constant as input
print " (1) Making SSL context with certificate string variable .... ",
try:
    ssl_context = create_ssl_context()
    ssl_context.load_verify_locations(cadata=CA_STRING)
    print("pass")
except Exception as error:
    print(str(error))

# Use the file content as input
print " (2) Making SSL context with certificate string from file ... ",
try:
    # write the constant into a file
    with open("cadata.pem", "w") as c:
        c.write(CA_STRING)

    # read it back
    with open("cadata.pem", "r") as c:
        ca_file_string = c.read()

    ssl_context = create_ssl_context()
    ssl_context.load_verify_locations(cadata=ca_file_string)
    print("pass")
except Exception as error:
    print(str(error))

# Use the file name as input
print " (3) Making SSL context with certificate file ............... ",
try:
    ssl_context = create_ssl_context()
    ssl_context.load_verify_locations(cafile="cadata.pem")
    print("pass")
except Exception as error:
    print(str(error))

# Are the ca constant and file contents identical ?
print " (4) CA variable and file content are identical .............. " + str(CA_STRING == ca_file_string)

```

Running the provided proof of concept script yields the output:

(1) Making SSL context with certificate string variable ....  nested asn1 error (_ssl.c:2903)
 (2) Making SSL context with certificate string from file ...  nested asn1 error (_ssl.c:2903)
 (3) Making SSL context with certificate file ...............  pass
 (4) CA variable and file content are identical .............. True

I expect all the tests to pass. Especially because (3) succeeds with a file written with the very same data.

答:
This was very helpful.

The test script succeeds with Python3 (after updating for 'print()')...

```<code>$ python3 cert_from_string.py
 (1) Making SSL context with certificate string variable ....  pass
 (2) Making SSL context with certificate string from file ...  pass
 (3) Making SSL context with certificate file ...............  pass
 (4) CA variable and file content are identical .............  True
</code>```

```<code># Proof of concept code to investigate the difference between using the cadata and cafile arguments.
# https://stackoverflow.com/questions/57002351/how-to-use-the-cadata-argument-in-load-verify-locations

# updated for Python3

from __future__ import print_function
import ssl

# Copy/paste from the cadata.pem file
CA_STRING = "-----BEGIN CERTIFICATE-----\n" \
            "MIIDpTCCAo2gAwIBAgIUBdwEtNtRkxog9YXLx73rcUaqwQgwDQYJKoZIhvcNAQEL" \
            "BQAwYjELMAkGA1UEBhMCQkUxETAPBgNVBAgMCEZsYW5kZXJzMRAwDgYDVQQHDAdh" \
            "bnR3ZXJwMQwwCgYDVQQKDANzc2wxDzANBgNVBAsMBnB5dGhvbjEPMA0GA1UEAwwG" \
            "Y2FkYXRhMB4XDTE5MDcxMjA2NDQwOVoXDTM5MDcwNzA2NDQwOVowYjELMAkGA1UE" \
            "BhMCQkUxETAPBgNVBAgMCEZsYW5kZXJzMRAwDgYDVQQHDAdhbnR3ZXJwMQwwCgYD" \
            "VQQKDANzc2wxDzANBgNVBAsMBnB5dGhvbjEPMA0GA1UEAwwGY2FkYXRhMIIBIjAN" \
            "BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA37p+/2uMgnaisgfxUUUPkPKLU48Q" \
            "O+Bhuyrhfb6hacCsPf6vHmGxqKrLnBA9TH/3Qi6dsMeu5AHvhFu6Y3WlnWXWRw0j" \
            "lHCOhWiFcUYxWfp1XMl2VSV5Z0dikgKQAU3H054gngQyLLPCSBtDIFQOktnD4fRc" \
            "BdmJrvxL3ebOksC5BzR3p/UqufhBDjGGZ0PKnWP2IyQUaruhWFGFJNU20GPySq0u" \
            "TLDWbuq+COzgbyEPMyuLAouOyEEC4SOKYgyWKKTvZjxQTjaKgOFGXrl1I2JNHliv" \
            "kJyT0Rdh4swqeK0PgxBDOc0TQk3i8mnOv+5xSvalSRmEfMnihUvpHAiY4QIDAQAB" \
            "o1MwUTAdBgNVHQ4EFgQUgao3ocJMrxC9eNzsJKkiNPoHxRQwHwYDVR0jBBgwFoAU" \
            "gao3ocJMrxC9eNzsJKkiNPoHxRQwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0B" \
            "AQsFAAOCAQEAZH4fiCx1whQcb9lMcWPUpfJHmE6ITs43yIijaqHI8zHoQdi3yiE8" \
            "AEVgWN2SL0O5FgeOiY0t5mRSRHoVZ409bVF60i6CrrsDsic7IQr4HjPXOs9auabT" \
            "UqqDPeZQyVrIpwYQp5Oof8DEugo39su/zOYfBnVB0bzU442RZGkp12EareBZBYdN" \
            "tLta5f1aZxyREbBy+afiY0vX6hk5PUywUvFCiSDWVcMALInMB/NmdpeCIKbeFnfC" \
            "pJ2CqLw1S2P3q1jzuu0pjre3VVlcafj0Y/FOjV1Xks0S6qzCOuvlFPil0rvEczuA" \
            "dIRqYWtpL1KtHCrIT+hijnGLaMnriJ5CDA==\n" \
            "-----END CERTIFICATE-----"

def create_ssl_context():
    context = ssl.create_default_context()
    context.verify_mode = ssl.CERT_REQUIRED
    return context

# Use the constant as input
print(" (1) Making SSL context with certificate string variable .... ", end =" ")
try:
    ssl_context = create_ssl_context()
    ssl_context.load_verify_locations(cadata=CA_STRING)
    print("pass")
except Exception as error:
    print(str(error))

# Use the file content as input
print(" (2) Making SSL context with certificate string from file ... ", end =" ")
try:
    # write the constant into a file
    with open("cadata.pem", "w") as c:
        c.write(CA_STRING)

    # read it back
    with open("cadata.pem", "r") as c:
        ca_file_string = c.read()

    ssl_context = create_ssl_context()
    ssl_context.load_verify_locations(cadata=ca_file_string)
    print("pass")
except Exception as error:
    print(str(error))

# Use the file name as input
print(" (3) Making SSL context with certificate file ............... ", end =" ")
try:
    ssl_context = create_ssl_context()
    ssl_context.load_verify_locations(cafile="cadata.pem")
    print("pass")
except Exception as error:
    print(str(error))

# Are the ca constant and file contents identical ?
print(" (4) CA variable and file content are identical .............  " + str(CA_STRING == ca_file_string))

</code>```

Body:
I need to make an ssl context with an in-memory CA root certificate. I assume this is done by using the method load_verify_locations(cadata=). But whatever I try I'm getting the error "nested asn1 error (_ssl.c:2903)".

Can somebody enlighten me as to what I am doing wrong ?

It works when providing a file name. However, the file contains the very same data as the string PEM variable.

The Python script will run on an environment w/o writing access to the local file system. So I can't write the PEM string into a temporary file. Hence my requirement to pass the root certificate as a string variable. It must run on Python 2.7, using only the standard libraries.

I've tried various ways of encoding/decoding, but that didn't work out either.

The script runs on Python 2.7, on Linux Mint 19.1 amd64. openssl-python 17.5.0 is installed. openssl 1.1.1 is installed.

I've made a proof of concept script to test different cases.

First, the CA_STRING string is used for the cadata argument. Which fails.

Second, the CA_STRING string is written into cadata.pem, read back into another string variable and used for the cadata argument. Which also fails.

Third, the name of the file previously created is used for the cafile argument. Which doesn't fail.

Fourth, the strings for the first and second test are compared. Maybe there is some kind of encoding issue here.

# Proof of concept code to investigate the difference between using the cadata and cafile arguments.

import ssl

# Copy/paste from the cadata.pem file
CA_STRING = "-----BEGIN CERTIFICATE-----\n" \
            "MIIDpTCCAo2gAwIBAgIUBdwEtNtRkxog9YXLx73rcUaqwQgwDQYJKoZIhvcNAQEL" \
            "BQAwYjELMAkGA1UEBhMCQkUxETAPBgNVBAgMCEZsYW5kZXJzMRAwDgYDVQQHDAdh" \
            "bnR3ZXJwMQwwCgYDVQQKDANzc2wxDzANBgNVBAsMBnB5dGhvbjEPMA0GA1UEAwwG" \
            "Y2FkYXRhMB4XDTE5MDcxMjA2NDQwOVoXDTM5MDcwNzA2NDQwOVowYjELMAkGA1UE" \
            "BhMCQkUxETAPBgNVBAgMCEZsYW5kZXJzMRAwDgYDVQQHDAdhbnR3ZXJwMQwwCgYD" \
            "VQQKDANzc2wxDzANBgNVBAsMBnB5dGhvbjEPMA0GA1UEAwwGY2FkYXRhMIIBIjAN" \
            "BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA37p+/2uMgnaisgfxUUUPkPKLU48Q" \
            "O+Bhuyrhfb6hacCsPf6vHmGxqKrLnBA9TH/3Qi6dsMeu5AHvhFu6Y3WlnWXWRw0j" \
            "lHCOhWiFcUYxWfp1XMl2VSV5Z0dikgKQAU3H054gngQyLLPCSBtDIFQOktnD4fRc" \
            "BdmJrvxL3ebOksC5BzR3p/UqufhBDjGGZ0PKnWP2IyQUaruhWFGFJNU20GPySq0u" \
            "TLDWbuq+COzgbyEPMyuLAouOyEEC4SOKYgyWKKTvZjxQTjaKgOFGXrl1I2JNHliv" \
            "kJyT0Rdh4swqeK0PgxBDOc0TQk3i8mnOv+5xSvalSRmEfMnihUvpHAiY4QIDAQAB" \
            "o1MwUTAdBgNVHQ4EFgQUgao3ocJMrxC9eNzsJKkiNPoHxRQwHwYDVR0jBBgwFoAU" \
            "gao3ocJMrxC9eNzsJKkiNPoHxRQwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0B" \
            "AQsFAAOCAQEAZH4fiCx1whQcb9lMcWPUpfJHmE6ITs43yIijaqHI8zHoQdi3yiE8" \
            "AEVgWN2SL0O5FgeOiY0t5mRSRHoVZ409bVF60i6CrrsDsic7IQr4HjPXOs9auabT" \
            "UqqDPeZQyVrIpwYQp5Oof8DEugo39su/zOYfBnVB0bzU442RZGkp12EareBZBYdN" \
            "tLta5f1aZxyREbBy+afiY0vX6hk5PUywUvFCiSDWVcMALInMB/NmdpeCIKbeFnfC" \
            "pJ2CqLw1S2P3q1jzuu0pjre3VVlcafj0Y/FOjV1Xks0S6qzCOuvlFPil0rvEczuA" \
            "dIRqYWtpL1KtHCrIT+hijnGLaMnriJ5CDA==\n" \
            "-----END CERTIFICATE-----"

def create_ssl_context():
    context = ssl.create_default_context()
    context.verify_mode = ssl.CERT_REQUIRED
    return context

# Use the constant as input
print " (1) Making SSL context with certificate string variable .... ",
try:
    ssl_context = create_ssl_context()
    ssl_context.load_verify_locations(cadata=CA_STRING)
    print("pass")
except Exception as error:
    print(str(error))

# Use the file content as input
print " (2) Making SSL context with certificate string from file ... ",
try:
    # write the constant into a file
    with open("cadata.pem", "w") as c:
        c.write(CA_STRING)

    # read it back
    with open("cadata.pem", "r") as c:
        ca_file_string = c.read()

    ssl_context = create_ssl_context()
    ssl_context.load_verify_locations(cadata=ca_file_string)
    print("pass")
except Exception as error:
    print(str(error))

# Use the file name as input
print " (3) Making SSL context with certificate file ............... ",
try:
    ssl_context = create_ssl_context()
    ssl_context.load_verify_locations(cafile="cadata.pem")
    print("pass")
except Exception as error:
    print(str(error))

# Are the ca constant and file contents identical ?
print " (4) CA variable and file content are identical .............. " + str(CA_STRING == ca_file_string)

Running the provided proof of concept script yields the output:

(1) Making SSL context with certificate string variable ....  nested asn1 error (_ssl.c:2903)
 (2) Making SSL context with certificate string from file ...  nested asn1 error (_ssl.c:2903)
 (3) Making SSL context with certificate file ...............  pass
 (4) CA variable and file content are identical .............. True

I expect all the tests to pass. Especially because (3) succeeds with a file written with the very same data.

Body:
This was very helpful.

The test script succeeds with Python3 (after updating for 'print()')...

$ python3 cert_from_string.py
 (1) Making SSL context with certificate string variable ....  pass
 (2) Making SSL context with certificate string from file ...  pass
 (3) Making SSL context with certificate file ...............  pass
 (4) CA variable and file content are identical .............  True

# Proof of concept code to investigate the difference between using the cadata and cafile arguments.
# https://stackoverflow.com/questions/57002351/how-to-use-the-cadata-argument-in-load-verify-locations

# updated for Python3

from __future__ import print_function
import ssl

# Copy/paste from the cadata.pem file
CA_STRING = "-----BEGIN CERTIFICATE-----\n" \
            "MIIDpTCCAo2gAwIBAgIUBdwEtNtRkxog9YXLx73rcUaqwQgwDQYJKoZIhvcNAQEL" \
            "BQAwYjELMAkGA1UEBhMCQkUxETAPBgNVBAgMCEZsYW5kZXJzMRAwDgYDVQQHDAdh" \
            "bnR3ZXJwMQwwCgYDVQQKDANzc2wxDzANBgNVBAsMBnB5dGhvbjEPMA0GA1UEAwwG" \
            "Y2FkYXRhMB4XDTE5MDcxMjA2NDQwOVoXDTM5MDcwNzA2NDQwOVowYjELMAkGA1UE" \
            "BhMCQkUxETAPBgNVBAgMCEZsYW5kZXJzMRAwDgYDVQQHDAdhbnR3ZXJwMQwwCgYD" \
            "VQQKDANzc2wxDzANBgNVBAsMBnB5dGhvbjEPMA0GA1UEAwwGY2FkYXRhMIIBIjAN" \
            "BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA37p+/2uMgnaisgfxUUUPkPKLU48Q" \
            "O+Bhuyrhfb6hacCsPf6vHmGxqKrLnBA9TH/3Qi6dsMeu5AHvhFu6Y3WlnWXWRw0j" \
            "lHCOhWiFcUYxWfp1XMl2VSV5Z0dikgKQAU3H054gngQyLLPCSBtDIFQOktnD4fRc" \
            "BdmJrvxL3ebOksC5BzR3p/UqufhBDjGGZ0PKnWP2IyQUaruhWFGFJNU20GPySq0u" \
            "TLDWbuq+COzgbyEPMyuLAouOyEEC4SOKYgyWKKTvZjxQTjaKgOFGXrl1I2JNHliv" \
            "kJyT0Rdh4swqeK0PgxBDOc0TQk3i8mnOv+5xSvalSRmEfMnihUvpHAiY4QIDAQAB" \
            "o1MwUTAdBgNVHQ4EFgQUgao3ocJMrxC9eNzsJKkiNPoHxRQwHwYDVR0jBBgwFoAU" \
            "gao3ocJMrxC9eNzsJKkiNPoHxRQwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0B" \
            "AQsFAAOCAQEAZH4fiCx1whQcb9lMcWPUpfJHmE6ITs43yIijaqHI8zHoQdi3yiE8" \
            "AEVgWN2SL0O5FgeOiY0t5mRSRHoVZ409bVF60i6CrrsDsic7IQr4HjPXOs9auabT" \
            "UqqDPeZQyVrIpwYQp5Oof8DEugo39su/zOYfBnVB0bzU442RZGkp12EareBZBYdN" \
            "tLta5f1aZxyREbBy+afiY0vX6hk5PUywUvFCiSDWVcMALInMB/NmdpeCIKbeFnfC" \
            "pJ2CqLw1S2P3q1jzuu0pjre3VVlcafj0Y/FOjV1Xks0S6qzCOuvlFPil0rvEczuA" \
            "dIRqYWtpL1KtHCrIT+hijnGLaMnriJ5CDA==\n" \
            "-----END CERTIFICATE-----"

def create_ssl_context():
    context = ssl.create_default_context()
    context.verify_mode = ssl.CERT_REQUIRED
    return context

# Use the constant as input
print(" (1) Making SSL context with certificate string variable .... ", end =" ")
try:
    ssl_context = create_ssl_context()
    ssl_context.load_verify_locations(cadata=CA_STRING)
    print("pass")
except Exception as error:
    print(str(error))

# Use the file content as input
print(" (2) Making SSL context with certificate string from file ... ", end =" ")
try:
    # write the constant into a file
    with open("cadata.pem", "w") as c:
        c.write(CA_STRING)

    # read it back
    with open("cadata.pem", "r") as c:
        ca_file_string = c.read()

    ssl_context = create_ssl_context()
    ssl_context.load_verify_locations(cadata=ca_file_string)
    print("pass")
except Exception as error:
    print(str(error))

# Use the file name as input
print(" (3) Making SSL context with certificate file ............... ", end =" ")
try:
    ssl_context = create_ssl_context()
    ssl_context.load_verify_locations(cafile="cadata.pem")
    print("pass")
except Exception as error:
    print(str(error))

# Are the ca constant and file contents identical ?
print(" (4) CA variable and file content are identical .............  " + str(CA_STRING == ca_file_string))


问:
TextInputLayout disable animation
I am using the TextInputLayout to implement the floating label pattern. However, when I set the text programmatically on the EditText, I still get the animation of the label moving from the control to the label - the same as if the user had clicked it.

I don't want this animation though if I set it programmatically, is this possible? Here is my code:

```<code><android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/root">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText1" />

</android.support.design.widget.TextInputLayout>
</code>```

And in the onResume I do:

```<code>    TextInputLayout root = (TextInputLayout)findViewById(R.id.root);
    EditText et = (EditText)root.findViewById(R.id.editText1);
    et.setText("Actual text");
    root.setHint("Hint");
</code>```

答:
You can disable it by using</p>

```<code>app:hintAnimationEnabled="false"
</code>```

Title: TextInputLayout disable animation

Body:
I am using the TextInputLayout to implement the floating label pattern. However, when I set the text programmatically on the EditText, I still get the animation of the label moving from the control to the label - the same as if the user had clicked it.

I don't want this animation though if I set it programmatically, is this possible? Here is my code:

<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/root">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText1" />

</android.support.design.widget.TextInputLayout>

And in the onResume I do:

    TextInputLayout root = (TextInputLayout)findViewById(R.id.root);
    EditText et = (EditText)root.findViewById(R.id.editText1);
    et.setText("Actual text");
    root.setHint("Hint");

Body:
You can disable it by using

app:hintAnimationEnabled="false"


问:
Renaming object properties in an array of objects
I have the following structure:

```<code>const data = {
    invoices: [
        {
            Date: "2018-12-18T00:00:00.000Z",
            InvoiceNumber: "59"
        },
        {
            Date: "2018-12-18T00:00:00.000Z",
            InvoiceNumber: "59"
        }
    ]
};
</code>```

I am wanting to re-name all instances of InvoiceNumber to CreditNoteNumber to give me the following:

```<code>const data = {
    invoices: [
        {
            Date: "2018-12-18T00:00:00.000Z",
            CreditNoteNumber: "59"
        },
        {
            Date: "2018-12-18T00:00:00.000Z",
            CreditNoteNumber: "59"
        }
    ]
};
</code>```

I have tried various things like the following for example:

```<code>var changed = data.invoices.map(function(item) {
    return {
        ...data.invoices,
        CreditNoteNumber: item.InvoiceNumber
    };
});
</code>```

However the spread pushes CreditNoteNumber outside the object.

答:
You can use the function map along with the function Object.assign as follow:

The following approach doesn't mutate the original object

const data = {invoices: [{Date: "2018-12-18T00:00:00.000Z",InvoiceNumber: "59"},{Date: "2018-12-18T00:00:00.000Z",InvoiceNumber: "59"}]},
      result = data.invoices.map(({InvoiceNumber: CreditNoteNumber, ...items}) => Object.assign({}, items, {CreditNoteNumber}));

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

<p>If you want to mutate the original object, you can use a <code>forEach</code> instead:</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 data = {invoices: [{Date: "2018-12-18T00:00:00.000Z",InvoiceNumber: "59"},{Date: "2018-12-18T00:00:00.000Z",InvoiceNumber: "59"}]};

data.invoices.forEach((item) => {
  item.CreditNoteNumber = item.InvoiceNumber;
  delete item.InvoiceNumber;
});

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

Body:
I have the following structure:

const data = {
    invoices: [
        {
            Date: "2018-12-18T00:00:00.000Z",
            InvoiceNumber: "59"
        },
        {
            Date: "2018-12-18T00:00:00.000Z",
            InvoiceNumber: "59"
        }
    ]
};

I am wanting to re-name all instances of InvoiceNumber to CreditNoteNumber to give me the following:

const data = {
    invoices: [
        {
            Date: "2018-12-18T00:00:00.000Z",
            CreditNoteNumber: "59"
        },
        {
            Date: "2018-12-18T00:00:00.000Z",
            CreditNoteNumber: "59"
        }
    ]
};

I have tried various things like the following for example:

var changed = data.invoices.map(function(item) {
    return {
        ...data.invoices,
        CreditNoteNumber: item.InvoiceNumber
    };
});

However the spread pushes CreditNoteNumber outside the object.

Body:
You can use the function map along with the function Object.assign as follow:

The following approach doesn't mutate the original object

const data = {invoices: [{Date: "2018-12-18T00:00:00.000Z",InvoiceNumber: "59"},{Date: "2018-12-18T00:00:00.000Z",InvoiceNumber: "59"}]},
      result = data.invoices.map(({InvoiceNumber: CreditNoteNumber, ...items}) => Object.assign({}, items, {CreditNoteNumber}));

console.log(result);

If you want to mutate the original object, you can use a forEach instead:

const data = {invoices: [{Date: "2018-12-18T00:00:00.000Z",InvoiceNumber: "59"},{Date: "2018-12-18T00:00:00.000Z",InvoiceNumber: "59"}]};

data.invoices.forEach((item) => {
  item.CreditNoteNumber = item.InvoiceNumber;
  delete item.InvoiceNumber;
});

console.log(data);


问:
jQuery UI How to Open a Dialog, append to a div not the body
I'm using this simple modal dialog example here:
http://jqueryui.com/demos/dialog/modal-form.html

When the page loads, jQuery removes the dialog's div from the DOM. When the button is clicked to open the dialog, jQuery appends the dialog's div to the end of the body element.

I want to append it to a certain div, not the body. The reason is I have a large form on the page, and in the dialog is a single file input (no seperate form). I want to keep my file input in the dialog, within the same form as the rest of the fields on the page (which aren't in the dialog).

Is it possible to append the dialog to a given div or element?

答:
Such ModalDialogs are designed to not interfere in the existing DOM, so only they are appended in the body rather than you configuring where to add.

For your specific use, I would suggest to find the form inputs from Dialog when it is closed, clone them and append them to your form. You might want to convert type=text to type=hidden when you insert them into your form. That way, you can get that data submitted
with normal form submit.

Happy Coding.


问:
IdentityServer4 error when using WindowsAuthentication
I successfully followed the Deblokt tutorial on IdentityServer4 (https://deblokt.com/2020/01/24/01-identityserver4-quickstart-net-core-3-1/).  This tutorial uses the IdentityServer4 QuickstartUI.  Userid/password authentication using the AspNet Identity database is working.

I'm using the latest .Net Core (3.1), which differs slightly from the tutorial, but it is working.

Now I'm attempting to add Windows Authentication and hitting a runtime error. What befuddles me is that the error is occurring after the user is successfully authenticated by windows.  I'm running locally on a Windows 10 machine inside Visual Studio 2019 in debug mode, using Google Chrome.

Per the IdentityServer4 documentation (https://identityserver4.readthedocs.io/en/latest/topics/windows.html#using-kestrel) I added this to my Startup.cs:

services.Configure<IISServerOptions>(iis =>
{
    iis.AuthenticationDisplayName = "Windows";
    iis.AutomaticAuthentication = false;
});
```

<p>I then right-clicked the project, chose "Properties", chose the "Debug" tab, and checked "Windows Authentication":</p>

<p><img src="https://i.stack.imgur.com/iQcPb.png" alt="enter image description here"></p>

<p>This makes the "Windows" button visible when I navigate to /Account/Login:</p>

<p><img src="https://i.stack.imgur.com/Fm4ya.png" alt="enter image description here"></p>

<p>When the "Windows" button is clicked the postback is handled inside the ExternalController "Challenge" method, with "Windows" as the provider argument and "~/" for the returnUrl argument. Since the provider argument is "Windows" this method calls ProcessWindowsLoginAsync, passing the returnUrl argument.</p>

<p>The first time, ProcessWindowsLoginAsync calls HttpContext.AuthenticateAsync("Windows"), which returns a null Principal, which causes the method to re-call /External/Challenge("Windows"), which calls ProcessWindowsLoginAsync a second time, which in turn calls HttpContext.AuthenticateAsync("Windows"), and this 2nd call is successful--HttpContext.AuthenticateAsync returns a windows principal (which is me) and I can view it in the debugger and see that it has all of my particulars correct.</p>

<p>ProcessWindowsLoginAsync then makes this call:</p>

<pre class="lang-cs prettyprint-override"><code>await HttpContext.SignInAsync(
    IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme,
    new ClaimsPrincipal(id),
    props
);
</code>```

This executes without error. The "id" argument is a ClaimsIdentity with 2 claims pulled from my windows identity, Subject and Name.

At this point all appears to be well.  The method ProcessWindowsLoginAsync ends with a Redirect to /External/Callback.  This is where the error occurs.  The method /External/Callback method contains this bit of code at the top, and is throwing the exception you see.  For reasons unknown HttpContext.AuthenticateAsync is not succeeding.

var result = await HttpContext.AuthenticateAsync(IdentityConstants.ExternalScheme);
if (result?.Succeeded != true)
{
    throw new Exception("External authentication error");
}
```

The "result" object has a "Succeeded" value of false and a "None" value of true, the other properties (Principal, Properties, and Ticket) are all null.

Any advice is appreciated.

答:
The fix is to change this, on ExternalController.cs line 173:

```<code>await HttpContext.SignInAsync(
           IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme,
            new ClaimsPrincipal(id),
            props);
</code>```

To this:

```<code>await HttpContext.SignInAsync(
                IdentityConstants.ExternalScheme,
                new ClaimsPrincipal(id),
                props);
</code>```

This seems obvious in hindsight: AuthenticateAsync and SignInAsync should reference the same scheme.

After bumbling across the solution I notice that the IdentityServer4 github already has a closed bug report from March 2018, I don't know why this bug is still part of the Quickstart though: https://github.com/IdentityServer/IdentityServer4/issues/2166

Body:
I successfully followed the Deblokt tutorial on IdentityServer4 (https://deblokt.com/2020/01/24/01-identityserver4-quickstart-net-core-3-1/).  This tutorial uses the IdentityServer4 QuickstartUI.  Userid/password authentication using the AspNet Identity database is working.

I'm using the latest .Net Core (3.1), which differs slightly from the tutorial, but it is working.

Now I'm attempting to add Windows Authentication and hitting a runtime error. What befuddles me is that the error is occurring after the user is successfully authenticated by windows.  I'm running locally on a Windows 10 machine inside Visual Studio 2019 in debug mode, using Google Chrome.

Per the IdentityServer4 documentation (https://identityserver4.readthedocs.io/en/latest/topics/windows.html#using-kestrel) I added this to my Startup.cs:

services.Configure<IISServerOptions>(iis =>
{
    iis.AuthenticationDisplayName = "Windows";
    iis.AutomaticAuthentication = false;
});

I then right-clicked the project, chose "Properties", chose the "Debug" tab, and checked "Windows Authentication":

This makes the "Windows" button visible when I navigate to /Account/Login:

When the "Windows" button is clicked the postback is handled inside the ExternalController "Challenge" method, with "Windows" as the provider argument and "~/" for the returnUrl argument. Since the provider argument is "Windows" this method calls ProcessWindowsLoginAsync, passing the returnUrl argument.

The first time, ProcessWindowsLoginAsync calls HttpContext.AuthenticateAsync("Windows"), which returns a null Principal, which causes the method to re-call /External/Challenge("Windows"), which calls ProcessWindowsLoginAsync a second time, which in turn calls HttpContext.AuthenticateAsync("Windows"), and this 2nd call is successful--HttpContext.AuthenticateAsync returns a windows principal (which is me) and I can view it in the debugger and see that it has all of my particulars correct.

ProcessWindowsLoginAsync then makes this call:

await HttpContext.SignInAsync(
    IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme,
    new ClaimsPrincipal(id),
    props
);

This executes without error. The "id" argument is a ClaimsIdentity with 2 claims pulled from my windows identity, Subject and Name.

At this point all appears to be well.  The method ProcessWindowsLoginAsync ends with a Redirect to /External/Callback.  This is where the error occurs.  The method /External/Callback method contains this bit of code at the top, and is throwing the exception you see.  For reasons unknown HttpContext.AuthenticateAsync is not succeeding.

var result = await HttpContext.AuthenticateAsync(IdentityConstants.ExternalScheme);
if (result?.Succeeded != true)
{
    throw new Exception("External authentication error");
}

The "result" object has a "Succeeded" value of false and a "None" value of true, the other properties (Principal, Properties, and Ticket) are all null.

Any advice is appreciated.

Body:
The fix is to change this, on ExternalController.cs line 173:

await HttpContext.SignInAsync(
           IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme,
            new ClaimsPrincipal(id),
            props);

To this:

await HttpContext.SignInAsync(
                IdentityConstants.ExternalScheme,
                new ClaimsPrincipal(id),
                props);

This seems obvious in hindsight: AuthenticateAsync and SignInAsync should reference the same scheme.

After bumbling across the solution I notice that the IdentityServer4 github already has a closed bug report from March 2018, I don't know why this bug is still part of the Quickstart though: https://github.com/IdentityServer/IdentityServer4/issues/2166