问:
How to display nested lists like this?
I have lists nested within lists like this:

```<code><ul>
    <li><a href="#">Rings</a></li>
    <li><a href="#">Bracelets</a></li>
    <li><a href="#">Earrings</a>
        <ul>
            <li><a href="#">Diamond Earrings</a></li>
            <li><a href="#">Hoop Earrings</a></li>
            ...
        </ul>
    </li>
    <li><a href="#">Necklaces and Pendants</a>
    ...
</ul>
</code>```

The lists are floated left. The nested lists are defaulted to not be displayed. So it ends up looking like this:

This so far I have. Now what I want to do is whenever a list is hovered that has a nested list (for example Earrings). I want the nested list to be revealed like so:

Notice what all is going on here, its not just telling the nested list to be displayed, that would not look right. Its putting them in a block between the first level lists where they wrap (between "Sports Jewelry" and "Charms").

I am not sure how to go about this.

Any ideas?

答:
The easiest way I think would be to create different lists, for each line. Something like the following:

```<code><ul>
    <li><a href="#">Rings</a></li>
    <li><a href="#">Bracelets</a></li>
    <li><a href="#">Earrings</a>
        <ul>
            <li><a href="#">Diamond Earrings</a></li>
            <li><a href="#">Hoop Earrings</a></li>
            ...
        </ul>
    </li>
    <li><a href="#">Necklaces and Pendants</a>
    ...
</ul>
<ul><li><a href="#">Charms</a></li>
    <li><a href="#">Mens Jewelry</a></li>
     ....
</code>```

So when you hover a li of the first line, the inner ul will be appear above the second line according to the normal flow.

To hide the inner ul, you can use the display:none as initial state, and show it using ul li:hover {display:block; }

Title: How to display nested lists like this?

Body:
I have lists nested within lists like this:

Rings

Bracelets

Earrings

Diamond Earrings

Hoop Earrings

            ...

Necklaces and Pendants
    ...

The lists are floated left. The nested lists are defaulted to not be displayed. So it ends up looking like this:

This so far I have. Now what I want to do is whenever a list is hovered that has a nested list (for example Earrings). I want the nested list to be revealed like so:

Notice what all is going on here, its not just telling the nested list to be displayed, that would not look right. Its putting them in a block between the first level lists where they wrap (between "Sports Jewelry" and "Charms").

I am not sure how to go about this.

Any ideas?

Body:
The easiest way I think would be to create different lists, for each line. Something like the following:

<ul>
    <li><a href="#">Rings</a></li>
    <li><a href="#">Bracelets</a></li>
    <li><a href="#">Earrings</a>
        <ul>
            <li><a href="#">Diamond Earrings</a></li>
            <li><a href="#">Hoop Earrings</a></li>
            ...
        </ul>
    </li>
    <li><a href="#">Necklaces and Pendants</a>
    ...
</ul>
<ul><li><a href="#">Charms</a></li>
    <li><a href="#">Mens Jewelry</a></li>
     ....

So when you hover a li of the first line, the inner ul will be appear above the second line according to the normal flow.

To hide the inner ul, you can use the display:none as initial state, and show it using ul li:hover {display:block; }


来源: stackexchange

问:
Specify type from keyof type typescript
I have a function

```<code>newText<T, U extends keyof T>(name: keyof T, value: T[U]){...}
</code>```

If I call it with T looking like { one: Function, two: string } the types should looks like 'one' | 'two' for one and Function | string for value.

This is super close to what I want but when I specify a name I want the value to be the type of that key. So if I do newText('one', I would want to see Function as my only option for value and doing newText('two', () =>{}) should throw an error.

Is this possible in typescript 2.6?

Full use case with solution

```<code>type params = {
  util?: Function;
  utilName?: string;
  other?: string;
};

type utilParams = 'util' | 'utilName';

class field {
  name: string;
  required: boolean;
  value: any;
  params: params;
  constructor(name: string, required: boolean, value: any, params: params) {
    this.name = name;
    this.required = required;
    this.value = value;
    this.params = params;
  }
}

type coreOptional<T, U extends keyof T> = {
  required?: boolean;
  value?: T[U];
};

class test<T> {
  test<U extends keyof T>(name: keyof T, optional: coreOptional<T, U> & Partial<Pick<params, utilParams>>) {
    let onlyParams: Partial<Pick<params, utilParams>> = { ...optional };
    return new field(name, optional.required || false, optional.value, onlyParams);
  }
}

let myTest = new test<{ one: Function; two: Function }>();

myTest.test('one', { value: '' }); //works!
myTest.test('one', { value: false}); //errors like it should.
</code>```

答:
So if I do newText('one', I would want to see Function as my only option for value and doing newText('two', () =>{}) should throw an error.

Simple:

```<code>type T = { one: Function, two: string };
declare function newText<KEY extends keyof T>(name: KEY, value: T[KEY]): any;

newText('one', () => null); // Okay
newText('two', () => null); // Error
</code>```

Cheers

ContentLicense: CC BY-SA 3.0

Title: Specify type from keyof type typescript

Body:
I have a function

newText<T, U extends keyof T>(name: keyof T, value: T[U]){...}

If I call it with T looking like { one: Function, two: string } the types should looks like 'one' | 'two' for one and Function | string for value.

This is super close to what I want but when I specify a name I want the value to be the type of that key. So if I do newText('one', I would want to see Function as my only option for value and doing newText('two', () =>{}) should throw an error.

Is this possible in typescript 2.6?

Full use case with solution

type params = {
  util?: Function;
  utilName?: string;
  other?: string;
};

type utilParams = 'util' | 'utilName';

class field {
  name: string;
  required: boolean;
  value: any;
  params: params;
  constructor(name: string, required: boolean, value: any, params: params) {
    this.name = name;
    this.required = required;
    this.value = value;
    this.params = params;
  }
}

type coreOptional<T, U extends keyof T> = {
  required?: boolean;
  value?: T[U];
};

class test<T> {
  test(name: keyof T, optional: coreOptional<T, U> & Partial<Pick<params, utilParams>>) {
    let onlyParams: Partial<Pick<params, utilParams>> = { ...optional };
    return new field(name, optional.required || false, optional.value, onlyParams);
  }
}

let myTest = new test<{ one: Function; two: Function }>();

myTest.test('one', { value: '' }); //works!
myTest.test('one', { value: false}); //errors like it should.

Body:
So if I do newText('one', I would want to see Function as my only option for value and doing newText('two', () =>{}) should throw an error.

Simple:

type T = { one: Function, two: string };
declare function newText<KEY extends keyof T>(name: KEY, value: T[KEY]): any;

newText('one', () => null); // Okay
newText('two', () => null); // Error

Cheers


问:
How can I exclude unnecessary DLLs from my build?
I'm trying to optimize the file size of my game, in particular the android build. I have optimized the assets and set the build stripping level to Use micro mscorlib. However, looking at the Editor.log reveals the DLLs still take up more than 50%:

```<code> Textures      2.7 mb     35.7%
 Meshes        80.5 kb     1.0%
 Animations    0.0 kb     0.0%
 Sounds        0.8 kb     0.0%
 Shaders       98.2 kb     1.3%
 Other Assets  177.9 kb     2.3%
 Levels        110.0 kb     1.4%
 Scripts       447.4 kb     5.8%
 Included DLLs 3.9 mb     52.2%
 File headers  26.2 kb     0.3%
 Complete size 7.5 mb     100.0%
</code>```

3.9mb seemed a bit much, so I looked at which DLLs are actually added. I found this:

```<code> Mono dependencies included in the build
 Dependency assembly - Mono.Security.dll
 Dependency assembly - System.Core.dll
 Dependency assembly - System.dll
 Dependency assembly - mscorlib.dll
 Dependency assembly - UnityEngine.UI.dll
 Dependency assembly - UnityEngine.Networking.dll
 Dependency assembly - UnityEngine.Analytics.dll
 Dependency assembly - Assembly-CSharp.dll
 Dependency assembly - Assembly-UnityScript-firstpass.dll
 Dependency assembly - Assembly-UnityScript.dll
</code>```

This looks like it can be improved quite a bit. I don't use UnitScript, so Assembly-UnityScript-firstpass.dll and Assembly-UnityScript.dll should be obsolete. Neither do I use Networking or Analytics, so these could be removed as well. Not sure what Mono.Security.dll does or whether UnityEngine.UI.dll is really necessarry.
So, knowing this, how can I get rid of these seemingly unnecessary DLLs?

答:
There is another way of doing this:

Step 1: Right-click on the .apk file and Open it with WinRAR/ZIP

Step 2: Enter the assets folder, then enter bin\Data\Managed

Step 3: There you will find all the DLLs, just remove what you want (not that much :D)

Body:
I'm trying to optimize the file size of my game, in particular the android build. I have optimized the assets and set the build stripping level to Use micro mscorlib. However, looking at the Editor.log reveals the DLLs still take up more than 50%:

 Textures      2.7 mb     35.7%
 Meshes        80.5 kb     1.0%
 Animations    0.0 kb     0.0%
 Sounds        0.8 kb     0.0%
 Shaders       98.2 kb     1.3%
 Other Assets  177.9 kb     2.3%
 Levels        110.0 kb     1.4%
 Scripts       447.4 kb     5.8%
 Included DLLs 3.9 mb     52.2%
 File headers  26.2 kb     0.3%
 Complete size 7.5 mb     100.0%

3.9mb seemed a bit much, so I looked at which DLLs are actually added. I found this:

 Mono dependencies included in the build
 Dependency assembly - Mono.Security.dll
 Dependency assembly - System.Core.dll
 Dependency assembly - System.dll
 Dependency assembly - mscorlib.dll
 Dependency assembly - UnityEngine.UI.dll
 Dependency assembly - UnityEngine.Networking.dll
 Dependency assembly - UnityEngine.Analytics.dll
 Dependency assembly - Assembly-CSharp.dll
 Dependency assembly - Assembly-UnityScript-firstpass.dll
 Dependency assembly - Assembly-UnityScript.dll

This looks like it can be improved quite a bit. I don't use UnitScript, so Assembly-UnityScript-firstpass.dll and Assembly-UnityScript.dll should be obsolete. Neither do I use Networking or Analytics, so these could be removed as well. Not sure what Mono.Security.dll does or whether UnityEngine.UI.dll is really necessarry.
So, knowing this, how can I get rid of these seemingly unnecessary DLLs?


问:
Cartesian product using python without itertools
I came across this nice line of python code for cartesian product of n number of lists that I would like to bring back on multiple lines :

```<code>def cart_product_1(*seqs):
    if not seqs:
        return [[]]
    else:
        return [[x] + p for x in seqs[0] for p in cart_product_1(*seqs[1:])]
</code>```

This seemed pretty straightforward to me, but obviously I'm missing something here. I'm thinking I need to append a list somewhere but can't quite figure it out.

```<code>def cart_product_1(result,*seqs):
    if not seqs:
        return [[]]
    else:
        for x in seqs[0]:
            for p in cart_product_1(result,*seqs[1:]):
                 result.append([x]+p)
        return result
</code>```

This leads to a MemoryError.

答:
The line in your example is a list comprehension. Basically, the one line is constructing a list and calculating its members.

To do the same thing, you have to add an initializer and return:

```<code>result = []
for x in seqs[0]:
    for p in cart_product_1(*seqs[1:]):
        result.append([x]+p)
return result
</code>```

Body:
I came across this nice line of python code for cartesian product of n number of lists that I would like to bring back on multiple lines :

def cart_product_1(*seqs):
    if not seqs:
        return [[]]
    else:
        return [[x] + p for x in seqs[0] for p in cart_product_1(*seqs[1:])]

This seemed pretty straightforward to me, but obviously I'm missing something here. I'm thinking I need to append a list somewhere but can't quite figure it out.

def cart_product_1(result,*seqs):
    if not seqs:
        return [[]]
    else:
        for x in seqs[0]:
            for p in cart_product_1(result,*seqs[1:]):
                 result.append([x]+p)
        return result

This leads to a MemoryError.

Body:
The line in your example is a list comprehension. Basically, the one line is constructing a list and calculating its members.

To do the same thing, you have to add an initializer and return:

result = []
for x in seqs[0]:
    for p in cart_product_1(*seqs[1:]):
        result.append([x]+p)
return result


问:
What has replaced Application.CaptureScreenshot in Unity
My goal is to convert a block of text that is on the screen into an image and save it to the user's gallery (or downloads folder, or anywhere on there phone that allows them access to it)<br>
On searching through the many many threads on this subject it seems the best way is to take a screenshot with the "camera".
However, the manual tells me to use Application.CaptureScreenshot but in unity it says that is depreciated.
All i can find on searching for alternatives are paid for assets (seems dodgy for something that should be so simple) and examples of using Application.CaptureScreenshot </p>

答: ScreenCapture.CaptureScreenshot is what you are looking for now.</p>

Body:
My goal is to convert a block of text that is on the screen into an image and save it to the user's gallery (or downloads folder, or anywhere on there phone that allows them access to it)

On searching through the many many threads on this subject it seems the best way is to take a screenshot with the "camera".
However, the manual tells me to use Application.CaptureScreenshot but in unity it says that is depreciated.
All i can find on searching for alternatives are paid for assets (seems dodgy for something that should be so simple) and examples of using Application.CaptureScreenshot


问:
Remove buttons that are added at runtime
I have a view that allows buttons to be created and added to at runtime.

This seems to be working correctly.

I have a series of background images that are cycled through the application when the user clicks a button on the main form.

This works fine, but the buttons that are added at runtime need to be removed whenever the user switches background images.

How do I remove the buttons that were added at runtime?

答:
If you want to remove all of them:

```<code>for (UIButton* button in [[viewWithButtonsInIt.subviews copy] autorelease]) {
    if ([button.currentTitle hasPrefix:@"Prefix"]) { //or whatever condition you need
        [button removeFromSuperview];
    }
}
</code>```

If the view contains other subviews, keep a list of the added buttons and enumerate over that instead.

ContentLicense: CC BY-SA 2.5

Body:
If you want to remove all of them:

for (UIButton* button in [[viewWithButtonsInIt.subviews copy] autorelease]) {
    if ([button.currentTitle hasPrefix:@"Prefix"]) { //or whatever condition you need
        [button removeFromSuperview];
    }
}

If the view contains other subviews, keep a list of the added buttons and enumerate over that instead.


问:
How to count distinct values that all satisfy a condition in MySQL?
I'm trying to write a query to find distinct values in a particular field, count the number of occurrences of that value where for all instances of that particular value another column value is satisfied, and then display the results as follows (more explanation to follow):

Example db:

```<code>RowId    Status       MemberIdentifier
-----    ------       ----------------
1       In Progress   111111111
2       Complete      123456789
3       Not Started   146782452
4       Complete      111111111
5       Complete      123456789
6       Not Started   146782452
7       Complete      111111111
</code>```

Desired Result:

```<code>Status         MemberIdentifierCount
------         ----------------------
Not Started    1
In Progress    1
Complete       1
</code>```

In the above query, the number of distinct MemberIdentifiers with a given Status are counted and displayed. If a MemberIdentifier has two rows with Status 'Complete' but one with Status 'In Progress,' it is grouped and counted as in progress (i.e., MemberIdentifier= 111111111). For a MemberIdentifier to be grouped and counted as complete, all of its rows must have a Status of 'Complete' (i.e., MemberIdentifier= 123456789). Any insight would be appreciated (MySQL newbie).

答:
If the order of precedence for status is

```<code> Not Started
 In Progress
 Complete
</code>```

We can use a shortcut...

```<code>   SELECT t.memberIdentifier
        , MAX(t.status) AS status
     FROM mytable t
    GROUP BY t.MemberIdentifier
</code>```

That gets us the distinct memberIdentifier.

If there are any rows for a member that has rows in 'In Progress' and 'Complete' status, the query will return 'In Progress' as the status.

We will get status 'Complete' returned for a member only if that member does not have any rows with a status greater than 'Complete'.

To get counts from that result, we can reference that query as an inline view:

```<code> SELECT q.status
      , COUNT(q.memberIdentifier)
   FROM (
          SELECT t.memberIdentifier
               , MAX(t.status) AS status
            FROM mytable t
           GROUP BY t.MemberIdentifier
        ) q
  ORDER BY q.status
</code>```

Think of if this way... MySQL runs the query between the parens first (MySQL calls this a "derived table". The results from the query is a set of rows which can be queried like a table.

We could do a COUNT(DISTINCT q.memberIdentifier) or, assuming memberIdentifier is guaranteed to be non-NULL, we could do COUNT(1) or SUM(1) and get an equivalent result. (The GROUP BY in the inline view guarantees us that memberIdentifier will be unique.)

In the more general case, where we don't have a convenient shortcut of alphabetic ordering for the precedence of the status... we could use an expression that returns values that are "in order". That makes the query a bit more complicated, but it would work the same.

We could replace t.status with something like this:

```<code>  CASE t.status
  WHEN 'Complete'    THEN 1
  WHEN 'In Progress' THEN 2
  WHEN 'Not Started' THEN 3
  ELSE 4
  END AS `status_priority`
</code>```

And replace q.status with something the inverse, to convert back to strings:

```<code>  CASE q.status_priority
  WHEN 1 THEN 'Complete'
  WHEN 2 THEN 'In Progress'
  WHEN 3 THEN 'Not Started'
  ELSE NULL
  END AS `status`
</code>```

We'd need to decide how we would handle values of status that aren't one of the three... are those going to be ignored, handled as a higher or lower priority than any of the others. (A test case would be rows with status = 'Unknown' and rows with status = 'Abracadabra.

Body:
I'm trying to write a query to find distinct values in a particular field, count the number of occurrences of that value where for all instances of that particular value another column value is satisfied, and then display the results as follows (more explanation to follow):

Example db:

RowId    Status       MemberIdentifier
-----    ------       ----------------
1       In Progress   111111111
2       Complete      123456789
3       Not Started   146782452
4       Complete      111111111
5       Complete      123456789
6       Not Started   146782452
7       Complete      111111111

Desired Result:

Status         MemberIdentifierCount
------         ----------------------
Not Started    1
In Progress    1
Complete       1

In the above query, the number of distinct MemberIdentifiers with a given Status are counted and displayed. If a MemberIdentifier has two rows with Status 'Complete' but one with Status 'In Progress,' it is grouped and counted as in progress (i.e., MemberIdentifier= 111111111). For a MemberIdentifier to be grouped and counted as complete, all of its rows must have a Status of 'Complete' (i.e., MemberIdentifier= 123456789). Any insight would be appreciated (MySQL newbie).

Body:
If the order of precedence for status is

 Not Started
 In Progress
 Complete

We can use a shortcut...

   SELECT t.memberIdentifier
        , MAX(t.status) AS status
     FROM mytable t
    GROUP BY t.MemberIdentifier

That gets us the distinct memberIdentifier.

If there are any rows for a member that has rows in 'In Progress' and 'Complete' status, the query will return 'In Progress' as the status.

We will get status 'Complete' returned for a member only if that member does not have any rows with a status greater than 'Complete'.

To get counts from that result, we can reference that query as an inline view:

 SELECT q.status
      , COUNT(q.memberIdentifier)
   FROM (
          SELECT t.memberIdentifier
               , MAX(t.status) AS status
            FROM mytable t
           GROUP BY t.MemberIdentifier
        ) q
  ORDER BY q.status

Think of if this way... MySQL runs the query between the parens first (MySQL calls this a "derived table". The results from the query is a set of rows which can be queried like a table.

We could do a COUNT(DISTINCT q.memberIdentifier) or, assuming memberIdentifier is guaranteed to be non-NULL, we could do COUNT(1) or SUM(1) and get an equivalent result. (The GROUP BY in the inline view guarantees us that memberIdentifier will be unique.)

In the more general case, where we don't have a convenient shortcut of alphabetic ordering for the precedence of the status... we could use an expression that returns values that are "in order". That makes the query a bit more complicated, but it would work the same.

We could replace t.status with something like this:

  CASE t.status
  WHEN 'Complete'    THEN 1
  WHEN 'In Progress' THEN 2
  WHEN 'Not Started' THEN 3
  ELSE 4
  END AS `status_priority`

And replace q.status with something the inverse, to convert back to strings:

  CASE q.status_priority
  WHEN 1 THEN 'Complete'
  WHEN 2 THEN 'In Progress'
  WHEN 3 THEN 'Not Started'
  ELSE NULL
  END AS `status`

We'd need to decide how we would handle values of status that aren't one of the three... are those going to be ignored, handled as a higher or lower priority than any of the others. (A test case would be rows with status = 'Unknown' and rows with status = 'Abracadabra.


问:
Equivalent of `type -a` in Powershell
I am attempting to build my PowerShell troubleshooting skills, and I was hoping to find a similar tool to type in bash.

Example usage of type:

```<code>17:07 Mac Shell: Git/>$ type -a shell_session_save
shell_session_save is a function
shell_session_save ()
{
    if [ -n "$SHELL_SESSION_FILE" ]; then
        echo -n 'Saving session...';
        ( umask 077;
        echo 'echo Restored session: "$(date -r '$(date +%s)')"' >|"$SHELL_SESSION_FILE" );
        declare -F shell_session_save_user_state > /dev/null && shell_session_save_user_state;
        shell_session_history_allowed && shell_session_save_history;
        echo 'completed.';
    fi
}
17:07 Mac Shell: Git/>$
</code>```

I just want an easy way to view function code in PowerShell's CLI.  Is this possible natively?

Thanks for any help.

答:
It is available natively using Get-Command as such:

```<code>Get-Command MyFunctionName -ShowCommandInfo
</code>```

Here's the output of one of my functions that I keep on hand named Get-OutputFilePath:

```<code>Name          : Get-OutputFilePath
ModuleName    :
Module        : @{Name=}
CommandType   : Function
Definition    :
                [CmdletBinding()]
                Param(
                    [String]$Filter = "All Files (*.*)|*.*",
                    [String]$InitialDirectory,
                    [Parameter(ValueFromPipelineByPropertyName,ValueFromPipeline)]
                    [Alias('DefaultFileName')]
                    [String]$FullName,
                    [Switch]$Force)
                    BEGIN{
                        [void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")
                    }
                    PROCESS{
                        If($FullName -match "\\.+$" -and !$InitialDirectory){$InitialDirectory = Split-Path $FullName;$FullName = Split-Path $FullName -Leaf}ElseIf(!$InitialDirectory){$InitialDirectory=[Environment]::GetFolderPath('Desktop')}
                        $SaveFileDialog = New-Object System.Windows.Forms.SaveFileDialog
                        $SaveFileDialog.initialDirectory = $InitialDirectory
                        Try{$SaveFileDialog.filter = $Filter}Catch{Throw $_;Break}
                        $SaveFileDialog.FileName = $FullName
                        $SaveFileDialog.OverwritePrompt = !$Force
                        If($SaveFileDialog.ShowDialog() -eq "OK"){$SaveFileDialog.FileName}
                    }

ParameterSets : {@{Name=__AllParameterSets; IsDefault=False; Parameters=System.Management.Automation.PSObject[]}}
</code>```

Title: Equivalent of `type -a` in Powershell

Body:
I am attempting to build my PowerShell troubleshooting skills, and I was hoping to find a similar tool to type in bash.

Example usage of type:

17:07 Mac Shell: Git/>$ type -a shell_session_save
shell_session_save is a function
shell_session_save ()
{
    if [ -n "$SHELL_SESSION_FILE" ]; then
        echo -n 'Saving session...';
        ( umask 077;
        echo 'echo Restored session: "$(date -r '$(date +%s)')"' >|"$SHELL_SESSION_FILE" );
        declare -F shell_session_save_user_state > /dev/null && shell_session_save_user_state;
        shell_session_history_allowed && shell_session_save_history;
        echo 'completed.';
    fi
}
17:07 Mac Shell: Git/>$

I just want an easy way to view function code in PowerShell's CLI.  Is this possible natively?

Thanks for any help.

Body:
It is available natively using Get-Command as such:

Get-Command MyFunctionName -ShowCommandInfo

Here's the output of one of my functions that I keep on hand named Get-OutputFilePath:

Name          : Get-OutputFilePath
ModuleName    :
Module        : @{Name=}
CommandType   : Function
Definition    :
                [CmdletBinding()]
                Param(
                    [String]$Filter = "All Files (*.*)|*.*",
                    [String]$InitialDirectory,
                    [Parameter(ValueFromPipelineByPropertyName,ValueFromPipeline)]
                    [Alias('DefaultFileName')]
                    [String]$FullName,
                    [Switch]$Force)
                    BEGIN{
                        [void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")
                    }
                    PROCESS{
                        If($FullName -match "\\.+$" -and !$InitialDirectory){$InitialDirectory = Split-Path $FullName;$FullName = Split-Path $FullName -Leaf}ElseIf(!$InitialDirectory){$InitialDirectory=[Environment]::GetFolderPath('Desktop')}
                        $SaveFileDialog = New-Object System.Windows.Forms.SaveFileDialog
                        $SaveFileDialog.initialDirectory = $InitialDirectory
                        Try{$SaveFileDialog.filter = $Filter}Catch{Throw $_;Break}
                        $SaveFileDialog.FileName = $FullName
                        $SaveFileDialog.OverwritePrompt = !$Force
                        If($SaveFileDialog.ShowDialog() -eq "OK"){$SaveFileDialog.FileName}
                    }

ParameterSets : {@{Name=__AllParameterSets; IsDefault=False; Parameters=System.Management.Automation.PSObject[]}}


问:
Javascript conditional click event running multiple times
I have an HTML select that is meant to influence my Javascript click event. While my code technically works, I am unsure why my click event runs in the corresponding times that I change my select box value.

Say I change the option select to anything that isn't --. If I then click on the text labeled donate then on my console log there is a text Michael. Now, if I switch the option value to another value that isn'
t --, and click on donate again, then my console runs my click event 2 times. And if I repeat this process again my click event runs 3 times.

My example is going to seem a bit nonsensical, but hopefully the point is clear.

var changing = document.getElementById("changing");
var donate = document.getElementsByClassName("donate");
changing.addEventListener('change', function() {
  if (this.value !== "--") {
    for (i = 0; i < donate.length; i++) {
      donate[i].addEventListener('click', function() {
        console.log("Michael");
      });
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id="changing">
 <option value="--">--</option>
 <option value="vegetarian">Vegetarian</option>
 <option value="technical">Technical</option>
 <option value="shoes">Shoes</option>
</select>
<p class="donate">Donate</p>
<p class="donate">Donate</p>
<p class="donate">Donate</p></code>```

To clarify, if I do an option change once, then clicking on any donate text leads to my console adding the text Michael one time. If I change it again, it multiplies this into 2, leading to 3 shows of Michael. Change again, and it adds 3, leading to 6 times console logging Michael.

This indicates to me that my function is running these many times whenever I click on the donate text. How would I reformat to where my function is only run once after each option change? Or is there something fundamental that I am completely missing?

答:
Is this closer to what you are trying to accomplish?

```<code>var changing = document.getElementById("changing");
var donate = document.getElementsByClassName("donate");
var flag = false;

function log() {
    console.log("Michael");
}

changing.addEventListener('change', function() {
  if (this.value !== "--" && !flag) {
    flag = true;
    for (i = 0; i < donate.length; i++) {
      donate[i].addEventListener('click', log );
    }
  }
  else if(this.value == "--") {
    flag = false;
    console.log("+++")
    for (i = 0; i < donate.length; i++) {
      donate[i].removeEventListener('click', log );
    }
  }
});
</code>```

.

```<code><select id="changing">
    <option value="--">--</option>
    <option value="vegetarian">Vegetarian</option>
    <option value="technical">Technical</option>
    <option value="shoes">Shoes</option>
</select>
<p class="donate">Donate</p>
<p class="donate">Donate</p>
<p class="donate">Donate</p>
</code>```

Note, event listeners need to be attached only once. So, consider what it is the code is actually trying to accomplish.

Body:
I have an HTML select that is meant to influence my Javascript click event. While my code technically works, I am unsure why my click event runs in the corresponding times that I change my select box value.

Say I change the option select to anything that isn't --. If I then click on the text labeled donate then on my console log there is a text Michael. Now, if I switch the option value to another value that isn'
t --, and click on donate again, then my console runs my click event 2 times. And if I repeat this process again my click event runs 3 times.

My example is going to seem a bit nonsensical, but hopefully the point is clear.

var changing = document.getElementById("changing");
var donate = document.getElementsByClassName("donate");
changing.addEventListener('change', function() {
  if (this.value !== "--") {
    for (i = 0; i < donate.length; i++) {
      donate[i].addEventListener('click', function() {
        console.log("Michael");
      });
    }
  }
});

<select id="changing">
 <option value="--">--</option>
 <option value="vegetarian">Vegetarian</option>
 <option value="technical">Technical</option>
 <option value="shoes">Shoes</option>
</select>

Donate

Donate

Donate

To clarify, if I do an option change once, then clicking on any donate text leads to my console adding the text Michael one time. If I change it again, it multiplies this into 2, leading to 3 shows of Michael. Change again, and it adds 3, leading to 6 times console logging Michael.

This indicates to me that my function is running these many times whenever I click on the donate text. How would I reformat to where my function is only run once after each option change? Or is there something fundamental that I am completely missing?

Body:
Is this closer to what you are trying to accomplish?

var changing = document.getElementById("changing");
var donate = document.getElementsByClassName("donate");
var flag = false;

function log() {
    console.log("Michael");
}

changing.addEventListener('change', function() {
  if (this.value !== "--" && !flag) {
    flag = true;
    for (i = 0; i < donate.length; i++) {
      donate[i].addEventListener('click', log );
    }
  }
  else if(this.value == "--") {
    flag = false;
    console.log("+++")
    for (i = 0; i < donate.length; i++) {
      donate[i].removeEventListener('click', log );
    }
  }
});

.

<select id="changing">
    <option value="--">--</option>
    <option value="vegetarian">Vegetarian</option>
    <option value="technical">Technical</option>
    <option value="shoes">Shoes</option>
</select>
<p class="donate">Donate</p>
<p class="donate">Donate</p>
<p class="donate">Donate</p>

Note, event listeners need to be attached only once. So, consider what it is the code is actually trying to accomplish.


问:
Event Handler Use
Is there a way to have a function executed when an automated script is completed, as opposed to having the function initiated in response to a user's action, such as mouse movement?</p>

答:
```<code>function nameoffunction(){
    //code in this function will be done after the window loads
    alert("hi");
}

window.onload=function(){
    var alignarray=['left','center','right'];
    var elem=document.getElementById('text-content');
    elem.style.textAlign=alignarray[Math.round(Math.random()*2)];
    nameoffunction();
}
</code>```

Title: Event Handler Use


问:
Error 400 when trying to Connect Azure Function App to Azure Cosmos DB Table
I am trying to connect to azure CosmosDB Table from function app.

I am getting the error

The remote server returned an error: (400) Bad Request.

When trying to perform the same connection from the sample c# project in visual studio, it works fine.

Code Snippet:

```<code>string connectionString = ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString;
CloudStorageAccount storageAccount = CreateStorageAccountFromConnectionString(connectionString);

CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
CloudTable table = tableClient.GetTableReference("People");

table.CreateIfNotExists();
</code>```

The connection string is:

DefaultEndpointsProtocol=https;AccountName=digital-signature-db;AccountKey=XXX==;TableEndpoint=https://digital-signature-db.documents.azure.com

Full error stack:

Exception while executing function: Functions.SignPDF
  Microsoft.Azure.WebJobs.Host.FunctionInvocationException : Exception while executing function: Functions.SignPDF ---> System.AggregateException : One or more errors occurred. ---> The remote server returned an error: (400) Bad Request. ---> The remote server returned an error: (400) Bad Request.
     at Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.GetTaskResult(Task task) at C:\projects\azure-webjobs-sdk-script\src\WebJobs.Script\Description\DotNet\DotNetFunctionInvoker.cs : 453
     at Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.<>c.b__26_0(Task t) at C:\projects\azure-webjobs-sdk-script\src\WebJobs.Script\Description\DotNet\DotNetFunctionInvoker.cs : 276
     at System.Threading.Tasks.ContinuationResultTaskFromTask1.InnerInvoke()
     at System.Threading.Tasks.Task.Execute()
     at async Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.InvokeCore(Object[] parameters,FunctionInvocationContext context) at C:\projects\azure-webjobs-sdk-script\src\WebJobs.Script\Description\DotNet\DotNetFunctionInvoker.cs : 276
     at async Microsoft.Azure.WebJobs.Script.Description.FunctionInvokerBase.Invoke(Object[] parameters) at C:\projects\azure-webjobs-sdk-script\src\WebJobs.Script\Description\FunctionInvokerBase.cs : 90
     at async Microsoft.Azure.WebJobs.Host.Executors.VoidTaskMethodInvoker2.InvokeAsync[TReflected,TReturnType](TReflected instance,Object[] arguments)
     at async Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker`2.InvokeAsync[TReflected,TReturnValue](Object instance,Object[] arguments)
     at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.InvokeAsync(IFunctionInvoker invoker,ParameterHelper parameterHelper,CancellationTokenSource timeoutTokenSource,CancellationTokenSource functionCancellationTokenSource,Boolean throwOnTimeout,TimeSpan timerInterval,IFunctionInstance instance)
     at async Microsoft.Azure.WebJobs.Host.Ex…

Please Advice.

答: The CreateIfNotExists call requires a reference to WindowsAzure.Storage-PremiumTable.  When referenced in a console app, it will replace the Microsoft.WindowsAzure.Storage.dll with the version 1.0.9.1.  This is not supported by Azure Functions at this point.  Kindly raise an issue with CosmosDB team on this issue.  We have an issue tracking this at https://github.com/Azure/azure-webjobs-sdk-script/issues/2026#issuecomment-343910660

Body:
I am trying to connect to azure CosmosDB Table from function app.

I am getting the error

The remote server returned an error: (400) Bad Request.

When trying to perform the same connection from the sample c# project in visual studio, it works fine.

Code Snippet:

string connectionString = ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString;
CloudStorageAccount storageAccount = CreateStorageAccountFromConnectionString(connectionString);

CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
CloudTable table = tableClient.GetTableReference("People");

table.CreateIfNotExists();

The connection string is:

DefaultEndpointsProtocol=https;AccountName=digital-signature-db;AccountKey=XXX==;TableEndpoint=https://digital-signature-db.documents.azure.com

Full error stack:

Exception while executing function: Functions.SignPDF
  Microsoft.Azure.WebJobs.Host.FunctionInvocationException : Exception while executing function: Functions.SignPDF ---> System.AggregateException : One or more errors occurred. ---> The remote server returned an error: (400) Bad Request. ---> The remote server returned an error: (400) Bad Request.
     at Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.GetTaskResult(Task task) at C:\projects\azure-webjobs-sdk-script\src\WebJobs.Script\Description\DotNet\DotNetFunctionInvoker.cs : 453
     at Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.<>c.b__26_0(Task t) at C:\projects\azure-webjobs-sdk-script\src\WebJobs.Script\Description\DotNet\DotNetFunctionInvoker.cs : 276
     at System.Threading.Tasks.ContinuationResultTaskFromTask1.InnerInvoke()
     at System.Threading.Tasks.Task.Execute()
     at async Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.InvokeCore(Object[] parameters,FunctionInvocationContext context) at C:\projects\azure-webjobs-sdk-script\src\WebJobs.Script\Description\DotNet\DotNetFunctionInvoker.cs : 276
     at async Microsoft.Azure.WebJobs.Script.Description.FunctionInvokerBase.Invoke(Object[] parameters) at C:\projects\azure-webjobs-sdk-script\src\WebJobs.Script\Description\FunctionInvokerBase.cs : 90
     at async Microsoft.Azure.WebJobs.Host.Executors.VoidTaskMethodInvoker2.InvokeAsync[TReflected,TReturnType](TReflected instance,Object[] arguments)
     at async Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker`2.InvokeAsync[TReflected,TReturnValue](Object instance,Object[] arguments)
     at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.InvokeAsync(IFunctionInvoker invoker,ParameterHelper parameterHelper,CancellationTokenSource timeoutTokenSource,CancellationTokenSource functionCancellationTokenSource,Boolean throwOnTimeout,TimeSpan timerInterval,IFunctionInstance instance)
     at async Microsoft.Azure.WebJobs.Host.Ex…

Please Advice.


问:
iOS Firebase get data where value equals to something
How can I get data in swift3 from firebase where the value equals something.

In MySQL that would be "SELECT * FROM users WHERE type = 'brown'"; how can I write that where part in Firebase?

I have this DB

And I want to get all the data from it where month == currentMonth (I have a currentMonth variable)

答:
You can Query like this:

```<code>let ref = Database.database().reference()
ref.child("Budget")
    .queryOrdered(byChild: "Month")
    .queryEqual(toValue: "November")
    .observe(.value, with: { (snapshot: DataSnapshot) in

        var array:[Budget] = []

        for budgetChild in snapshot.children {
            let budgetSnapshot = budgetChild as! DataSnapshot
            let budgetDictionary = budgetSnapshot.value as! [String:String]

            let budget: Budget = Budget()
            budget.description_ = budgetDictionary["Description"]
            budget.month = budgetDictionary["Month"]
            budget.type = budgetDictionary["Type"]
            budget.value = budgetDictionary["Value"]

            array.append(budget)
        }
    })
</code>```

Body:
You can Query like this:

let ref = Database.database().reference()
ref.child("Budget")
    .queryOrdered(byChild: "Month")
    .queryEqual(toValue: "November")
    .observe(.value, with: { (snapshot: DataSnapshot) in

        var array:[Budget] = []

        for budgetChild in snapshot.children {
            let budgetSnapshot = budgetChild as! DataSnapshot
            let budgetDictionary = budgetSnapshot.value as! [String:String]

            let budget: Budget = Budget()
            budget.description_ = budgetDictionary["Description"]
            budget.month = budgetDictionary["Month"]
            budget.type = budgetDictionary["Type"]
            budget.value = budgetDictionary["Value"]

            array.append(budget)
        }
    })


问:
Python list manipulation and comparison of lists
I am having a bit of trouble working out some code to update ranking points for player scores in a game with the use of lists. The first list I have is a list of positions that the players came in, for example:

```<code>results = [P2, P4, P3, P1, P5, P6]
</code>```

This list is in descending order (P2 came first, P4 came second etc) and is determined by other code that I have in the program. The second list I have is a list of ranking points that I want to assign to each player based on their position:

```<code>rankingPoints = [100, 50, 25, 10, 5, 0]
</code>```

(P2 would get 100, P4 would get 50, etc)

Lastly, I have a third list that contains nested lists for each player:

```<code>playerRank = [[P1], [P2], [P3], [P4], [P5], [P6]]
</code>```

Basically what I'm wanting to do is initialize each player in the 'playerRank' list with '0' ranking score (The players are read into the list from a csv file and I cannot initialize them with '0' manually) so that it looks something like this: [[P1, 0], [P2, 0], [P3, 0]] etc.

Then based on their position in the game, add the appropriate amount of ranking score to their current ranking score (there will be multiple games so ranking score will be constantly added on top of current ranking score for players), the desired outcome will look something like:

```<code>playerRank = [[P1, 10] [P2, 100], [P3, 25], [P4, 50], [P5, 5], [P6, 0]]
</code>```

Any help on this would be greatly appreciated as I am new to programming and struggling to work out the code and logic behind it

Thanks

答:
You can use a defaultdict to update the scores and zip to create the game results:

```<code>from collections import defaultdict
results = ['P2', 'P4', 'P3', 'P1', 'P5', 'P6']
rankingPoints = [100, 50, 25, 10, 5, 0]
d = defaultdict(int)
for a, b in zip(results, rankingPoints):
   d[a] += b

final_results = [[a, b] for a, b in sorted(d.items(), key=lambda x:x[0])]
</code>```

Output:

```<code>[['P1', 10], ['P2', 100], ['P3', 25], ['P4', 50], ['P5', 5], ['P6', 0]]
</code>```

While you could just use sorted(zip(results, rankingPoints), key=lambda x:x[0]) to achieve the final output, the dictionary will allow you to increment the scores for each player later on in the program.

Body:
I am having a bit of trouble working out some code to update ranking points for player scores in a game with the use of lists. The first list I have is a list of positions that the players came in, for example:

results = [P2, P4, P3, P1, P5, P6]

This list is in descending order (P2 came first, P4 came second etc) and is determined by other code that I have in the program. The second list I have is a list of ranking points that I want to assign to each player based on their position:

rankingPoints = [100, 50, 25, 10, 5, 0]

(P2 would get 100, P4 would get 50, etc)

Lastly, I have a third list that contains nested lists for each player:

playerRank = [[P1], [P2], [P3], [P4], [P5], [P6]]

Basically what I'm wanting to do is initialize each player in the 'playerRank' list with '0' ranking score (The players are read into the list from a csv file and I cannot initialize them with '0' manually) so that it looks something like this: [[P1, 0], [P2, 0], [P3, 0]] etc.

Then based on their position in the game, add the appropriate amount of ranking score to their current ranking score (there will be multiple games so ranking score will be constantly added on top of current ranking score for players), the desired outcome will look something like:

playerRank = [[P1, 10] [P2, 100], [P3, 25], [P4, 50], [P5, 5], [P6, 0]]

Any help on this would be greatly appreciated as I am new to programming and struggling to work out the code and logic behind it

Thanks

Body:
You can use a defaultdict to update the scores and zip to create the game results:

from collections import defaultdict
results = ['P2', 'P4', 'P3', 'P1', 'P5', 'P6']
rankingPoints = [100, 50, 25, 10, 5, 0]
d = defaultdict(int)
for a, b in zip(results, rankingPoints):
   d[a] += b

final_results = [[a, b] for a, b in sorted(d.items(), key=lambda x:x[0])]

Output:

[['P1', 10], ['P2', 100], ['P3', 25], ['P4', 50], ['P5', 5], ['P6', 0]]

While you could just use sorted(zip(results, rankingPoints), key=lambda x:x[0]) to achieve the final output, the dictionary will allow you to increment the scores for each player later on in the program.


问:
Why do we say functional API in Keras is used for non-sequential models?
AFAIK, we still need to create a model and add layers to the model using the functional API. Why people say that the functional AI is used to create non-sequential neural network?</p>

答:
Why people said it is used to non-sequential neural network?

The thing is that with the Sequential Model you are defining a model step by step (sequentially), when you call the .add() method. Whereas, on the Functional API (specifically the Model class) you have more freedom, as you can define different layers that receive different inputs and then instantiate a model with the Model creator using any of those layers (not necessarily in a step by step, or sequential way).

In other words, when calling model = Sequential() you are in that moment instantiating your model object (for which you then add layers and constraints). In the Functional API, you create layers and then instantiate your model by calling model = Model(inputs=in, outputs=out) with your desired input and output layer(s). As you see, both approaches can be equivalent, for example, these two are the same:

from keras.models import Sequential, Model
from keras.layers import Input, Dense, Activation
#---Using the Sequential model
model = Sequential() #Object is instantiated here
model.add(Dense(32, input_dim=784))
model.add(Activation('relu'))
#---Or using the Functional API
a = Input(shape=(784,))
b = Dense(32, activation='relu')(a)
model = Model(inputs=a, outputs=b) #Object is instantiated here
```

<p>Considering only this, then choosing which way to go depends more on your personal style and coding preferences. Now, there is a <strong>major advantage</strong> of using the Functional API over the Sequential model, which is that <strong>you can share or reuse layers across different models</strong>. </p>

<p><strong>When compiling and fitting a model, all its associated layers will be compiled and trained. Thus, any other model that shares such layers will also reflect those changes</strong>. This gives you the freedom to do many things, as obtaining sub-models of your network, redefine them, obtain its relative outputs, merge them into more complex models, etc., without having to train again for each of those sub-models.</p>

<p>To make it clearer, here is an example (based on this Keras Autoencoder Blog post) that illustrates what was discussed in the last paragraph:</p>

<pre class="lang-py prettyprint-override"><code>from keras.layers import Input, Dense
from keras.models import Model
#Create an autoencoder, along with its encoder and decoder model
input_img = Input(shape=(784,))
encoded = Dense(32, activation='relu')(input_img)
decoded = Dense(784, activation='sigmoid')(encoded)

#Here we define our autoencoder model: image -> encoding -> decoded image
autoencoder = Model(input_img, decoded)

#Now here is the advantage of the Funcional API
#We can reuse those layers to obtain an encoder model (image -> encoding)
#as well as a decoder model (encoding -> image)
#but compile all three by just compiling and fitting the Autoencoder model
encoder = Model(input_img, encoded) #see how the 'encoded' layer is output
# create a placeholder for an encoded (32-dimensional) input
encoded_input = Input(shape=(32,))
# retrieve the last layer of the autoencoder model
decoder_layer = autoencoder.layers[-1]
# create the decoder model
decoder = Model(encoded_input, decoder_layer(encoded_input))
#compile and fit with your data
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
autoencoder.fit(X,Y,...)
</code>```

After this, you will be able to make predictions on the encoder and decoder model individually (to visualize your encoding, for example), as well as make predictions with the autoencoder model as a whole. At this point, doing the following things are equivalent:

#obtain reconstructed representation directly
autoencoder_imgs = autoencoder.predict(x_test)
#obtain reconstructed representation by joining encoder and decoder models
encoder_imgs = encoder.predict(x_test)
decoded_imgs = decoder.predict(encoded_imgs)
```

Hope this helps. Personally, I always try to use the Functional API instead, regardless if I want or not to reuse or recycle layers, as I find it more verbose, but that is up to you to decide.

ContentLicense: CC BY-SA 4.0

Body:
Why people said it is used to non-sequential neural network?

The thing is that with the Sequential Model you are defining a model step by step (sequentially), when you call the .add() method. Whereas, on the Functional API (specifically the Model class) you have more freedom, as you can define different layers that receive different inputs and then instantiate a model with the Model creator using any of those layers (not necessarily in a step by step, or sequential way).

In other words, when calling model = Sequential() you are in that moment instantiating your model object (for which you then add layers and constraints). In the Functional API, you create layers and then instantiate your model by calling model = Model(inputs=in, outputs=out) with your desired input and output layer(s). As you see, both approaches can be equivalent, for example, these two are the same:

from keras.models import Sequential, Model
from keras.layers import Input, Dense, Activation
#---Using the Sequential model
model = Sequential() #Object is instantiated here
model.add(Dense(32, input_dim=784))
model.add(Activation('relu'))
#---Or using the Functional API
a = Input(shape=(784,))
b = Dense(32, activation='relu')(a)
model = Model(inputs=a, outputs=b) #Object is instantiated here

Considering only this, then choosing which way to go depends more on your personal style and coding preferences. Now, there is a major advantage of using the Functional API over the Sequential model, which is that you can share or reuse layers across different models.

When compiling and fitting a model, all its associated layers will be compiled and trained. Thus, any other model that shares such layers will also reflect those changes. This gives you the freedom to do many things, as obtaining sub-models of your network, redefine them, obtain its relative outputs, merge them into more complex models, etc., without having to train again for each of those sub-models.

To make it clearer, here is an example (based on this Keras Autoencoder Blog post) that illustrates what was discussed in the last paragraph:

from keras.layers import Input, Dense
from keras.models import Model
#Create an autoencoder, along with its encoder and decoder model
input_img = Input(shape=(784,))
encoded = Dense(32, activation='relu')(input_img)
decoded = Dense(784, activation='sigmoid')(encoded)

#Here we define our autoencoder model: image -> encoding -> decoded image
autoencoder = Model(input_img, decoded)

#Now here is the advantage of the Funcional API
#We can reuse those layers to obtain an encoder model (image -> encoding)
#as well as a decoder model (encoding -> image)
#but compile all three by just compiling and fitting the Autoencoder model
encoder = Model(input_img, encoded) #see how the 'encoded' layer is output
# create a placeholder for an encoded (32-dimensional) input
encoded_input = Input(shape=(32,))
# retrieve the last layer of the autoencoder model
decoder_layer = autoencoder.layers[-1]
# create the decoder model
decoder = Model(encoded_input, decoder_layer(encoded_input))
#compile and fit with your data
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
autoencoder.fit(X,Y,...)

After this, you will be able to make predictions on the encoder and decoder model individually (to visualize your encoding, for example), as well as make predictions with the autoencoder model as a whole. At this point, doing the following things are equivalent:

#obtain reconstructed representation directly
autoencoder_imgs = autoencoder.predict(x_test)
#obtain reconstructed representation by joining encoder and decoder models
encoder_imgs = encoder.predict(x_test)
decoded_imgs = decoder.predict(encoded_imgs)

Hope this helps. Personally, I always try to use the Functional API instead, regardless if I want or not to reuse or recycle layers, as I find it more verbose, but that is up to you to decide.


问:
How to get last record based on a date with some other aggregate column in a SQL query
I know this question is already asked like 100 time and I reviewed all of them but I'm Kinda Stuck and had to asked for help

I have table like this:

```<code>hivenumber Visitdate   CombsNO  WaxNo  BeeBehave
------------------------------------------------
    1      2017-11-10    10       2        4
    2      2017-11-10    11       1        3
    3      2017-11-10    12       3        3
    1      2017-11-12    13       1        1
    3      2017-11-11    14       5        2
</code>```

At first I want to aggregate it by HiveNumber

```<code>Select HiveNumber
From tHivesDetails
Group BY HiveNumber
</code>```

Then I want the last record of CombNo for each HiveNumber

```<code>Select Top(1) CombNo
From `tHivesDetails`
Order By VisitDate Desc
</code>```

Then I need sum of Wax for each HiveNumber

```<code>Select Sum(Wax)
From `tHivesDetails`
Group BY HiveNumber
</code>```

and at the end I want average of BeeBehave

```<code>Select Avg(BeeBehave)
From tHivesDetails
Group By HiveNumber
</code>```

I don't know how to combine these queries to 1 and have one table with all I need in this case. I read most of same question but unfortunately couldn't figure it how do that.

I want a result like this:

```<code>hivenumber  Visitdate  CombsNO  WaxNo  BeeBehave
------------------------------------------------
    1      2017-11-12    13      Sum      avg
    2      2017-11-10    11      sum      avg
    3      2017-11-11    14      sum      avg
</code>```

答:
"Window Functions" to the rescue. You can use aggregate functions with an over clause to produce values on each row of a result. ROW_NUMBER() allows use of order by as well, do by ordering within each "partition" by the dates descending, the number 1 is given to "the most recent:" visit (per hive due to the partition).

```<code>select *
from (
       Select *
         , row_number() over(partition by HiveNumber order by VisitDate DESC) rn
         , sum(Wax) over(partition by HiveNumber) sum_wax
         , Avg(BeeBehave) over(partition by HiveNumber) avg_bb
       From tHivesDetails
      ) d
where rn = 1
</code>```

Body:
I know this question is already asked like 100 time and I reviewed all of them but I'm Kinda Stuck and had to asked for help

I have table like this:

hivenumber Visitdate   CombsNO  WaxNo  BeeBehave
------------------------------------------------
    1      2017-11-10    10       2        4
    2      2017-11-10    11       1        3
    3      2017-11-10    12       3        3
    1      2017-11-12    13       1        1
    3      2017-11-11    14       5        2

At first I want to aggregate it by HiveNumber

Select HiveNumber
From tHivesDetails
Group BY HiveNumber

Then I want the last record of CombNo for each HiveNumber

Select Top(1) CombNo
From `tHivesDetails`
Order By VisitDate Desc

Then I need sum of Wax for each HiveNumber

Select Sum(Wax)
From `tHivesDetails`
Group BY HiveNumber

and at the end I want average of BeeBehave

Select Avg(BeeBehave)
From tHivesDetails
Group By HiveNumber

I don't know how to combine these queries to 1 and have one table with all I need in this case. I read most of same question but unfortunately couldn't figure it how do that.

I want a result like this:

hivenumber  Visitdate  CombsNO  WaxNo  BeeBehave
------------------------------------------------
    1      2017-11-12    13      Sum      avg
    2      2017-11-10    11      sum      avg
    3      2017-11-11    14      sum      avg

Body:
"Window Functions" to the rescue. You can use aggregate functions with an over clause to produce values on each row of a result. ROW_NUMBER() allows use of order by as well, do by ordering within each "partition" by the dates descending, the number 1 is given to "the most recent:" visit (per hive due to the partition).

select *
from (
       Select *
         , row_number() over(partition by HiveNumber order by VisitDate DESC) rn
         , sum(Wax) over(partition by HiveNumber) sum_wax
         , Avg(BeeBehave) over(partition by HiveNumber) avg_bb
       From tHivesDetails
      ) d
where rn = 1


问:
laravel angular add post 500 error
I'm trying to submit a post using angular, I was following this tutorial and I get the following error.

$http.post(...).success is not a function Failed to load resource: the
  server responded with a status of 500 (Internal Server Error)

$http.post(...).success is not a function
      at b.$scope.addPost (main.js:18)

Here is the route:

Route::post('auth/post', 'PostController@storePost')->name('add.post');

PostController

```<code>public function storePost(Request $request)
{
    $data = request()->validate([
     'title' => 'required|max:120',
     'body' => 'required|max:1000'
    ]);

    $data['user_id'] = auth()->user()->id;

    $post = Post::create($data);

    // return redirect('/home')->withMessage('A new post was created.');

    return Response::json(array('success' => true));
}
</code>```

Main.js

```<code>app.controller('mainCtrl', ['$scope', '$http', function($scope, $http){
    $scope.posts = {};

    $scope.addPost = function(){
        $http.post('/auth/post', {
            title: $scope.mytitle,
            body: $scope.mybody

        }).success(function(data, status, headers, config){
            $scope.posts.push(data);
            $scope.post = '';

        });

    };
}]);
</code>```

答:
I changed success to then, and it worked.</p>

```<code>app.controller('mainCtrl', ['$scope', '$http', function($scope, $http){
    $scope.posts = {};

    $scope.addPost = function(){
        $http.post('/auth/post', {
            title: $scope.mytitle,
            body: $scope.mybody

        }).then(function(data, status, headers, config){
            $scope.posts.push(data);
            $scope.post = '';

        });

    };
}]);
</code>```

Title: laravel angular add post 500 error

Body:
I'm trying to submit a post using angular, I was following this tutorial and I get the following error.

$http.post(...).success is not a function Failed to load resource: the
  server responded with a status of 500 (Internal Server Error)

$http.post(...).success is not a function
      at b.$scope.addPost (main.js:18)

Here is the route:

Route::post('auth/post', 'PostController@storePost')->name('add.post');

PostController

public function storePost(Request $request)
{
    $data = request()->validate([
     'title' => 'required|max:120',
     'body' => 'required|max:1000'
    ]);

    $data['user_id'] = auth()->user()->id;

    $post = Post::create($data);

    // return redirect('/home')->withMessage('A new post was created.');

    return Response::json(array('success' => true));
}

Main.js

app.controller('mainCtrl', ['$scope', '$http', function($scope, $http){
    $scope.posts = {};

    $scope.addPost = function(){
        $http.post('/auth/post', {
            title: $scope.mytitle,
            body: $scope.mybody

        }).success(function(data, status, headers, config){
            $scope.posts.push(data);
            $scope.post = '';

        });

    };
}]);

Body:
I changed success to then, and it worked.

app.controller('mainCtrl', ['$scope', '$http', function($scope, $http){
    $scope.posts = {};

    $scope.addPost = function(){
        $http.post('/auth/post', {
            title: $scope.mytitle,
            body: $scope.mybody

        }).then(function(data, status, headers, config){
            $scope.posts.push(data);
            $scope.post = '';

        });

    };
}]);


问:
Android Studio, download soruces android-27 to target latest SDK
To start a new project, I want to target the latest SDK (taking advantage of the fresh start).
But, I also want to have access to the Android source code to be able to read the code of android classes (like AsyncTask, just as an example).
I'm targeting SDK 27 on gradle and also using compileSdkVersion 27.
I've tried by different ways (as indicated here, here and here) but I can't seem to download those sources.

When I try to browse an Android class like AsyncTask for example, I get the message:

Decompiled .class file, bytecode version: 52.0 (Java 8)

  Sources for 'Android API 27 Platform' not found.

Even after clicking the Download and then the Refresh (if already downloaded) links (which is the most intuitive thing to do) I still can't see the source code of any Android class.

This is an issue only for API 27. I'm able to download sources for all other API versions.

Is this because of API 27 being the latest one?

I want to avoid targeting 26. Is it possible to download those sources? Has anyone been able to do it so far?

If someone knows how to do this so far, that would be very helpful. Thanks.

I'm using Android Studio 3.0 and the download option for API 27 source is not available:

UPDATE

As indicated by the accepted answer, the problem was the API Level 27 being a dev preview back then, the problem got resolved with time (once the official release happened). This update may be useful for people facing similar problems when targeting the latest available API version.

答:
Is this because of API 27 being the latest one?

No, it is because API Level 27 is Android 8.1, which is in a developer preview at the moment.

I want to avoid targeting 26

I am not certain why, considering that 26 is the API level corresponding with the latest production release of Android (8.0).

Is it possible to download those sources?

Usually, the sources are not available via the IDE until the OS release ships in final form.


问:
Sync additional Billing registration fields with default Wordpress fields in WooCommerce
I Have added the below codes into Woocommerce user registration form to get the Billing Details on the registration page.

Now what is happening when a new user register, the first and last name will get registered in the database of billing details & as well as in the default wordpress user account. If the user update his first name & last name on his account (wordpress user account), the same should update on the billing details.

Woocommerce settings:

Guest checkout is disabled.
Checkout page user registration is enabled.
Login Page Registration is enabled.
Only Registered user can make purchases.

This is the user registration form where I'm pulling these additional billing details from checkout process.

On "Account Details" I updated the "First Name", it worked here but i didn't get the same update on "Billing Details". I want the same "First Name" & "Last Name" update on the "Billing Details" if a user update these 2 fields and his email address on his "Account Details".

Now after updating the "First Name" & "Last Name" on "Account Details", I came back to "Billing Details" but it is still displaying the old "First Name" & "Last Name" which were used during registeration process. Also, I want to hide these 3 fields from Billing details, "First Name", "Last Name" & "Email Address"- to not to confuse the registered users. I need these updates on "Billing Details" in database only because these information will be printed on the invoices & Emails

The data will only sync/update if an administrator or store manager go to the user profile (from back-end) and manually press the "update" button then only it will take the effects. I want the data to sync/update automatically when a registered user made any changes from his account (front-end).

Any help will be highly appreciated.

Please check the below code:

```<code>// Custom function to display the Billing Address form to registration page
add_action('woocommerce_register_form_start','zk_add_billing_form_to_registration');
function zk_add_billing_form_to_registration(){
    $checkout = WC()->checkout;
    foreach ( $checkout->get_checkout_fields( 'billing' ) as $key => $field ) :
        if($key!='billing_email')
            woocommerce_form_field( $key, $field, $checkout->get_value( $key ) );
    endforeach;
}

// Custom function to save Usermeta or Billing Address of registered user
add_action('woocommerce_created_customer','zk_save_billing_address');
function zk_save_billing_address($user_id){
    $address = $_POST;
    foreach ($address as $key => $field){
        // Only billing fields values
        if( strpos( $key, 'billing_' ) !== false ){
            // Condition to add firstname and last name to user meta table
            if($key == 'billing_first_name' || $key == 'billing_last_name'){
                $new_key = str_replace( 'billing_', '', $key );
                update_user_meta( $user_id, $new_key, $_POST[$key] );
            }
            update_user_meta( $user_id, $key, $_POST[$key] );
        }
    }
}

// Checking & validation of the additional fields in registration form.
add_action('woocommerce_register_post','zk_validation_billing_address', 10, 3 );
function zk_validation_billing_address( $username, $email, $validation_errors ){
    foreach ($_POST as $key => $field) :
        // Validation: Required fields
        if( strpos( $key, 'billing_' ) !== false ){
            if($key == 'billing_country' && empty($field) ){
                $validation_errors->add( $key.'_error',  __( 'Please select a country.', 'woocommerce' ));
            }
            if($key == 'billing_first_name' && empty($field) ){
                $validation_errors->add( $key.'_error', __( 'Please enter first name.', 'woocommerce' ) );
            }
            if($key == 'billing_last_name' && empty($field) ){
                $validation_errors->add( $key.'_error', __( 'Please enter last name.', 'woocommerce' ) );
            }
            if($key == 'billing_address_1' && empty($field) ){
                $validation_errors->add( $key.'_error', __( 'Please enter address.', 'woocommerce' ) );
            }
            if($key == 'billing_city' && empty($field) ){
                $validation_errors->add( $key.'_error', __( 'Please enter city.', 'woocommerce' ) );
            }
            if($key == 'billing_state' && empty($field) ){
                if(count( WC()->countries->get_states($_POST['billing_country']) ) > 0)
                    $validation_errors->add( $key.'_error', __( 'Please enter state.', 'woocommerce' ) );
            }
            if($key == 'billing_postcode' && empty($field) ){
                $validation_errors->add( $key.'_error', __( 'Please enter a postcode.', 'woocommerce' ) );
            }
            /*
            if($key == 'billing_email' && empty($field) ){
                $validation_errors->add( $key.'_error', __( 'Please enter billing email address.', 'woocommerce' ) );
            }
            */
            if($key == 'billing_phone' && empty($field) ){
                $validation_errors->add( $key.'_error', __( 'Please enter phone number.', 'woocommerce' ) );
            }

        }
    endforeach;
}

add_filter( 'woocommerce_billing_fields', 'sv_required_billing_fields' );
function sv_required_billing_fields( $fields ) {
    $fields['billing_phone']['required'] = true;
    $fields['billing_city']['required'] = true;
    $fields['billing_country']['required'] = true;
    $fields['billing_address_1']['required'] = true;
    return $fields;
}

// Hidding some billing fields (Wordpress edit user pages)
add_action( 'edit_user_profile', 'user_profile_hide_some_fields_css', 1, 1 );
function user_profile_hide_some_fields_css( $user ){
    ?>
    <style>
    .user-edit-php table#fieldset-billing tr:first-child,
    .user-edit-php table#fieldset-billing tr:nth-child(2),
    .user-edit-php table#fieldset-billing tr:last-child {
        display:none;
    }
    </style>
    <?php
}

// Sync hidden billing fields (Wordpress edit user pages)
add_action( 'personal_options_update', 'sync_user_data_wp_and_billing_wc', 100, 1 );
add_action( 'edit_user_profile_update', 'sync_user_data_wp_and_billing_wc', 100, 1 );
function sync_user_data_wp_and_billing_wc( $user_id )
{
    if( ! empty($_POST['first_name']) ) {
        update_user_meta( $user_id, 'billing_first_name', sanitize_text_field( $_POST['first_name'] ) );
    }

    if( ! empty($_POST['last_name']) ) {
        update_user_meta( $user_id, 'billing_last_name', sanitize_text_field( $_POST['last_name'] ) );
    }

    if( ! empty($_POST['email']) ) {
        update_user_meta( $user_id, 'billing_email', sanitize_text_field( $_POST['email'] ), sanitize_text_field( $_POST['billing_email'] ) );
    }
}
</code>```

答:
I have revisited your code a bit, as for example the 4 last functions can be merged in one, and other things…

Data update and sync

Now when a customer updates his data on his my account pages, all data is synched by woocommerce everywhere, except on his existing past Orders…

If a customer change checkout fields and process checkout, the data is also updated everywhere…

So you don't need to worry about customer synched data.

Note: The function hooked in woocommerce_billing_fields will be enabled either in your additional registration fields and in checkout fields, as you are using checkout object to generate additional registration fields… You can use the conditional ! is_checkout() to only target my account registration fields.

Here is your revisited code:

```<code>// Custom function to display the Billing Address form to registration page
add_action('woocommerce_register_form_start','zk_add_billing_form_to_registration');
function zk_add_billing_form_to_registration(){
    $checkout = WC()->checkout;
    foreach ( $checkout->get_checkout_fields( 'billing' ) as $key => $field ) :
        if($key!='billing_email')
            woocommerce_form_field( $key, $field, $checkout->get_value( $key ) );
    endforeach;
}

// Custom function to save Usermeta or Billing Address of registered user
add_action('woocommerce_created_customer','zk_save_billing_address');
function zk_save_billing_address($user_id){
    $address = $_POST;
    foreach ($address as $key => $field){
        // Only billing fields values
        if( strpos( $key, 'billing_' ) !== false ){
            // Condition to add firstname and last name to user meta table
            if($key == 'billing_first_name' || $key == 'billing_last_name'){
                $new_key = str_replace( 'billing_', '', $key );
                update_user_meta( $user_id, $new_key, $_POST[$key] );
            }
            update_user_meta( $user_id, $key, $_POST[$key] );
        }
    }
}

// Checking & validation of the additional fields in registration form.
add_action('woocommerce_register_post','zk_validation_billing_address', 10, 3 );
function zk_validation_billing_address( $username, $email, $validation_errors ){
    foreach ($_POST as $key => $field) :
        // Validation: Required fields
        if( strpos( $key, 'billing_' ) !== false ){
            if($key == 'billing_country' && empty($field) ){
                $validation_errors->add( $key.'_error',  __( 'Please select a country.', 'woocommerce' ));
            }
            if($key == 'billing_first_name' && empty($field) ){
                $validation_errors->add( $key.'_error', __( 'Please enter first name.', 'woocommerce' ) );
            }
            if($key == 'billing_last_name' && empty($field) ){
                $validation_errors->add( $key.'_error', __( 'Please enter last name.', 'woocommerce' ) );
            }
            if($key == 'billing_address_1' && empty($field) ){
                $validation_errors->add( $key.'_error', __( 'Please enter address.', 'woocommerce' ) );
            }
            if($key == 'billing_city' && empty($field) ){
                $validation_errors->add( $key.'_error', __( 'Please enter city.', 'woocommerce' ) );
            }
            if($key == 'billing_state' && empty($field) ){
                if(count( WC()->countries->get_states($_POST['billing_country']) ) > 0)
                    $validation_errors->add( $key.'_error', __( 'Please enter state.', 'woocommerce' ) );
            }
            if($key == 'billing_postcode' && empty($field) ){
                $validation_errors->add( $key.'_error', __( 'Please enter a postcode.', 'woocommerce' ) );
            }
            /*
            if($key == 'billing_email' && empty($field) ){
                $validation_errors->add( $key.'_error', __( 'Please enter billing email address.', 'woocommerce' ) );
            }
            */
            if($key == 'billing_phone' && empty($field) ){
                $validation_errors->add( $key.'_error', __( 'Please enter phone number.', 'woocommerce' ) );
            }

        }
    endforeach;
}

add_filter( 'woocommerce_billing_fields', 'sv_required_billing_fields' );
function sv_required_billing_fields( $fields ) {
    $fields['billing_phone']['required'] = true;
    $fields['billing_city']['required'] = true;
    $fields['billing_country']['required'] = true;
    $fields['billing_address_1']['required'] = true;
    return $fields;
}
</code>```

The customer can't access (never) to WordPress backend User edit pages. Only shop Manager and administrators can do it…

To sync Wordpress user data in backend you need to choose which fields will have the priority:

the Wordpress default fields (or)

the billing fields (from WooCommerce).

Is better to give the priority to WordPress default fields and hide necessary billing fields…

This code will hide the 3 billing fields (first name, last name and email) and will sync them with default fields updated values:

```<code>// Hidding some billing fields (Wordpress edit user pages)
add_action( 'edit_user_profile', 'user_profile_hide_some_fields_css', 1, 1 );
function user_profile_hide_some_fields_css( $user ){
    ?>
    <style>
    .user-edit-php table#fieldset-billing tr:first-child,
    .user-edit-php table#fieldset-billing tr:nth-child(2),
    .user-edit-php table#fieldset-billing tr:last-child {
        display:none;
    }
    </style>
    <?php
}

// Sync hidden billing fields (Wordpress edit user pages)
add_action( 'personal_options_update', 'sync_user_data_wp_and_billing_wc', 100, 1 );
add_action( 'edit_user_profile_update', 'sync_user_data_wp_and_billing_wc', 100, 1 );
function sync_user_data_wp_and_billing_wc( $user_id )
{
    if( ! empty($_POST['first_name']) ) {
        update_user_meta( $user_id, 'billing_first_name', sanitize_text_field( $_POST['first_name'] ) );
    }

    if( ! empty($_POST['last_name']) ) {
        update_user_meta( $user_id, 'billing_last_name', sanitize_text_field( $_POST['last_name'] ) );
    }

    if( ! empty($_POST['email']) ) {
        update_user_meta( $user_id, 'billing_email', sanitize_text_field( $_POST['email'] ), sanitize_text_field( $_POST['billing_email'] ) );
    }
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works…

Body:
I Have added the below codes into Woocommerce user registration form to get the Billing Details on the registration page.

Now what is happening when a new user register, the first and last name will get registered in the database of billing details & as well as in the default wordpress user account. If the user update his first name & last name on his account (wordpress user account), the same should update on the billing details.

Woocommerce settings:

Guest checkout is disabled.
Checkout page user registration is enabled.
Login Page Registration is enabled.
Only Registered user can make purchases.

This is the user registration form where I'm pulling these additional billing details from checkout process.

On "Account Details" I updated the "First Name", it worked here but i didn't get the same update on "Billing Details". I want the same "First Name" & "Last Name" update on the "Billing Details" if a user update these 2 fields and his email address on his "Account Details".

Now after updating the "First Name" & "Last Name" on "Account Details", I came back to "Billing Details" but it is still displaying the old "First Name" & "Last Name" which were used during registeration process. Also, I want to hide these 3 fields from Billing details, "First Name", "Last Name" & "Email Address"- to not to confuse the registered users. I need these updates on "Billing Details" in database only because these information will be printed on the invoices & Emails

The data will only sync/update if an administrator or store manager go to the user profile (from back-end) and manually press the "update" button then only it will take the effects. I want the data to sync/update automatically when a registered user made any changes from his account (front-end).

Any help will be highly appreciated.

Please check the below code:

// Custom function to display the Billing Address form to registration page
add_action('woocommerce_register_form_start','zk_add_billing_form_to_registration');
function zk_add_billing_form_to_registration(){
    $checkout = WC()->checkout;
    foreach ( $checkout->get_checkout_fields( 'billing' ) as $key => $field ) :
        if($key!='billing_email')
            woocommerce_form_field( $key, $field, $checkout->get_value( $key ) );
    endforeach;
}

// Custom function to save Usermeta or Billing Address of registered user
add_action('woocommerce_created_customer','zk_save_billing_address');
function zk_save_billing_address($user_id){
    $address = $_POST;
    foreach ($address as $key => $field){
        // Only billing fields values
        if( strpos( $key, 'billing_' ) !== false ){
            // Condition to add firstname and last name to user meta table
            if($key == 'billing_first_name' || $key == 'billing_last_name'){
                $new_key = str_replace( 'billing_', '', $key );
                update_user_meta( $user_id, $new_key, $_POST[$key] );
            }
            update_user_meta( $user_id, $key, $_POST[$key] );
        }
    }
}

// Checking & validation of the additional fields in registration form.
add_action('woocommerce_register_post','zk_validation_billing_address', 10, 3 );
function zk_validation_billing_address( $username, $email, $validation_errors ){
    foreach ($_POST as $key => $field) :
        // Validation: Required fields
        if( strpos( $key, 'billing_' ) !== false ){
            if($key == 'billing_country' && empty($field) ){
                $validation_errors->add( $key.'_error',  __( 'Please select a country.', 'woocommerce' ));
            }
            if($key == 'billing_first_name' && empty($field) ){
                $validation_errors->add( $key.'_error', __( 'Please enter first name.', 'woocommerce' ) );
            }
            if($key == 'billing_last_name' && empty($field) ){
                $validation_errors->add( $key.'_error', __( 'Please enter last name.', 'woocommerce' ) );
            }
            if($key == 'billing_address_1' && empty($field) ){
                $validation_errors->add( $key.'_error', __( 'Please enter address.', 'woocommerce' ) );
            }
            if($key == 'billing_city' && empty($field) ){
                $validation_errors->add( $key.'_error', __( 'Please enter city.', 'woocommerce' ) );
            }
            if($key == 'billing_state' && empty($field) ){
                if(count( WC()->countries->get_states($_POST['billing_country']) ) > 0)
                    $validation_errors->add( $key.'_error', __( 'Please enter state.', 'woocommerce' ) );
            }
            if($key == 'billing_postcode' && empty($field) ){
                $validation_errors->add( $key.'_error', __( 'Please enter a postcode.', 'woocommerce' ) );
            }
            /*
            if($key == 'billing_email' && empty($field) ){
                $validation_errors->add( $key.'_error', __( 'Please enter billing email address.', 'woocommerce' ) );
            }
            */
            if($key == 'billing_phone' && empty($field) ){
                $validation_errors->add( $key.'_error', __( 'Please enter phone number.', 'woocommerce' ) );
            }

        }
    endforeach;
}

add_filter( 'woocommerce_billing_fields', 'sv_required_billing_fields' );
function sv_required_billing_fields( $fields ) {
    $fields['billing_phone']['required'] = true;
    $fields['billing_city']['required'] = true;
    $fields['billing_country']['required'] = true;
    $fields['billing_address_1']['required'] = true;
    return $fields;
}

// Hidding some billing fields (Wordpress edit user pages)
add_action( 'edit_user_profile', 'user_profile_hide_some_fields_css', 1, 1 );
function user_profile_hide_some_fields_css( $user ){
    ?>

    <?php
}

// Sync hidden billing fields (Wordpress edit user pages)
add_action( 'personal_options_update', 'sync_user_data_wp_and_billing_wc', 100, 1 );
add_action( 'edit_user_profile_update', 'sync_user_data_wp_and_billing_wc', 100, 1 );
function sync_user_data_wp_and_billing_wc( $user_id )
{
    if( ! empty($_POST['first_name']) ) {
        update_user_meta( $user_id, 'billing_first_name', sanitize_text_field( $_POST['first_name'] ) );
    }

    if( ! empty($_POST['last_name']) ) {
        update_user_meta( $user_id, 'billing_last_name', sanitize_text_field( $_POST['last_name'] ) );
    }

    if( ! empty($_POST['email']) ) {
        update_user_meta( $user_id, 'billing_email', sanitize_text_field( $_POST['email'] ), sanitize_text_field( $_POST['billing_email'] ) );
    }
}

Body:
I have revisited your code a bit, as for example the 4 last functions can be merged in one, and other things…

Data update and sync

Now when a customer updates his data on his my account pages, all data is synched by woocommerce everywhere, except on his existing past Orders…

If a customer change checkout fields and process checkout, the data is also updated everywhere…

So you don't need to worry about customer synched data.

Note: The function hooked in woocommerce_billing_fields will be enabled either in your additional registration fields and in checkout fields, as you are using checkout object to generate additional registration fields… You can use the conditional ! is_checkout() to only target my account registration fields.

Here is your revisited code:

// Custom function to display the Billing Address form to registration page
add_action('woocommerce_register_form_start','zk_add_billing_form_to_registration');
function zk_add_billing_form_to_registration(){
    $checkout = WC()->checkout;
    foreach ( $checkout->get_checkout_fields( 'billing' ) as $key => $field ) :
        if($key!='billing_email')
            woocommerce_form_field( $key, $field, $checkout->get_value( $key ) );
    endforeach;
}

// Custom function to save Usermeta or Billing Address of registered user
add_action('woocommerce_created_customer','zk_save_billing_address');
function zk_save_billing_address($user_id){
    $address = $_POST;
    foreach ($address as $key => $field){
        // Only billing fields values
        if( strpos( $key, 'billing_' ) !== false ){
            // Condition to add firstname and last name to user meta table
            if($key == 'billing_first_name' || $key == 'billing_last_name'){
                $new_key = str_replace( 'billing_', '', $key );
                update_user_meta( $user_id, $new_key, $_POST[$key] );
            }
            update_user_meta( $user_id, $key, $_POST[$key] );
        }
    }
}

// Checking & validation of the additional fields in registration form.
add_action('woocommerce_register_post','zk_validation_billing_address', 10, 3 );
function zk_validation_billing_address( $username, $email, $validation_errors ){
    foreach ($_POST as $key => $field) :
        // Validation: Required fields
        if( strpos( $key, 'billing_' ) !== false ){
            if($key == 'billing_country' && empty($field) ){
                $validation_errors->add( $key.'_error',  __( 'Please select a country.', 'woocommerce' ));
            }
            if($key == 'billing_first_name' && empty($field) ){
                $validation_errors->add( $key.'_error', __( 'Please enter first name.', 'woocommerce' ) );
            }
            if($key == 'billing_last_name' && empty($field) ){
                $validation_errors->add( $key.'_error', __( 'Please enter last name.', 'woocommerce' ) );
            }
            if($key == 'billing_address_1' && empty($field) ){
                $validation_errors->add( $key.'_error', __( 'Please enter address.', 'woocommerce' ) );
            }
            if($key == 'billing_city' && empty($field) ){
                $validation_errors->add( $key.'_error', __( 'Please enter city.', 'woocommerce' ) );
            }
            if($key == 'billing_state' && empty($field) ){
                if(count( WC()->countries->get_states($_POST['billing_country']) ) > 0)
                    $validation_errors->add( $key.'_error', __( 'Please enter state.', 'woocommerce' ) );
            }
            if($key == 'billing_postcode' && empty($field) ){
                $validation_errors->add( $key.'_error', __( 'Please enter a postcode.', 'woocommerce' ) );
            }
            /*
            if($key == 'billing_email' && empty($field) ){
                $validation_errors->add( $key.'_error', __( 'Please enter billing email address.', 'woocommerce' ) );
            }
            */
            if($key == 'billing_phone' && empty($field) ){
                $validation_errors->add( $key.'_error', __( 'Please enter phone number.', 'woocommerce' ) );
            }

        }
    endforeach;
}

add_filter( 'woocommerce_billing_fields', 'sv_required_billing_fields' );
function sv_required_billing_fields( $fields ) {
    $fields['billing_phone']['required'] = true;
    $fields['billing_city']['required'] = true;
    $fields['billing_country']['required'] = true;
    $fields['billing_address_1']['required'] = true;
    return $fields;
}

The customer can't access (never) to WordPress backend User edit pages. Only shop Manager and administrators can do it…

To sync Wordpress user data in backend you need to choose which fields will have the priority:

the Wordpress default fields (or)

the billing fields (from WooCommerce).

Is better to give the priority to WordPress default fields and hide necessary billing fields…

This code will hide the 3 billing fields (first name, last name and email) and will sync them with default fields updated values:

// Hidding some billing fields (Wordpress edit user pages)
add_action( 'edit_user_profile', 'user_profile_hide_some_fields_css', 1, 1 );
function user_profile_hide_some_fields_css( $user ){
    ?>
    <style>
    .user-edit-php table#fieldset-billing tr:first-child,
    .user-edit-php table#fieldset-billing tr:nth-child(2),
    .user-edit-php table#fieldset-billing tr:last-child {
        display:none;
    }
    </style>
    <?php
}

// Sync hidden billing fields (Wordpress edit user pages)
add_action( 'personal_options_update', 'sync_user_data_wp_and_billing_wc', 100, 1 );
add_action( 'edit_user_profile_update', 'sync_user_data_wp_and_billing_wc', 100, 1 );
function sync_user_data_wp_and_billing_wc( $user_id )
{
    if( ! empty($_POST['first_name']) ) {
        update_user_meta( $user_id, 'billing_first_name', sanitize_text_field( $_POST['first_name'] ) );
    }

    if( ! empty($_POST['last_name']) ) {
        update_user_meta( $user_id, 'billing_last_name', sanitize_text_field( $_POST['last_name'] ) );
    }

    if( ! empty($_POST['email']) ) {
        update_user_meta( $user_id, 'billing_email', sanitize_text_field( $_POST['email'] ), sanitize_text_field( $_POST['billing_email'] ) );
    }
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works…


问:
Rails STI, subclasses don't show up unless used?
I am using Rails STI to model a complex domain.  In a view, I am listing all subclasses with:

```<code>> <% StateDescription.subclasses.each do |state_description| %>   <li>
> <%= state_description.to_s %> </li> <% end %>
</code>```

With the intent to eventually make each label of the subclass a link to the individual "index" page for just instances of that subclass.

This saves me from having to have a list of all possible subclasses myself (and updating it later if I add more).

However, I have noticed that only those subclasses I have actually loaded from the database show up in the list.  If I say StateDescription.all, then all existing subclasses show up (but none that have no instances yet).  If I instead ask for all of a particular subclass, then only that subclass show up.

I imagine this is part of the "lazy loading" I have heard about.  Is it?  It SEEMS like the problem is that if I don't grab a particular "type" from the database, even if I have a model for it, it may as well not exist?

Is there a way around this, or am I doomed to have to write out a link for every single subclass I create?

Edit:

On the console, if I type

StateDescription.subclasses.count

I get 0.

If I then do StateDescription.all and THEN StateDescription.subclasses.count, i get 14.

答:
The easiest way to do this is eager_load! in development.

Something like:

```<code><% Rails.application.eager_load! if Rails.env.development? %>
<% StateDescription.subclasses.each do |state_description| %>
  <li><%= state_description.to_s %> </li>
<% end %>
</code>```

Body:
I am using Rails STI to model a complex domain.  In a view, I am listing all subclasses with:

> <% StateDescription.subclasses.each do |state_description| %>

> <%= state_description.to_s %>
 <% end %>

With the intent to eventually make each label of the subclass a link to the individual "index" page for just instances of that subclass.

This saves me from having to have a list of all possible subclasses myself (and updating it later if I add more).

However, I have noticed that only those subclasses I have actually loaded from the database show up in the list.  If I say StateDescription.all, then all existing subclasses show up (but none that have no instances yet).  If I instead ask for all of a particular subclass, then only that subclass show up.

I imagine this is part of the "lazy loading" I have heard about.  Is it?  It SEEMS like the problem is that if I don't grab a particular "type" from the database, even if I have a model for it, it may as well not exist?

Is there a way around this, or am I doomed to have to write out a link for every single subclass I create?

Edit:

On the console, if I type

StateDescription.subclasses.count

I get 0.

If I then do StateDescription.all and THEN StateDescription.subclasses.count, i get 14.

Body:
The easiest way to do this is eager_load! in development.

Something like:

<% Rails.application.eager_load! if Rails.env.development? %>
<% StateDescription.subclasses.each do |state_description| %>
  <li><%= state_description.to_s %> </li>
<% end %>


问:
Advantages with code-signing EV certificates other than the Smartscreen ones?
I have to buy a code-signing certificate, for signing Win32 applications, and I was considering whether to pick an EV one.

The advantages of EV certificates I was able to find are:

Immediate Smartscreen reputation establisment (instead of waiting for 3k downloads? [source] )

Maintainance of Smartscreen reputation across certificate renewals [source] (probably a moot point if point 1 applies anyway)

Option for delivery on a hardware token, often not available for normal certificates

I wonder if they bring other advantages, for example if applications signed with them are more trusted than applications signed with non-EV certificates by antivirus, firewalls and other security applications (they get less blocked, provoke more favourable warnings, etc.).

I restate the case I'm most interested in: are you aware of differences in treatment by some specific antivirus/firewall/security application of applications signed with EV certificates, vs. applications signed with standard certificates?

答:
Disclosure: I work for an AV vendor.

I wonder if they bring other advantages, for example if applications
  signed with them are more trusted than applications signed with non-EV
  certificates by antivirus, firewalls and other security applications

This depends on the vendor making the security application, or their current(*) policy. Both security vendors I have worked for ignored the presence of the certificate when scanning for malware. There are several reasons for this:

Just because the code is signed doesn't mean it is not malicious. It only means it has not been modified after it has been signed. For example, a relatively large number of adware applications is signed.

Malware writes have used stolen certificates in past, and thus we cannot be truly sure it was used by the original author. This is why I mentioned "current policy" above, as this could change overnight.

Verifying a certificate is a complex and relatively slow process which requires reading the whole file from disk - an expensive operation for a non-SSD storage. It also requires performing some public key cryptography operations which are CPU-intensive. Thus for some large executable files checking the certificate might take longer than scanning the file for malware.

And since we generally don't look at certificate at all, it doesn't matter whether it is standard or EV.


问:
Anatomy of a Porch.com SMS lead alert
I would like to design the SMS referral link for a lead alerts application. (So the pro would receive the SMS message on their device with a link to click through to the job request details.) I'd like to make it secure and scalable. The link below arrives in the SMS as a shortened URL. That much I understand.

Porch.com does something similar and I'd like to know what the strategy is behind each segment in the URL (or your best estimation). Can someone help me understand?

Here is an example: (Thanks Porch.com)

https://porch.com/pro/project/3fd55669-d7cf-4655-892e-252080c34a79?c=50145918&email=12345@yahoo.com&referrerSource=sms

答:
Twilio developer evangelist here.

First of all, this isn't really a question for Stack Overflow. This is a place for asking questions about code that doesn't work in order to get it to work.

Having said that, the more I looked at the URL as I was commenting on this question, the more I feel I worked out. This is my idea of what the URL is saying.

Here's the URL again: https://porch.com/pro/project/3fd55669-d7cf-4655-892e-252080c34a79?c=50145918&email=12345@yahoo.com&referrerSource=sms

The random string in the URL, 3fd55669-d7cf-4655-892e-252080c34a79, looks like it is the identifier for the project itself. It's long and random, like a uuid, so it would be hard to guess, but can uniquely identify the project.

The email is presumably the email address of the pro that the SMS was sent to, so that the return on sending SMS projects to them can be measured.

The referrerSource is then used to measure how each of their referring sources is performing.

The only parameter that is impossible to really guess at is the c. Removing it (in fact, removing any or all of the query parameters) didn't change the result of loading the page. This implies that it is just another tracking parameter.

Hope that helps.

Title: Anatomy of a Porch.com SMS lead alert