问:
Is GHC's auto-derived `Eq` instance really *O(N)*?
I just noticed while trying to learn to read GHC Core, that the
automatically derived Eq instance for enum-style data types such as

```<code>data EType = ETypeA | ETypeB | ETypeC | ETypeD
           | ETypeE | ETypeF | ETypeG | ETypeH
           deriving (Eq)
</code>```

seems to be transformed into a O(N)-like lookup when looking at GHC's core representation:

```<code>$fEqEType_$c== =
  \ (a_ahZ :: EType) (b_ai0 :: EType) ->
    case a_ahZ of _ {
      ETypeA ->
        case b_ai0 of _ {
          ETypeA -> True;
          ETypeB -> False;
          ETypeC -> False;
          ETypeD -> False;
          ETypeE -> False;
          ETypeF -> False;
          ETypeG -> False;
          ETypeH -> False
        };
      ETypeB -> case b_ai0 of _ {__DEFAULT -> False; ETypeB -> True};
      ETypeC -> case b_ai0 of _ {__DEFAULT -> False; ETypeC -> True};
      ETypeD -> case b_ai0 of _ {__DEFAULT -> False; ETypeD -> True};
      ETypeE -> case b_ai0 of _ {__DEFAULT -> False; ETypeE -> True};
      ETypeF -> case b_ai0 of _ {__DEFAULT -> False; ETypeF -> True};
      ETypeG -> case b_ai0 of _ {__DEFAULT -> False; ETypeG -> True};
      ETypeH -> case b_ai0 of _ {__DEFAULT -> False; ETypeH -> True}
    }
</code>```

Am I misinterpreting the GHC core output? Shouldn't algebraic data types provide an integer id for each constructor, which could then be compared directly in O(1)? Also, why does the first case clause for ETypeA not make use of __DEFAULT as the other clauses do?

update:

As per suggestion by Simon Marlow, I addad a 9th constructor ETypeI, and then GHC switched to using dataToOtag#:

```<code>$fEqEType_$c/= =
  \ (a_ahS :: EType) (b_ahT :: EType) ->
    case dataToTag# @ EType a_ahS of a#_ahQ {
      __DEFAULT ->
        case dataToTag# @ EType b_ahT of b#_ahR {
          __DEFAULT ->
            case ==# a#_ahQ b#_ahR of _ {
              False -> True; True -> False
            }
        }
    }
</code>```

For me, this adds the question as to what the trade-offs  between GHC core's case and use of dataToTag# are, and why this particular cut-off of 9 constructors for using dataToTag# is implemented in GHC.

答:
Equality comparison of EType is O(1) because the case construct is O(1).

There might or might not be an integer tag for constructors.  There are several low level representation choices, so the Core generated works for all of them.  That said, you can always make an integer tag for constructors, and that's how I usually implement the derived comparison when I write Haskell compilers.

I have no idea why ETypeA gets a different treatment.  Looks like bug.

Body:
I just noticed while trying to learn to read GHC Core, that the
automatically derived Eq instance for enum-style data types such as

data EType = ETypeA | ETypeB | ETypeC | ETypeD
           | ETypeE | ETypeF | ETypeG | ETypeH
           deriving (Eq)

seems to be transformed into a O(N)-like lookup when looking at GHC's core representation:

$fEqEType_$c== =
  \ (a_ahZ :: EType) (b_ai0 :: EType) ->
    case a_ahZ of _ {
      ETypeA ->
        case b_ai0 of _ {
          ETypeA -> True;
          ETypeB -> False;
          ETypeC -> False;
          ETypeD -> False;
          ETypeE -> False;
          ETypeF -> False;
          ETypeG -> False;
          ETypeH -> False
        };
      ETypeB -> case b_ai0 of _ {__DEFAULT -> False; ETypeB -> True};
      ETypeC -> case b_ai0 of _ {__DEFAULT -> False; ETypeC -> True};
      ETypeD -> case b_ai0 of _ {__DEFAULT -> False; ETypeD -> True};
      ETypeE -> case b_ai0 of _ {__DEFAULT -> False; ETypeE -> True};
      ETypeF -> case b_ai0 of _ {__DEFAULT -> False; ETypeF -> True};
      ETypeG -> case b_ai0 of _ {__DEFAULT -> False; ETypeG -> True};
      ETypeH -> case b_ai0 of _ {__DEFAULT -> False; ETypeH -> True}
    }

Am I misinterpreting the GHC core output? Shouldn't algebraic data types provide an integer id for each constructor, which could then be compared directly in O(1)? Also, why does the first case clause for ETypeA not make use of __DEFAULT as the other clauses do?

update:

As per suggestion by Simon Marlow, I addad a 9th constructor ETypeI, and then GHC switched to using dataToOtag#:

$fEqEType_$c/= =
  \ (a_ahS :: EType) (b_ahT :: EType) ->
    case dataToTag# @ EType a_ahS of a#_ahQ {
      __DEFAULT ->
        case dataToTag# @ EType b_ahT of b#_ahR {
          __DEFAULT ->
            case ==# a#_ahQ b#_ahR of _ {
              False -> True; True -> False
            }
        }
    }

For me, this adds the question as to what the trade-offs  between GHC core's case and use of dataToTag# are, and why this particular cut-off of 9 constructors for using dataToTag# is implemented in GHC.


来源: stackexchange

问:
"implicit declaration of function" in utarray.h (part of uthash)
I'm using utarray (part of the uthash library) for a project. Whenever I include it, I get the following error:

utarray.h:221:3: error: implicit declaration of function ‘strdup’ [-Wimplicit-function-declaration]
```

<p>Admittedly, I use some pretty aggressive flags when compiling (<code>-Wall -Wpedantic -Wextra -Werror -pedantic-errors -std=c99</code>), but I don't understand why this should be an error at all. <code>strdup</code> is defined in <code>string.h</code> (according to <code>man strdup</code>) which is very clearly included from <code>utarray.h</code>.</p>

<p>What am I doing wrong? Google was no help. (apparently nobody else tries to compile <code>utarray.h</code> with these flags?)</p>

<p>Here's an example file that fails to compile (using <code>gcc -Wall -Wpedantic -Wextra -Werror -pedantic-errors -std=c99 scratch.c</code>).
</p>

<pre class="lang-c prettyprint-override"><code>#include "utarray.h"

int main(int argc, char *argv[]) {
    (void)argc;
    (void)argv;
    return 0;
}
</code>```

versions: gcc 4.9.2, glibc 2.21, uthash 1.9.9

答:
I had the same error with strdup), so I added the dummy prototype statement

```<code>char * strdup(char *) ;
</code>```

I don’t get the error message anymore.

ContentLicense: CC BY-SA 3.0

Body:
I'm using utarray (part of the uthash library) for a project. Whenever I include it, I get the following error:

utarray.h:221:3: error: implicit declaration of function ‘strdup’ [-Wimplicit-function-declaration]

Admittedly, I use some pretty aggressive flags when compiling (-Wall -Wpedantic -Wextra -Werror -pedantic-errors -std=c99), but I don't understand why this should be an error at all. strdup is defined in string.h (according to man strdup) which is very clearly included from utarray.h.

What am I doing wrong? Google was no help. (apparently nobody else tries to compile utarray.h with these flags?)

Here's an example file that fails to compile (using gcc -Wall -Wpedantic -Wextra -Werror -pedantic-errors -std=c99 scratch.c).

#include "utarray.h"

int main(int argc, char *argv[]) {
    (void)argc;
    (void)argv;
    return 0;
}

versions: gcc 4.9.2, glibc 2.21, uthash 1.9.9

Body:
I had the same error with strdup), so I added the dummy prototype statement

char * strdup(char *) ;

I don’t get the error message anymore.

ContentLicense: CC BY-SA 4.0


问:
Gitkraken doesn't show branches and commits
When I try to open a repository in a xampp server with Gitkraken I can't view branches or commits, just the message "Displaying 2000 commits. Adjust this setting in Preferences". I tried to reinstall Gitkraken, reopen the repository and reboot xampp/my computer but it didn't work. My computer is a MacBook Pro (Retina, 13-inch, Early 2015) with macOS Mojave 10.14.6.

答: I deleted my repository and installed again. The error is gone.</p>


问:
pass json data to onclick jquery function
I am trying to pass JSON object to onclick function but it does not work

```<code>              $.each(response, function(k, v) {
                    html += "<tr>";
                    html += "   <td><a  onclick='showcomplaints('+ v.ID +')'  >" + v.ID + "</a></td>";
                    html += "   <td>" + v.Name + "</td>";
                    html += '  </tr>';
               });

            function showcomplaints(id)
            {
             alert(id);
            }
</code>```

I get this error "Uncaught SyntaxError: Unexpected end of input" in console window.

答:
Here you need to fix this line in your code:

```<code>html += "   <td><a  onclick='showcomplaints('v.ID')'  >" + v.ID + "</a></td>";
</code>```

As:

```<code>html += "   <td><a  onclick='showcomplaints("+v.ID+")'  >" + v.ID + "</a></td>";
</code>```

the reason for this is you are calling a function showcomplaints which requires id and instead of this you were passing a string v.ID

hope this helps you in future : https://www.w3schools.com/js/js_strings.asp

Body:
I am trying to pass JSON object to onclick function but it does not work

              $.each(response, function(k, v) {
                    html += "
";
                    html += "   " + v.ID + "	";
                    html += "   " + v.Name + "	";
                    html += '
';
               });

            function showcomplaints(id)
            {
             alert(id);
            }

I get this error "Uncaught SyntaxError: Unexpected end of input" in console window.

Body:
Here you need to fix this line in your code:

html += "   <td><a  onclick='showcomplaints('v.ID')'  >" + v.ID + "</a></td>";

As:

html += "   <td><a  onclick='showcomplaints("+v.ID+")'  >" + v.ID + "</a></td>";

the reason for this is you are calling a function showcomplaints which requires id and instead of this you were passing a string v.ID

hope this helps you in future : https://www.w3schools.com/js/js_strings.asp


问:
Facing issue of Real face detection in Vision Framework
I have faced the issue of real face detection using Vision Framework.
I have referred below apple link.

```<code>https://developer.apple.com/documentation/vision/tracking_the_user_s_face_in_real_time
</code>```

I used demo code provided in above link. I see, Camera can detect the face from printed photo or passport photo. It is not real face photo. How can I know if this is not real face in camera using Vision framework?

答:
Here is a project link

here I have used camera API for face detection and eye blinking. you can check and customize according to your requirement.

Update: Here is another project for liveness Check using MLKit link

Body:
I have faced the issue of real face detection using Vision Framework.
I have referred below apple link.

https://developer.apple.com/documentation/vision/tracking_the_user_s_face_in_real_time

I used demo code provided in above link. I see, Camera can detect the face from printed photo or passport photo. It is not real face photo. How can I know if this is not real face in camera using Vision framework?


问:
Can not fire the ondialogaccept event handler in Thunderbird 68.5.0 add-on's xul dialog
In my currently writing Thunderbird 68.5.0's addon, the dialog's event handlers both ondialogaccept and ondialogcancel are not fired for unknown reasons.

enter image description here

When clicking the "strangers" button on the sample dialog, the alert is shown.
However clicking the "Accept" button or the "Cancel" button, any alert is not.

The just written code is as follows:

```<code><?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/global.css" type="text/css"?>

<dialog id="sample" title="event handlers"
        xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
        buttons="accept,cancel"
        ondialogaccept="window.alert('Hi!');return true;"
        ondialogcancel="window.alert('Oops!');return true;"
        >

    <button label="strangers" onclick="window.alert('Yip Yip!');" />

</dialog>
</code>```

```<code>// launcher.js
        window.openDialog(
            "chrome://myaddon/content/sample.xul",
            "sampleDlg",
            "resizable,chrome,modal,titlebar,centerscreen");
</code>```

Thank you in advance.

答:
In TB68, the on... handlers do no longer work due to CSP.
In your javascript, you need to load a listener to the event. See the update info to TB 60 in mozilla TB wiki and/or the upgrade info on developer.thunderbird.net

Klaus

Body:
In my currently writing Thunderbird 68.5.0's addon, the dialog's event handlers both ondialogaccept and ondialogcancel are not fired for unknown reasons.

enter image description here

When clicking the "strangers" button on the sample dialog, the alert is shown.
However clicking the "Accept" button or the "Cancel" button, any alert is not.

The just written code is as follows:

<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/global.css" type="text/css"?>

<dialog id="sample" title="event handlers"
        xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
        buttons="accept,cancel"
        ondialogaccept="window.alert('Hi!');return true;"
        ondialogcancel="window.alert('Oops!');return true;"
        >

    <button label="strangers" onclick="window.alert('Yip Yip!');" />

</dialog>

// launcher.js
        window.openDialog(
            "chrome://myaddon/content/sample.xul",
            "sampleDlg",
            "resizable,chrome,modal,titlebar,centerscreen");

Thank you in advance.


问:
Cannot upgrade Angular Material with Angular 8
I did everything described in the update guide (complex app) but it was keep failing at the point of ng update @angular/material with the following error:

```<code>Package "@angular/flex-layout" has an incompatible peer dependency to "@angular/cdk" (requires "^7.0.0-rc.0", would install "8.0.0").
</code>```

答:
You need to update @angular/cli and @angular/core to the latest version of v8.

```<code>ng update @angular/core@8 @angular/cli@8 --force
</code>```

Body:
I did everything described in the update guide (complex app) but it was keep failing at the point of ng update @angular/material with the following error:

Package "@angular/flex-layout" has an incompatible peer dependency to "@angular/cdk" (requires "^7.0.0-rc.0", would install "8.0.0").

Body:
You need to update @angular/cli and @angular/core to the latest version of v8.

ng update @angular/core@8 @angular/cli@8 --force


问:
How do I print the index from this array after I've randomly picked a selection?
I have an array of quotes stored in a json file called quotes.json. I read the file and am able to pick and output a random quote using the code below, but when I try to display the number of the quote, it shows up like Quote [object Object] of 3. What am I doing wrong?

```<code>[
    {"quote": "quote 1"},
    {"quote": "quote 2"},
    {"quote": "quote 3"}
]
</code>```

```<code>let quote_num = quotes[Math.floor(Math.random() * quotes.length)];
let embed = new Discord.RichEmbed()
    .setTitle("Quote")
    .setColor(0x27367A)
    .setFooter(`Listening for ${prefix}`, `${bot_avatar_url}`)
    .setThumbnail(`${bot_avatar_url}`)
    .setTimestamp()
    .addField(`Quote ${quote_num} of ${quotes.length}`, `'${quote_num.quote}'`)

message.channel.send({embed});
</code>```

答:
let's analyze this code

let quote_num = quotes[Math.floor(Math.random() * quotes.length)];
```

<p>Firstly you get random number from the range of your array</p>

<pre class="lang-js prettyprint-override"><code>const index = Math.floor(Math.random() * quotes.length)
</code>```

Then you get object from array of objects by index

let quote_num = quotes[index]
```

<p>So to get index of your object you have to edit your <code>addField</code> method in this way</p>

<pre class="lang-js prettyprint-override"><code>.addField(`Quote ${index} of ${quotes.length}`, `'${quote_num.quote}'`)
</code>```

Summary:
Your quote_num contains resulted object but not it's index in array of objects.

Body:
I have an array of quotes stored in a json file called quotes.json. I read the file and am able to pick and output a random quote using the code below, but when I try to display the number of the quote, it shows up like Quote [object Object] of 3. What am I doing wrong?

[
    {"quote": "quote 1"},
    {"quote": "quote 2"},
    {"quote": "quote 3"}
]

let quote_num = quotes[Math.floor(Math.random() * quotes.length)];
let embed = new Discord.RichEmbed()
    .setTitle("Quote")
    .setColor(0x27367A)
    .setFooter(`Listening for ${prefix}`, `${bot_avatar_url}`)
    .setThumbnail(`${bot_avatar_url}`)
    .setTimestamp()
    .addField(`Quote ${quote_num} of ${quotes.length}`, `'${quote_num.quote}'`)

message.channel.send({embed});

Body:
let's analyze this code

let quote_num = quotes[Math.floor(Math.random() * quotes.length)];

Firstly you get random number from the range of your array

const index = Math.floor(Math.random() * quotes.length)

Then you get object from array of objects by index

let quote_num = quotes[index]

So to get index of your object you have to edit your addField method in this way

.addField(`Quote ${index} of ${quotes.length}`, `'${quote_num.quote}'`)

Summary:
Your quote_num contains resulted object but not it's index in array of objects.


问:
How to (re)send email from a file using mutt or mail?
I have set up exim4 to deliver a copy of all outgoing mails to a local maildir in case something goes wrong. Now something's gone wrong and I need to resend some of the mail from the local maildir.

The emails have their full headers (inc. Return-Path, To, From, Subject etc.) and body (MIME).

Is there a way to do this:

```<code>$ somemailcommand <theemail
</code>```

and have it make a new attempt to deliver it?

I've tried mutt -H theemail which looked promising (although it starts an interactive UI) but the emails came through blank.

I've tried mail anemail@example.com <theemail but that just sent the headers in the body. I'm on Debian Linux.

答:
You can use bounce function (default bound to b key) to resend message and keep original headers.

To do so:

a) bounce single message

just press b

b) bounce multiple messages

tag messages you want using t or T<PATTERN> (see patterns in mutt manual)

then ;b then You'll be asked to fill e-mail address
Bounce tagged messages to:

Body:
I have set up exim4 to deliver a copy of all outgoing mails to a local maildir in case something goes wrong. Now something's gone wrong and I need to resend some of the mail from the local maildir.

The emails have their full headers (inc. Return-Path, To, From, Subject etc.) and body (MIME).

Is there a way to do this:

$ somemailcommand <theemail

and have it make a new attempt to deliver it?

I've tried mutt -H theemail which looked promising (although it starts an interactive UI) but the emails came through blank.

I've tried mail anemail@example.com <theemail but that just sent the headers in the body. I'm on Debian Linux.


问:
Why navbar components doesn't update after user logs in? (no Redux)
I want the Navbar to change state but I couldn't figure out how to pass state from Login to Navbar without using Redux. It only updates the state of the Navbar after I manually refresh the page. This is not good. It would be great if once I click on the Login button, then the Navbar also updates its state. How can I pass the state over?

App component:

```<code>const App = () => {
    return (
        <BrowserRouter>
            <div className="App">
                <Navbar />
                <Switch>
                    <Login exact path="/login" component={Login} />
                    <Signup exact path="/signup" component={Signup} />
                </Switch>
            </div>
        </BrowserRouter>
    );
};
</code>```

Navbar component:

```<code>class Navbar extends React.Component {
    constructor() {
        super();
        this.state = {
            modalOpen: false,
            isAuthenticated: false,
            name: '',
        };
}

componentDidMount() {
        if (localStorage.getItem('token')) {
            this.setState({ isAuthenticated: true });
        }
    }

render() {
        return (
            <div className="navbar">
                <div className="navbar-flex">
                    {this.state.isAuthenticated && <p>Hello {this.state.name}</p>}
                    <Button onClick={this.toggleModal}>Menu</Button>
                </div>
                {this.state.modalOpen && (
                    <div className="modal" ref={this.setWrapperRef}>
                        {!this.state.isAuthenticated ? (
                            <div>
                                <Link to="/">
                                    <Button onClick={() => this.setState({ modalOpen: false })}>Home</Button>
                                </Link>
                                <Link to="/login">
                                    <Button onClick={() => this.setState({ modalOpen: false })}>Login</Button>
                                </Link>
                                <Link to="/signup">
                                    <Button onClick={() => this.setState({ modalOpen: false })}>Signup</Button>
                                </Link>
                            </div>
                        ) : (
                            <div>
                                <Link to="/">
                                    <Button onClick={() => this.setState({ modalOpen: false })}>Home</Button>
                                </Link>
                                <Link to="/">
                                    <Button onClick={this.logout}>Logout</Button>
                                </Link>
                            </div>
                        )}
                    </div>
                )}
            </div>
        );
    }
</code>```

Login component submit method:

```<code>onSubmit = (e) => {
        e.preventDefault();

        this.setState({ loading: true });

        axios
            .post('/api/login', {
                email: this.state.email,
                password: this.state.password,
            })
            .then((res) => {
                if (res.data.token) {
                    localStorage.setItem('token', res.data.token);
                    this.setState({ loading: false });
                    this.props.history.push('/');
                } else if (res.data.status === 'fail') {
                    this.setState({ loading: false });
                }
            });
    };
</code>```

答:
You can put the isAuntheticated state in the App.js container, and then pass the function to update it in Login, and it's state in NavBar.
Something like:

```<code>const App = () => {
const [unauthenticated, setIsAuthenticated] = useState(false);

return (
    <BrowserRouter>
        <div className="App">
            <Navbar />
            <Switch>
                <Login exact path="/login" component={Login} isAuthenticated={isAuthenticated} />
                <Signup exact path="/signup" component={Signup} setIsAuthenticated={setIsAuthenticated} />
            </Switch>
        </div>
    </BrowserRouter>
   );

};
</code>```

And then in login, you can use setIsAunthenticated to update the state along with updating the localstorage.

And then in NavBar in render, you can use !this.state.isAuthenticated || !this.props.isAuthenticated to render your navigation.

Do note that this can work well in small applications, but for large projects you should always use global state like Redux.
Or if you don't want to include any extra libraries, you can use ContextAPI, react's own implementation of global state.

Body:
I want the Navbar to change state but I couldn't figure out how to pass state from Login to Navbar without using Redux. It only updates the state of the Navbar after I manually refresh the page. This is not good. It would be great if once I click on the Login button, then the Navbar also updates its state. How can I pass the state over?

App component:

const App = () => {
    return (
        <BrowserRouter>

                <Navbar />
                <Switch>
                    <Login exact path="/login" component={Login} />
                    <Signup exact path="/signup" component={Signup} />
                </Switch>

        </BrowserRouter>
    );
};

Navbar component:

class Navbar extends React.Component {
    constructor() {
        super();
        this.state = {
            modalOpen: false,
            isAuthenticated: false,
            name: '',
        };
}

componentDidMount() {
        if (localStorage.getItem('token')) {
            this.setState({ isAuthenticated: true });
        }
    }

render() {
        return (

                    {this.state.isAuthenticated &&
Hello {this.state.name}
}
                    <Button onClick={this.toggleModal}>Menu</Button>

                {this.state.modalOpen && (

                        {!this.state.isAuthenticated ? (

                                <Link to="/">
                                    <Button onClick={() => this.setState({ modalOpen: false })}>Home</Button>
                                </Link>
                                <Link to="/login">
                                    <Button onClick={() => this.setState({ modalOpen: false })}>Login</Button>
                                </Link>
                                <Link to="/signup">
                                    <Button onClick={() => this.setState({ modalOpen: false })}>Signup</Button>
                                </Link>

                        ) : (

                                <Link to="/">
                                    <Button onClick={() => this.setState({ modalOpen: false })}>Home</Button>
                                </Link>
                                <Link to="/">
                                    <Button onClick={this.logout}>Logout</Button>
                                </Link>

                        )}

                )}

        );
    }

Login component submit method:

onSubmit = (e) => {
        e.preventDefault();

        this.setState({ loading: true });

        axios
            .post('/api/login', {
                email: this.state.email,
                password: this.state.password,
            })
            .then((res) => {
                if (res.data.token) {
                    localStorage.setItem('token', res.data.token);
                    this.setState({ loading: false });
                    this.props.history.push('/');
                } else if (res.data.status === 'fail') {
                    this.setState({ loading: false });
                }
            });
    };

Body:
You can put the isAuntheticated state in the App.js container, and then pass the function to update it in Login, and it's state in NavBar.
Something like:

const App = () => {
const [unauthenticated, setIsAuthenticated] = useState(false);

return (
    <BrowserRouter>
        <div className="App">
            <Navbar />
            <Switch>
                <Login exact path="/login" component={Login} isAuthenticated={isAuthenticated} />
                <Signup exact path="/signup" component={Signup} setIsAuthenticated={setIsAuthenticated} />
            </Switch>
        </div>
    </BrowserRouter>
   );

};

And then in login, you can use setIsAunthenticated to update the state along with updating the localstorage.

And then in NavBar in render, you can use !this.state.isAuthenticated || !this.props.isAuthenticated to render your navigation.

Do note that this can work well in small applications, but for large projects you should always use global state like Redux.
Or if you don't want to include any extra libraries, you can use ContextAPI, react's own implementation of global state.


问:
Quick Sort Python
I just started learning python. I received an error trying to implement Quick Sort into my program. TypeError: recQuickSort() missing 1 required positional argument: 'last'. Personally, I don't think there's anything wrong with it because I acquired it from my school's lecture. The only problem I'm facing is how to implement it to sort a dictionary. How do I go about calling the function? </p>

<p>Below is my code: </p>

```<code># Quick Sort

# Sorts an array or list using the recursive quick sort algorithm
def quickSort(theSeq):
    n = len(theSeq)
    recQuickSort(theSeq, 0, n - 1)

# The recursive "in-place" implementation
def recQuickSort(theSeq, first, last):
    # Check the base case (range is trivially sorted)
    if first >= last:
        return
    else:
        # Partition the sequence and obtain the pivot position
        pos = partitionSeq(theSeq, first, last)
        # Repeat the process on the two subsequences
        recQuickSort(theSeq, first, pos - 1)
        recQuickSort(theSeq, pos + 1, last)

# Partitions the subsequence using the first key as the pivot
def partitionSeq(theSeq, first, last):
    # Save a copy of the pivot value.
    pivot = theSeq[first] # first element of range is pivot
    # Find the pivot position and move the elements around the pivot
    left = first + 1 # will scan rightward
    right = last # will scan leftward
    while left <= right:
    # Scan until reaches value equal or larger than pivot (or right marker)
        while left <= right and theSeq[left] < pivot:
            left += 1
    # Scan until reaches value equal or smaller than pivot (or left marker)
        while left <= right and theSeq[right] > pivot:
            right -= 1
        # Scans did not strictly cross
        if left <= right:
        # swap values
            theSeq[left], theSeq[right] = theSeq[right], theSeq[left]
        # Shrink range (Recursion: Progress towards base case)
            left += 1
            right -= 1
    # Put the pivot in the proper position (marked by the right index)
    theSeq[first], theSeq[right] = theSeq[right], pivot
    # Return the index position of the pivot value.
    return right
</code>```

答:
I copy pasted your code, and it is working fine (Python 2.7.16 here).

Here is an example on how to call you function:

```<code>a = [3,2,1]
quickSort(a)
# [1, 2, 3]

b = [10,9,8,7,1,2,3,4,5]
quickSort(b)
# [1, 2, 3, 4, 5, 7, 8, 9, 10]
</code>```

Obs.: I do not receive the error you mentioned.

Title: Quick Sort Python

Body:
I just started learning python. I received an error trying to implement Quick Sort into my program. TypeError: recQuickSort() missing 1 required positional argument: 'last'. Personally, I don't think there's anything wrong with it because I acquired it from my school's lecture. The only problem I'm facing is how to implement it to sort a dictionary. How do I go about calling the function?

Below is my code:

# Quick Sort

# Sorts an array or list using the recursive quick sort algorithm
def quickSort(theSeq):
    n = len(theSeq)
    recQuickSort(theSeq, 0, n - 1)

# The recursive "in-place" implementation
def recQuickSort(theSeq, first, last):
    # Check the base case (range is trivially sorted)
    if first >= last:
        return
    else:
        # Partition the sequence and obtain the pivot position
        pos = partitionSeq(theSeq, first, last)
        # Repeat the process on the two subsequences
        recQuickSort(theSeq, first, pos - 1)
        recQuickSort(theSeq, pos + 1, last)

# Partitions the subsequence using the first key as the pivot
def partitionSeq(theSeq, first, last):
    # Save a copy of the pivot value.
    pivot = theSeq[first] # first element of range is pivot
    # Find the pivot position and move the elements around the pivot
    left = first + 1 # will scan rightward
    right = last # will scan leftward
    while left <= right:
    # Scan until reaches value equal or larger than pivot (or right marker)
        while left <= right and theSeq[left] < pivot:
            left += 1
    # Scan until reaches value equal or smaller than pivot (or left marker)
        while left <= right and theSeq[right] > pivot:
            right -= 1
        # Scans did not strictly cross
        if left <= right:
        # swap values
            theSeq[left], theSeq[right] = theSeq[right], theSeq[left]
        # Shrink range (Recursion: Progress towards base case)
            left += 1
            right -= 1
    # Put the pivot in the proper position (marked by the right index)
    theSeq[first], theSeq[right] = theSeq[right], pivot
    # Return the index position of the pivot value.
    return right

Body:
I copy pasted your code, and it is working fine (Python 2.7.16 here).

Here is an example on how to call you function:

a = [3,2,1]
quickSort(a)
# [1, 2, 3]

b = [10,9,8,7,1,2,3,4,5]
quickSort(b)
# [1, 2, 3, 4, 5, 7, 8, 9, 10]

Obs.: I do not receive the error you mentioned.


问:
Paypal wallet creation using java for a mobile app
I need to integrate paypal wallet for a e-commerce application. is there any way to create using java.  Can you share any api links and integration steps. thank you.</p>

答:
You'll have to be more specific about what you mean by "paypal wallet" -- but if you mean a PayPal Checkout with a Java backend, the server-side SDK is here: https://github.com/paypal/Checkout-Java-SDK

There's some documentation here: https://developer.paypal.com/docs/checkout/reference/server-integration/set-up-transaction/ -- in particular you'll need routes on your server to 'Set Up Transaction' and 'Capture Transaction'.

Once you have those two routes to create and capture an order, they can be paired with the web front-end: https://developer.paypal.com/demo/checkout/#/pattern/server


问:
How to work with Apache Spark using Intellij Idea?
I want to know what is the best way to work with Apache Spark using Intellij Idea? (specially for Scala programming language)

Please explain step-by-step if you can.

Thanks for answer

答:
Setup a Scala development environment with IntelliJ. See Scala - Getting Started.

JDK is required since Scala is a JVM language

sbt is the build tool

IntelliJ can be the IDE

To the Scala environment, add the Spark dependency. See Spark - Getting Started.

Execute the application using spark-submit

The links provide simple working examples which you can extend to write your own application.


问:
How to paste two matlab graphs together?
I have two Matlab graphs. The first graph is a histogram with the range from 0 to 1 only. Another graph is a histogram with the range from 100 to 120. If I plot the two histograms on the same graph simultaneously, we can obtain a plot such that the first histogram is too narrow which is difficult to view. So I would like to generate the first graph and the second graph separately and paste them together. So the final graph would paste two graphs together. My idea is in a new graph with axis range from 0 to 5, I plot the first histogram with the range from 0 to 1 and plot the second histogram with the range from 3 to 5, then relabel the x-tick to the desired values. Are there any ways to do it?</p>

答:
Following your idea, rescale your data [100,120] -> [3,5], and relabel the x-axis.

```<code>A = rand(100,1);
B = 100 + 20*rand(100,1);

figure
hist(A, 5) %adjust number of bins to better match width of other hist
hold on
Bb = (B-100)/20*2 + 3;
hist(Bb)
set(gca, 'xtick', 0:5)
set(gca, 'xticklabel', {'0', '1', '', '100', '110', '120'})
</code>```

ps. Why don't you use subplot?

Body:
Following your idea, rescale your data [100,120] -> [3,5], and relabel the x-axis.

A = rand(100,1);
B = 100 + 20*rand(100,1);

figure
hist(A, 5) %adjust number of bins to better match width of other hist
hold on
Bb = (B-100)/20*2 + 3;
hist(Bb)
set(gca, 'xtick', 0:5)
set(gca, 'xticklabel', {'0', '1', '', '100', '110', '120'})

ps. Why don't you use subplot?


问:
How to resolve "SSLRead() return error -9841" error in source tree
I am getting

SSLRead() return error -9841

error whenever I try top perform any action like - fetch, checkout in source tree.

Any pointers would help. Thanks.

答:
I had the same issue -9841.

I fixed it using git config http.sslVerify true.

You can check http.sslverify using this git config --global --list


问:
Get the array of objects from query parameters in javascript
I'm trying to parse the array from the url query parameters. The url is as below which contains the array of emp objects specified in query parameters

```<code>http://localhost:8080/list?emp[0].id=21&emp[0].name=john&emp[1].id=22&emp[1].name=tom
</code>```

Can someone please help me with the function that will parse such query params(with some ReGEX maybe) and returns the array as below

```<code>[{id:'21',name:'john'},{id:'22',name:'tom'}]
</code>```

Note: There could be any number of emp objects mentioned in the query params, for example purpose I've just added two.
I've looked for similar solutions but none of them seems to return the array which has its objects specified in the query params with the index value. So please don't mark the question as duplicate

Edit: I've written the below function which works for fetching simple query params but doesn't work for array of objects specified in query param as above.

```<code>export const getQueryParamByName = (name, url) => {
    if (!url) url = window.location.href;
    name = name.replace(/[[\]]/g, '\\$&');
    const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
    const results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
</code>```

答:
You may match id and name pair with the following regex:

```<code>(emp\[\d+]\.)id=(\d+)&\1name=([^&]+)
</code>```

(demo)

and then iterate through all such matches returned by matchAll() to build the array of id-name objects:

const extractObjects = url => {
  const regex = /(emp\[\d+]\.)id=(\d+)&\1name=([^&]+)/g;
  const result = [];
  for (const match of url.matchAll(regex)) {
    result.push({id: match[2], name: match[3]});
  }
  return result;
}

const url = 'http://localhost:8080/list?emp[0].id=21&emp[0].name=john&emp[1].id=22&emp[1].name=tom';
const objects = extractObjects(url);
console.log(objects);```

Body:
I'm trying to parse the array from the url query parameters. The url is as below which contains the array of emp objects specified in query parameters

http://localhost:8080/list?emp[0].id=21&emp[0].name=john&emp[1].id=22&emp[1].name=tom

Can someone please help me with the function that will parse such query params(with some ReGEX maybe) and returns the array as below

[{id:'21',name:'john'},{id:'22',name:'tom'}]

Note: There could be any number of emp objects mentioned in the query params, for example purpose I've just added two.
I've looked for similar solutions but none of them seems to return the array which has its objects specified in the query params with the index value. So please don't mark the question as duplicate

Edit: I've written the below function which works for fetching simple query params but doesn't work for array of objects specified in query param as above.

export const getQueryParamByName = (name, url) => {
    if (!url) url = window.location.href;
    name = name.replace(/[[\]]/g, '\\$&');
    const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
    const results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

Body:
You may match id and name pair with the following regex:

(emp\[\d+]\.)id=(\d+)&\1name=([^&]+)

(demo)

and then iterate through all such matches returned by matchAll() to build the array of id-name objects:

const extractObjects = url => {
  const regex = /(emp\[\d+]\.)id=(\d+)&\1name=([^&]+)/g;
  const result = [];
  for (const match of url.matchAll(regex)) {
    result.push({id: match[2], name: match[3]});
  }
  return result;
}

const url = 'http://localhost:8080/list?emp[0].id=21&emp[0].name=john&emp[1].id=22&emp[1].name=tom';
const objects = extractObjects(url);
console.log(objects);


问:
UWP: Retrieving installed fonts causes exception
In my UWP app, I have been retrieving the installed fonts using

```<code>try
   {
       var fonts = CanvasTextFormat.GetSystemFontFamilies();
       return (fonts.Length>0) ? fonts.OrderBy(f => f).ToList() : new List<string>();
   }
   catch (Exception)
   {
       return new List<string>();
   }
</code>```

Worked fine, until it did no longer. Now, I am getting the exception

```<code>{System.IO.FileNotFoundException: The specified module could not be found. (Exception from HRESULT: 0x8007007E)
   at System.StubHelpers.StubHelpers.GetWinRTFactoryObject(IntPtr pCPCMD)
   at Microsoft.Graphics.Canvas.Text.CanvasTextFormat.GetSystemFontFamilies()
   at FontHelper.<>c.<LoadInstalledFonts>b__11_0()}
</code>```

I have moved this section into the UI Dispatcher, thinking that maybe there were restrictions in when and by whome GetSystemFontFamilies() can get called. That did not prevent the exception.

What is most galling: it worked before. No changes, now it just stopped working... Win2D is part of the project in version 1.25.0.

Any idea what might be causing this?

答:
UWP: Retrieving installed fonts causes exception

I can't reproduce your issue, But I have other way to get the system font info with SharpDx.Direct2D1 nuget package.

```<code>public void GetFontLibrary()
        {
            SharpDX.DirectWrite.Factory factory = new SharpDX.DirectWrite.Factory();

            var fontCollection = factory.GetSystemFontCollection(false);
            var familCount = fontCollection.FontFamilyCount;

            for (int i = 0; i < familCount; i++)
            {
                var fontFamily = fontCollection.GetFontFamily(i);
                var familyNames = fontFamily.FamilyNames;

                int index;

                if (!familyNames.FindLocaleName(CultureInfo.CurrentCulture.Name, out index))
                {
                    if (!familyNames.FindLocaleName("en-us", out index))
                    {
                        index = 0;
                    }
                }

                string name = familyNames.GetString(index);

                FontList.Add(name);
            }

        }
</code>```

Body:
In my UWP app, I have been retrieving the installed fonts using

try
   {
       var fonts = CanvasTextFormat.GetSystemFontFamilies();
       return (fonts.Length>0) ? fonts.OrderBy(f => f).ToList() : new List<string>();
   }
   catch (Exception)
   {
       return new List<string>();
   }

Worked fine, until it did no longer. Now, I am getting the exception

{System.IO.FileNotFoundException: The specified module could not be found. (Exception from HRESULT: 0x8007007E)
   at System.StubHelpers.StubHelpers.GetWinRTFactoryObject(IntPtr pCPCMD)
   at Microsoft.Graphics.Canvas.Text.CanvasTextFormat.GetSystemFontFamilies()
   at FontHelper.<>c.<LoadInstalledFonts>b__11_0()}

I have moved this section into the UI Dispatcher, thinking that maybe there were restrictions in when and by whome GetSystemFontFamilies() can get called. That did not prevent the exception.

What is most galling: it worked before. No changes, now it just stopped working... Win2D is part of the project in version 1.25.0.

Any idea what might be causing this?

Body:
UWP: Retrieving installed fonts causes exception

I can't reproduce your issue, But I have other way to get the system font info with SharpDx.Direct2D1 nuget package.

public void GetFontLibrary()
        {
            SharpDX.DirectWrite.Factory factory = new SharpDX.DirectWrite.Factory();

            var fontCollection = factory.GetSystemFontCollection(false);
            var familCount = fontCollection.FontFamilyCount;

            for (int i = 0; i < familCount; i++)
            {
                var fontFamily = fontCollection.GetFontFamily(i);
                var familyNames = fontFamily.FamilyNames;

                int index;

                if (!familyNames.FindLocaleName(CultureInfo.CurrentCulture.Name, out index))
                {
                    if (!familyNames.FindLocaleName("en-us", out index))
                    {
                        index = 0;
                    }
                }

                string name = familyNames.GetString(index);

                FontList.Add(name);
            }

        }


问:
Extract first element from multi dimensional array from pandas dataframe
I have a data frame consists of reviews column which is a multi dimensional array, I would like to extract first element as shown below,

Suppose df['Reviews'] consists of following rows

I want the output in a separate column as shown below,

Please find sample data 3 values for the column below:

df['Reviews'] =
[['Just like home', 'A Warm Welcome to Wintry Amsterdam'], ['01/03/2018', '01/01/2018']]
[['Great food and staff', 'just perfect'], ['01/06/2018', '01/04/2018']]
[['Satisfaction', 'Delicious old school restaurant'], ['01/04/2018', '01/04/2018']]

Please help

答:
You need to add in the following for your dataframe access as per your need.
This will create a new column named output with the appropriate requirement

Apply Function

```<code>df['output'] = df.Reviews.apply(lambda x: x[0])
</code>```

Map Function

```<code>df.loc[:, 'output'] = df.Reviews.map(lambda x: x[0])
</code>```

Body:
You need to add in the following for your dataframe access as per your need.
This will create a new column named output with the appropriate requirement

Apply Function

df['output'] = df.Reviews.apply(lambda x: x[0])

Map Function

df.loc[:, 'output'] = df.Reviews.map(lambda x: x[0])


问:
How to name excel files as the names of the data frames in a list in R
I have a large list with more than 100 data frames in it. For simplification I show a list with three data frames (dummy data). I would like to write each data frame into an excel file by using openxlsx. I already created a loop, in which each data frame becomes on excel file, but I want to name each excel file as the name of the data frame. How can I get each excel file named as the data frame in the list??
So DF1 should become DF1.xlsx. DF2 should become DF2.xlsx. DF should become DF3.xlsx.But at the moment each excel file is name 1,2 or 3.
My loop:

```<code>for (i in (1:3)) {write.xlsx(listDF[i],file=paste(i,".xlsx"))}
</code>```

```<code># dummy data
listDF <- list(
  DF1 = data.frame(
    sample = c("TGX", "TGX", "TGX", "TGX"),
    RC = c(0, 1, 2, 3),
    medRC = c(0, 3, 4, 0),
    RC.norm = c(0, 3, 3, 3),
    medRC.norm = c(0, 3, 3, 3)
  ),
  DF2 = data.frame(
    sample = c("TBF", "TBF", "TBF", "TBF"),
    RC = c(2, 1, 2, 3),
    medRC = c(4, 3, 4, 0),
    RC.norm = c(1, 3, 3, 3),
    medRC.norm = c(0, 3, 3, 3)
  ),
  DF3 = data.frame(
    sample = c("TZW", "TZW", "TZW", "TZW"),
    RC = c(4, 3, 2, 3),
    medRC = c(1, 3, 2, 0),
    RC.norm = c(1, 1, 1, 1),
    medRC.norm = c(0, 7, 5, 3)
  )
</code>```

```<code>    listDF

    # $DF1
    #   sample  RC medRC RC.norm medRC.norm
    # 1  TGX    0     0       0          0
    # 2  TGX    1     3       3          3
    # 3  TGX    2     4       3          3
    # 4  TGX    3     0       3          3

    # $DF2
    #   sample RC medRC RC.norm medRC.norm
    # 1  TBF   2     4       1       0
    # 3  TBF   1     3       3       3
    # 4  TBF   2     4       3       3
    # 5  TBF   3     0       3       3

    # $DF3
    #   sample  RC medRC RC.norm medRC.norm
    # 1  TZW    4     1       1          0
    # 2  TZW    3     3       1          7
    # 3  TZW    2     2       1          5
    # 4  TZW    3     0       1          3
</code>```

答:
You can use purrr's imap using which you can access data and name.

```<code>purrr::imap(listDF, ~openxlsx::write.xlsx(.x, paste0(.y, '.xlsx')))
</code>```

Or in base using Map :

```<code>Map(openxlsx::write.xlsx, listDF, paste0(names(listDF), '.xlsx'))
</code>```

Body:
I have a large list with more than 100 data frames in it. For simplification I show a list with three data frames (dummy data). I would like to write each data frame into an excel file by using openxlsx. I already created a loop, in which each data frame becomes on excel file, but I want to name each excel file as the name of the data frame. How can I get each excel file named as the data frame in the list??
So DF1 should become DF1.xlsx. DF2 should become DF2.xlsx. DF should become DF3.xlsx.But at the moment each excel file is name 1,2 or 3.
My loop:

for (i in (1:3)) {write.xlsx(listDF[i],file=paste(i,".xlsx"))}

# dummy data
listDF <- list(
  DF1 = data.frame(
    sample = c("TGX", "TGX", "TGX", "TGX"),
    RC = c(0, 1, 2, 3),
    medRC = c(0, 3, 4, 0),
    RC.norm = c(0, 3, 3, 3),
    medRC.norm = c(0, 3, 3, 3)
  ),
  DF2 = data.frame(
    sample = c("TBF", "TBF", "TBF", "TBF"),
    RC = c(2, 1, 2, 3),
    medRC = c(4, 3, 4, 0),
    RC.norm = c(1, 3, 3, 3),
    medRC.norm = c(0, 3, 3, 3)
  ),
  DF3 = data.frame(
    sample = c("TZW", "TZW", "TZW", "TZW"),
    RC = c(4, 3, 2, 3),
    medRC = c(1, 3, 2, 0),
    RC.norm = c(1, 1, 1, 1),
    medRC.norm = c(0, 7, 5, 3)
  )

    listDF

    # $DF1
    #   sample  RC medRC RC.norm medRC.norm
    # 1  TGX    0     0       0          0
    # 2  TGX    1     3       3          3
    # 3  TGX    2     4       3          3
    # 4  TGX    3     0       3          3

    # $DF2
    #   sample RC medRC RC.norm medRC.norm
    # 1  TBF   2     4       1       0
    # 3  TBF   1     3       3       3
    # 4  TBF   2     4       3       3
    # 5  TBF   3     0       3       3

    # $DF3
    #   sample  RC medRC RC.norm medRC.norm
    # 1  TZW    4     1       1          0
    # 2  TZW    3     3       1          7
    # 3  TZW    2     2       1          5
    # 4  TZW    3     0       1          3

Body:
You can use purrr's imap using which you can access data and name.

purrr::imap(listDF, ~openxlsx::write.xlsx(.x, paste0(.y, '.xlsx')))

Or in base using Map :

Map(openxlsx::write.xlsx, listDF, paste0(names(listDF), '.xlsx'))


问:
How to solve date format problem when using Window XP in C?
I am using Window 7, when I run my code in local everything is alright, but when upload to Window server 2003 the code will coming error:

"String was not recognized as a valid DateTime"

My computer setting (date format) all same with my window server. Still come out the same problem.

below is my code:

```<code>dateFrom = Convert.ToDateTime("12-6-2011");

dateTo = Convert.ToDateTime("18-6-2011");

//or
dateFrom = DateTime.ParseExact("12-6-2011", "MM/dd/yyyy", CultureInfo.InvariantCulture);

dateTo = DateTime.ParseExact("18-6-2011", "MM/dd/yyyy", CultureInfo.InvariantCulture);

//i using parse also din come out.
</code>```

答:
Try:</p>

```<code>dateFrom = DateTime.ParseExact("12-6-2011", "dd-MM-yyyy", CultureInfo.InvariantCulture);
dateTo = DateTime.ParseExact("18-6-2011", "dd-MM-yyyy", CultureInfo.InvariantCulture);
</code>```

Body:
I am using Window 7, when I run my code in local everything is alright, but when upload to Window server 2003 the code will coming error:

"String was not recognized as a valid DateTime"

My computer setting (date format) all same with my window server. Still come out the same problem.

below is my code:

dateFrom = Convert.ToDateTime("12-6-2011");

dateTo = Convert.ToDateTime("18-6-2011");

//or
dateFrom = DateTime.ParseExact("12-6-2011", "MM/dd/yyyy", CultureInfo.InvariantCulture);

dateTo = DateTime.ParseExact("18-6-2011", "MM/dd/yyyy", CultureInfo.InvariantCulture);

//i using parse also din come out.

Body:
Try:

dateFrom = DateTime.ParseExact("12-6-2011", "dd-MM-yyyy", CultureInfo.InvariantCulture);
dateTo = DateTime.ParseExact("18-6-2011", "dd-MM-yyyy", CultureInfo.InvariantCulture);


问:
MongoDB mongoose findOneAndUpdate() Await does not wait. A3 runs before A2
A3 log runs before A2. How do I fix this? I want to wait until the update returns and use the result for the next logic. Thanks in Advance.</p>

```<code>const MongoClient = require("mongodb").MongoClient;

console.log('A1');
   // Inserting into DB
   await db.collection(companyCollection).findOneAndUpdate({"_id": new mongo.ObjectID(companyId)}, {$set: company}, {upsert: false}, await async function (err, result) {
      console.log('A2');
      let resultRes = null;
      if (err) {
         resultRes = { success: false };
      } else {
         resultRes = { success: true };
      }
      return callback(err ? true : false, resultRes);
 });
console.log('A3');
</code>```

答:
findOneAndUpdate has two signatures, either return a promise, or call a callback. Your version utilizes the callback version, hence adding the await is pointless because no promise is being returned.

Here's a simple re-write that utilizes the promise syntax:

```<code>const MongoClient = require("mongodb").MongoClient;

async function doSomething() {
    console.log('A1');
    // Inserting into DB
    let result = await db.collection(companyCollection).findOneAndUpdate({"_id": new mongo.ObjectID(companyId)}, {$set: company}, {upsert: false});
    console.log('A2');

    ... do whatever you want ...
    console.log('A3');
}

return doSomething();
</code>```

Body:
A3 log runs before A2. How do I fix this? I want to wait until the update returns and use the result for the next logic. Thanks in Advance.

const MongoClient = require("mongodb").MongoClient;

console.log('A1');
   // Inserting into DB
   await db.collection(companyCollection).findOneAndUpdate({"_id": new mongo.ObjectID(companyId)}, {$set: company}, {upsert: false}, await async function (err, result) {
      console.log('A2');
      let resultRes = null;
      if (err) {
         resultRes = { success: false };
      } else {
         resultRes = { success: true };
      }
      return callback(err ? true : false, resultRes);
 });
console.log('A3');

Body:
findOneAndUpdate has two signatures, either return a promise, or call a callback. Your version utilizes the callback version, hence adding the await is pointless because no promise is being returned.

Here's a simple re-write that utilizes the promise syntax:

const MongoClient = require("mongodb").MongoClient;

async function doSomething() {
    console.log('A1');
    // Inserting into DB
    let result = await db.collection(companyCollection).findOneAndUpdate({"_id": new mongo.ObjectID(companyId)}, {$set: company}, {upsert: false});
    console.log('A2');

    ... do whatever you want ...
    console.log('A3');
}

return doSomething();


问:
JQuery SVG graph - overlapping bars
I'm trying to learn SVG graphs, I've nearly completed my graph however I currently have overlapping bars, I believe this is due to a combination of my x axis return data and my json data. My x axis lists the months from my JSON data, but my JSON data can have multiple entries from the same month. and if this is the case then my entries will overlap for that month. What I need to do is return the month + day seperately, however I haven't been able to figure out how just yet.

JSON data example where there's 2 entries for the same month:

```<code>1: {dayNo: 2, monthNo: 7, monthName: "July", year: 2018, recordDate: "2018-07-02T00:00:00",…}
avgVolume: 3585.53
dayNo: 2
monthName: "July"
monthNo: 7
recordDate: "2018-07-02T00:00:00"
volumeLastYear: 4109.47
volumeToday: 3575.34
year: 2018
2: {dayNo: 30, monthNo: 7, monthName: "July", year: 2018, recordDate: "2018-07-30T00:00:00",…}
avgVolume: 3291.55
dayNo: 30
monthName: "July"
monthNo: 7
recordDate: "2018-07-30T00:00:00"
volumeLastYear: 3996.31
volumeToday: 3414.44
year: 2018
</code>```

And here is the svg code:

```<code>            $request.done(function (response) {
            // remove old svg
            $('svg').remove();

            // create svg element
            var $svg = d3.select('.card.mb-3.clickable-card.highlight')
                .append('svg')
                .attr('width', '100%')
                .attr('height', '400px')
                .attr('style', 'background-color: lavender')
                .classed('svg display-svg', true);

            // 2 determine size of svg element
            var w = $svg.node().getBoundingClientRect().width;
            var h = $svg.node().getBoundingClientRect().height;

            // 10 chart margins
            var chartMargin = new Object();
            chartMargin.left = 40;
            chartMargin.right = 25;
            chartMargin.top = 25;
            chartMargin.bottom = 40;

            // 10 cont
            h = h - chartMargin.bottom - chartMargin.top;

            // Max volume
            var maxVolume = d3.max(response, d => d.avgVolume);

            // bar Margins / width
            var barMargin = 10;
            var barWidth = (w - chartMargin.left - chartMargin.right) / response.length;

            // yScale
            var yScale = d3.scaleLinear()
                .domain([0, maxVolume])
                .range([h, chartMargin.top]);

            // xScale
            var xScale = d3.scaleBand()
                .domain(response.map(function (d) { return d.monthName; }))
                .range([0, w - chartMargin.left - chartMargin.right])
                .paddingInner(0.15);

            // chartGroup
            var chartGroup = $svg.append('g')
                .classed('chartGroup', true)
                .attr('transform', 'translate(' + chartMargin.left + ',' + chartMargin.top + ')');

            // 5
            var barGroups = chartGroup
                .selectAll('g')
                .data(response);

            // 6
            var newBarGroups = barGroups.enter()
                .append('g')
                .attr('transform', function (d, i) {
                    return 'translate('
                        + (xScale(d.monthName))
                        + ','
                        + (yScale(d.avgVolume))
                        + ')';
                })

            // yAxis label
            var yAxis = d3.axisLeft(yScale);
            chartGroup.append('g')
                .classed('axis y', true)
                .attr('transform', 'translate(' + -20 + ', ' + h / 2 + ')')
                .append('text')
                .attr('transform', 'rotate(-90)')
                .attr('dx', '-0.8em')
                .attr('dy', '0.25em')
                .attr("text-anchor", 'middle')
                .text("Reservoir Volume (ML)");

            // xAxis label
            var xAxis = d3.axisBottom(xScale);
            chartGroup.append('g')
                .attr('transform', 'translate(0,' + h + ')')
                .classed('axis x', true)
                .call(xAxis);

            newBarGroups
                .append('rect')
                .attr('x', 0)
                .attr('height', function (d, i) {
                    return h - yScale(d.avgVolume);
                })

                // animation
                .style('fill', 'transparent')
                .transition().duration(function (d, i) { return i * 500; })
                .delay(function (d, i) { return i + 200; })

                .attr('width', barWidth - barMargin)
                .style('fill', function (d, index) {
                    return "hsl(240, 100%, " + (d.avgVolume / maxVolume * 80) + "%)"
                });

            // bar text
            newBarGroups
                .append('text')
                .attr('transform', 'rotate(-45)')
                .attr('text-anchor', 'middle')
                .attr('x', function () { return 0; })
                .attr('y', 50)
                .attr('fill', 'white')
                .text(function (d, i) { return d.avgVolume; })
                .style('font-size', '1em')

        });
</code>```

in the xScale, I have tried changing the return data from

```<code>return d.monthName
</code>```

to

```<code>return d.monthName + ' ' + d.dayNo
</code>```

But then all my bars overlap and I get this error for each g element:
d3.js:1211 Error:  attribute transform: Expected number, "translate(undefined,25.183…".

Here is what I have currently with returning d.monthName:

Here is d.monthName + ' ' + d.dayNo:

答:
Nevermind sorry, I fixed it

I needed to change

```<code>            var newBarGroups = barGroups.enter()
            .append('g')
            .attr('transform', function (d, i) {
                return 'translate('
                    + (xScale(d.monthName))
                    + ','
                    + (yScale(d.avgVolume))
                    + ')';
            })
</code>```

to

```<code>                var newBarGroups = barGroups.enter()
                .append('g')
                .attr('transform', function (d, i) {
                    return 'translate('
                        + (xScale(d.monthName + ' ' + d.dayNo))
                        + ','
                        + (yScale(d.avgVolume))
                        + ')';
                })
</code>```

Title: JQuery SVG graph - overlapping bars

Body:
I'm trying to learn SVG graphs, I've nearly completed my graph however I currently have overlapping bars, I believe this is due to a combination of my x axis return data and my json data. My x axis lists the months from my JSON data, but my JSON data can have multiple entries from the same month. and if this is the case then my entries will overlap for that month. What I need to do is return the month + day seperately, however I haven't been able to figure out how just yet.

JSON data example where there's 2 entries for the same month:

1: {dayNo: 2, monthNo: 7, monthName: "July", year: 2018, recordDate: "2018-07-02T00:00:00",…}
avgVolume: 3585.53
dayNo: 2
monthName: "July"
monthNo: 7
recordDate: "2018-07-02T00:00:00"
volumeLastYear: 4109.47
volumeToday: 3575.34
year: 2018
2: {dayNo: 30, monthNo: 7, monthName: "July", year: 2018, recordDate: "2018-07-30T00:00:00",…}
avgVolume: 3291.55
dayNo: 30
monthName: "July"
monthNo: 7
recordDate: "2018-07-30T00:00:00"
volumeLastYear: 3996.31
volumeToday: 3414.44
year: 2018

And here is the svg code:

            $request.done(function (response) {
            // remove old svg
            $('svg').remove();

            // create svg element
            var $svg = d3.select('.card.mb-3.clickable-card.highlight')
                .append('svg')
                .attr('width', '100%')
                .attr('height', '400px')
                .attr('style', 'background-color: lavender')
                .classed('svg display-svg', true);

            // 2 determine size of svg element
            var w = $svg.node().getBoundingClientRect().width;
            var h = $svg.node().getBoundingClientRect().height;

            // 10 chart margins
            var chartMargin = new Object();
            chartMargin.left = 40;
            chartMargin.right = 25;
            chartMargin.top = 25;
            chartMargin.bottom = 40;

            // 10 cont
            h = h - chartMargin.bottom - chartMargin.top;

            // Max volume
            var maxVolume = d3.max(response, d => d.avgVolume);

            // bar Margins / width
            var barMargin = 10;
            var barWidth = (w - chartMargin.left - chartMargin.right) / response.length;

            // yScale
            var yScale = d3.scaleLinear()
                .domain([0, maxVolume])
                .range([h, chartMargin.top]);

            // xScale
            var xScale = d3.scaleBand()
                .domain(response.map(function (d) { return d.monthName; }))
                .range([0, w - chartMargin.left - chartMargin.right])
                .paddingInner(0.15);

            // chartGroup
            var chartGroup = $svg.append('g')
                .classed('chartGroup', true)
                .attr('transform', 'translate(' + chartMargin.left + ',' + chartMargin.top + ')');

            // 5
            var barGroups = chartGroup
                .selectAll('g')
                .data(response);

            // 6
            var newBarGroups = barGroups.enter()
                .append('g')
                .attr('transform', function (d, i) {
                    return 'translate('
                        + (xScale(d.monthName))
                        + ','
                        + (yScale(d.avgVolume))
                        + ')';
                })

            // yAxis label
            var yAxis = d3.axisLeft(yScale);
            chartGroup.append('g')
                .classed('axis y', true)
                .attr('transform', 'translate(' + -20 + ', ' + h / 2 + ')')
                .append('text')
                .attr('transform', 'rotate(-90)')
                .attr('dx', '-0.8em')
                .attr('dy', '0.25em')
                .attr("text-anchor", 'middle')
                .text("Reservoir Volume (ML)");

            // xAxis label
            var xAxis = d3.axisBottom(xScale);
            chartGroup.append('g')
                .attr('transform', 'translate(0,' + h + ')')
                .classed('axis x', true)
                .call(xAxis);

            newBarGroups
                .append('rect')
                .attr('x', 0)
                .attr('height', function (d, i) {
                    return h - yScale(d.avgVolume);
                })

                // animation
                .style('fill', 'transparent')
                .transition().duration(function (d, i) { return i * 500; })
                .delay(function (d, i) { return i + 200; })

                .attr('width', barWidth - barMargin)
                .style('fill', function (d, index) {
                    return "hsl(240, 100%, " + (d.avgVolume / maxVolume * 80) + "%)"
                });

            // bar text
            newBarGroups
                .append('text')
                .attr('transform', 'rotate(-45)')
                .attr('text-anchor', 'middle')
                .attr('x', function () { return 0; })
                .attr('y', 50)
                .attr('fill', 'white')
                .text(function (d, i) { return d.avgVolume; })
                .style('font-size', '1em')

        });

in the xScale, I have tried changing the return data from

return d.monthName

to

return d.monthName + ' ' + d.dayNo

But then all my bars overlap and I get this error for each g element:
d3.js:1211 Error:  attribute transform: Expected number, "translate(undefined,25.183…".

Here is what I have currently with returning d.monthName:

Here is d.monthName + ' ' + d.dayNo:

Body:
Nevermind sorry, I fixed it

I needed to change

            var newBarGroups = barGroups.enter()
            .append('g')
            .attr('transform', function (d, i) {
                return 'translate('
                    + (xScale(d.monthName))
                    + ','
                    + (yScale(d.avgVolume))
                    + ')';
            })

to

                var newBarGroups = barGroups.enter()
                .append('g')
                .attr('transform', function (d, i) {
                    return 'translate('
                        + (xScale(d.monthName + ' ' + d.dayNo))
                        + ','
                        + (yScale(d.avgVolume))
                        + ')';
                })


问:
Facing issues in migrating from ADAL JS to MSAL JS
Hope you all are safe & sound, I was migrating my angular app authentication from ADAL JS to MSAL JS.

In ADAL JS, I have my ADAL Config as follows and the authentication works as expected:

```<code>adalConfig: {
    tenant: 'GUID',
    clientId: 'GUID',
    redirectUri: window.location.origin
    ......
    ...... // other properties
 }
</code>```

In MSAL Config I tried to set the same properties in app.module.ts

```<code>MsalModule.forRoot({
      auth: {
          clientId: "GUID", // Same as the client ID of ADAL JS
          authority: https://login.microsoftonline.com/<tenant GUID>/, // Same as the tenant GUID of ADAL JS
          redirectUri: OAuthSettings.redirectUri, // This is your redirect URI
      },
      cache: {
        cacheLocation: 'localStorage',
       // storeAuthStateInCookie: true, // set to true for IE 11
    }
</code>```

However I keep on getting this error

"Please set the correlationId as a valid guid"

I tried looking at this documentation from Microsoft, but it mentions nothing about the authority.

Any help would be highly appreciated.

答:
correlationId would be seen in MSAL logs. As the doc shows, correlationId is a unique identifier, used to map the request with the response for debugging purposes.

You could try the code from this link:

```<code>MsalModule.forRoot({
    clientID: '00000000-0000-0000-0000-000000000000',
    authority: "https://login.microsoftonline.com/common/",
    validateAuthority: true,
    redirectUri: window.location.origin,
    cacheLocation: 'localStorage',
    postLogoutRedirectUri: window.location.origin,
    navigateToLoginRequestUrl: false,
    popUp: false,
    unprotectedResources: ["https://www.microsoft.com/en-us/"],
    protectedResourceMap: protectedResourceMap,
    logger: loggerCallback,
    correlationId: "1000",
    level: LogLevel.Info,
    piiLoggingEnabled: true
})
....
</code>```

Body:
Hope you all are safe & sound, I was migrating my angular app authentication from ADAL JS to MSAL JS.

In ADAL JS, I have my ADAL Config as follows and the authentication works as expected:

adalConfig: {
    tenant: 'GUID',
    clientId: 'GUID',
    redirectUri: window.location.origin
    ......
    ...... // other properties
 }

In MSAL Config I tried to set the same properties in app.module.ts

MsalModule.forRoot({
      auth: {
          clientId: "GUID", // Same as the client ID of ADAL JS
          authority: https://login.microsoftonline.com/<tenant GUID>/, // Same as the tenant GUID of ADAL JS
          redirectUri: OAuthSettings.redirectUri, // This is your redirect URI
      },
      cache: {
        cacheLocation: 'localStorage',
       // storeAuthStateInCookie: true, // set to true for IE 11
    }

However I keep on getting this error

"Please set the correlationId as a valid guid"

I tried looking at this documentation from Microsoft, but it mentions nothing about the authority.

Any help would be highly appreciated.

Body:
correlationId would be seen in MSAL logs. As the doc shows, correlationId is a unique identifier, used to map the request with the response for debugging purposes.

You could try the code from this link:

MsalModule.forRoot({
    clientID: '00000000-0000-0000-0000-000000000000',
    authority: "https://login.microsoftonline.com/common/",
    validateAuthority: true,
    redirectUri: window.location.origin,
    cacheLocation: 'localStorage',
    postLogoutRedirectUri: window.location.origin,
    navigateToLoginRequestUrl: false,
    popUp: false,
    unprotectedResources: ["https://www.microsoft.com/en-us/"],
    protectedResourceMap: protectedResourceMap,
    logger: loggerCallback,
    correlationId: "1000",
    level: LogLevel.Info,
    piiLoggingEnabled: true
})
....


问:
node.js await is only valid in async function
I have code like this

```<code>GetRequests(requestStartId,requestEndId);

async function GetRequests(startId,endId){
    let fileAddress = __dirname + '\\attachments';
    for (let i = startId; i <= endId; i++) {
        if (fs.existsSync(fileAddress + '\\' + i)) {
            await upload(i,fileAddress);
     }
    }
}

/**
upload files
**/
    async  function upload(i,fileAddress){
        fs.readdir(fileAddress + '\\' + i, (err, files) => {
            const newID=await  getNewRequestID(i);
            files.forEach(file => {
                ...
                ...
                 ...
                 await  axios({
                    method: 'post',
                    url: `my_url`,
                    data: form,
                    headers: {
                       [my_header_items]
                    }
                }).then(function (response) {
                    // handle success
                     console.log(response);
                }).catch(function (error) {
                    console.log(error);
                });
            });
        });

    }

   async function getNewRequestID(id) {
        let inputData = {
           [my_input_data]
        };
        form.append('input_data', JSON.stringify(inputData));
       return await axios({
            method: 'get',
            url: `my_url,
            data: form,
            headers: {
                [my_header_item]
            }
        }).then(function (response) {
              return response.data.id;
        }).catch(function (error) {
            console.log(error);
        });
    }
</code>```

when I run this script show me this error

const newID=await  getNewRequestID(i);
                                ^^^^^
 SyntaxError: await is only valid in async function

答:
Put async before the callback function in the following line...

```<code>fs.readdir(fileAddress + '\\' + i, async (err, files) => { ...

</code>```

Body:
I have code like this

GetRequests(requestStartId,requestEndId);

async function GetRequests(startId,endId){
    let fileAddress = __dirname + '\\attachments';
    for (let i = startId; i <= endId; i++) {
        if (fs.existsSync(fileAddress + '\\' + i)) {
            await upload(i,fileAddress);
     }
    }
}

/**
upload files
**/
    async  function upload(i,fileAddress){
        fs.readdir(fileAddress + '\\' + i, (err, files) => {
            const newID=await  getNewRequestID(i);
            files.forEach(file => {
                ...
                ...
                 ...
                 await  axios({
                    method: 'post',
                    url: `my_url`,
                    data: form,
                    headers: {
                       [my_header_items]
                    }
                }).then(function (response) {
                    // handle success
                     console.log(response);
                }).catch(function (error) {
                    console.log(error);
                });
            });
        });

    }

   async function getNewRequestID(id) {
        let inputData = {
           [my_input_data]
        };
        form.append('input_data', JSON.stringify(inputData));
       return await axios({
            method: 'get',
            url: `my_url,
            data: form,
            headers: {
                [my_header_item]
            }
        }).then(function (response) {
              return response.data.id;
        }).catch(function (error) {
            console.log(error);
        });
    }

when I run this script show me this error

const newID=await  getNewRequestID(i);
                                ^^^^^
 SyntaxError: await is only valid in async function

Body:
Put async before the callback function in the following line...

fs.readdir(fileAddress + '\\' + i, async (err, files) => { ...


问:
How does vuetify color code scheme works?
I am working on Vuetify.js but I am unable to understand how color code works?

https://vuetifyjs.com/en/styles/colors/#colors

This is the page I am referring too. This page has some predefined sets of colors, like red lighten-3 #EF9A9A

But, if I set my primary color as some random color code like mediumaquamarine    #66CDAA and then if I use primary lighten-3, then on what basis does I get my color?

答:
Vuetify calculate color and variants (lighten and darken) based on colors defined on theme at Vuetify inizialation:

new Vuetify({
    theme: {
       themes: {
          light: {
            primary: "#d63fd9", // pink
            secondary: "#b0bec5",
            anchor: "#8c9eff"
         }
       }
    }
})
```

See this codepen with primary color setted pink: https://codepen.io/hans-felix/pen/rNxBemM?editors=1010

Body:
Vuetify calculate color and variants (lighten and darken) based on colors defined on theme at Vuetify inizialation:

new Vuetify({
    theme: {
       themes: {
          light: {
            primary: "#d63fd9", // pink
            secondary: "#b0bec5",
            anchor: "#8c9eff"
         }
       }
    }
})

See this codepen with primary color setted pink: https://codepen.io/hans-felix/pen/rNxBemM?editors=1010


问:
SVG icons not showing up in Qt4 release build in windows
I have a Qt4 application with SVG icons, compiled with mingw (in windows), linked to Qt shared libraries.

When application is run, SVG icons show up in debug and release builds in linux, however in windows SVG icons show up only in debug build but not in release build.

All SVG icons are listed in project.qrc, and project.pro has RESOURCES = project.qrc. Application uses QtSvg4.dll (version 4.7.0).

Qt 4.7.0, Qt Creator 2.0.1, mingw/g++ 4.4.0.

Solution update: In application directory, create /imageformats/ directory and put qsvg4.dll there instead of application directory itself, or create a qt.conf file with appropriate path. More information in deploying plugins.

答:
for Qt 5.14
add a line to the .pro file</p>

```<code>QT       += svg
</code>```

Body:
for Qt 5.14
add a line to the .pro file

QT       += svg


问:
Continue in while inside foreach
In the following C# code snippet

I have a 'while' loop inside a 'foreach' loop and I wish to jump to the next item in 'foreach' when a certain condition occurs.

```<code>foreach (string objectName in this.ObjectNames)
{
    // Line to jump to when this.MoveToNextObject is true.
    this.ExecuteSomeCode();
    while (this.boolValue)
    {
        // 'continue' would jump to here.
        this.ExecuteSomeMoreCode();
        if (this.MoveToNextObject())
        {
            // What should go here to jump to next object.
        }
        this.ExecuteEvenMoreCode();
        this.boolValue = this.ResumeWhileLoop();
    }
    this.ExecuteSomeOtherCode();
}
</code>```

'continue' would jump to the beginning of the 'while' loop not the 'foreach' loop.
Is there's a keyword to use here, or should I just use goto which I don't really like.

答: You can use "break;" to exit the innermost while or foreach.</p>

OwnerDisplayName: Amr

ContentLicense: CC BY-SA 2.5

Title: Continue in while inside foreach

Body:
In the following C# code snippet

I have a 'while' loop inside a 'foreach' loop and I wish to jump to the next item in 'foreach' when a certain condition occurs.

foreach (string objectName in this.ObjectNames)
{
    // Line to jump to when this.MoveToNextObject is true.
    this.ExecuteSomeCode();
    while (this.boolValue)
    {
        // 'continue' would jump to here.
        this.ExecuteSomeMoreCode();
        if (this.MoveToNextObject())
        {
            // What should go here to jump to next object.
        }
        this.ExecuteEvenMoreCode();
        this.boolValue = this.ResumeWhileLoop();
    }
    this.ExecuteSomeOtherCode();
}

'continue' would jump to the beginning of the 'while' loop not the 'foreach' loop.
Is there's a keyword to use here, or should I just use goto which I don't really like.

LastEditorDisplayName: configurator

OwnerDisplayName: Andrew Robinson


问:
Upgrading Pyramid/SQLAlchemy web apps
I've got a standard run of the mill Pylons Pyramid application, that uses SQLAlchemy for its database persistence.

I have set up an SQLAlchemy-migrate repo and have it functioning, but I really want to have the ability to use paster to upgrade and downgrade the database, or at least some way of having the user (after installing the egg) upgrade/downgrading the database to the version required.

I've got it built-into my app now, so upon app startup it does the version upgrade, but I would rather go with something where the user explicitly has to upgrade the database so that they know exactly what is going on, and know to make backups beforehand.

How would I go about that? How do I add commands to paste?

The way users would set up the application is:

```<code>paste make-config appname production.ini
paste setup-app production.ini#appname
</code>```

To set it up the first time, to do the database upgrade or upgrade in general I would want:

```<code>paste upgrade-app production.ini#appname
</code>```

Or something along those lines.

答: You can create your own paster command, e.g. upgrade-app, and then call it from anywhere with paster --plugin=appname upgrade-app /path/to/production.ini appname. You can refer to how pyramid implements the PShellCommand.

Title: Upgrading Pyramid/SQLAlchemy web apps

Body:
I've got a standard run of the mill Pylons Pyramid application, that uses SQLAlchemy for its database persistence.

I have set up an SQLAlchemy-migrate repo and have it functioning, but I really want to have the ability to use paster to upgrade and downgrade the database, or at least some way of having the user (after installing the egg) upgrade/downgrading the database to the version required.

I've got it built-into my app now, so upon app startup it does the version upgrade, but I would rather go with something where the user explicitly has to upgrade the database so that they know exactly what is going on, and know to make backups beforehand.

How would I go about that? How do I add commands to paste?

The way users would set up the application is:

paste make-config appname production.ini
paste setup-app production.ini#appname

To set it up the first time, to do the database upgrade or upgrade in general I would want:

paste upgrade-app production.ini#appname

Or something along those lines.


问:
Change login timeout when logging in into Ubuntu
On my Login Screen I have to input a 32 character insane password, and the timer expires before I'm done entering password.

I've tried searching for how to change the timer that controls when an login attempt is reset. I'm having a hard time finding the solution, maybe because I'm not searching correctly. I've found this, which describes what I'm searching for, but can't find it for Ubuntu. I'm running Ubuntu 14.04.3 LTS.

It's only the timeout for the login screen I'm interested in changing, not the session timeout after a successful login. I'm logging in via console through VMware vSphere. SSH is closed down due to security concerns. Copy/paste option is removed due to security concerns.

答:
There is no such 60s delay in the graphical login in Ubuntu 20.04, but you can change the delay after a failed login attempt:

Edit the file

```<code>sudo vim /etc/pam.d/login

# Enforce a minimal delay in case of failure (in microseconds).
auth       optional   pam_faildelay.so  delay=1000000
</code>```

(default was 3000000 = 3 seconds)

There seems to be a delay though, that prevents you from entereing the password again after a failed attempt. Related question:

Change the delay that occurs after entering an incorrect password in the graphical Login screen?

Body:
There is no such 60s delay in the graphical login in Ubuntu 20.04, but you can change the delay after a failed login attempt:

Edit the file

sudo vim /etc/pam.d/login

# Enforce a minimal delay in case of failure (in microseconds).
auth       optional   pam_faildelay.so  delay=1000000

(default was 3000000 = 3 seconds)

There seems to be a delay though, that prevents you from entereing the password again after a failed attempt. Related question:

Change the delay that occurs after entering an incorrect password in the graphical Login screen?


问:
How do i print a for i in range loop to a PySimpleGUI window?
I am trying to make a programm that tells you a input amount of the words rhymig with the word you choose. i am doing it in PySimpleGUI and i dont know how to print the loop in to a PySimpleGUI window. Could someone help. Thanks in advance -Josh</p>

```<code>import PySimpleGUI as sg
import requests

layout = [[sg.Text('What would you like to hear rhymes about: '), sg.InputText()],
      [sg.Submit(), sg.Cancel()]]

window = sg.Window('Rhyme.', layout)
event, values = window.read()

rhyme = values[0]

words = requests.get('https://api.datamuse.com/words?rel_rhy=' + rhyme)

words_json = words.json()
window.close()

layout = [[sg.Text(f'How many rhymes about {rhyme} would you like to hear: '), sg.InputText()],
          [sg.Submit(), sg.Cancel()]]

window = sg.Window('Rhyme.', layout)
event, values = window.read()

num = values[0]

window.close()

layout = [[sg.Text(#I dont Know how to print the list here)
</code>```

答:
this code will work for you.</p>

```<code>import PySimpleGUI as sg
import requests

layout = [[sg.Text('What would you like to hear rhymes about: '), sg.InputText()],
      [sg.Submit(), sg.Cancel()]]

window = sg.Window('Rhyme.', layout)
event, values = window.read()

rhyme = values[0]

words = requests.get('https://api.datamuse.com/words?rel_rhy=' + rhyme)

words_json = words.json()
window.close()

layout = [[sg.Text(f'How many rhymes about {rhyme} would you like to hear: '), sg.InputText()],
          [sg.Submit(), sg.Cancel()]]

window = sg.Window('Rhyme.', layout)
event, values = window.read()

num = values[0]

window.close()

layout = []
for x in words_json:
    layout = layout + [sg.Text(x['word'])]

layout = [layout]

window = sg.Window('word',layout)

event, values = window.read()

window.close()
</code>```

Body:
I am trying to make a programm that tells you a input amount of the words rhymig with the word you choose. i am doing it in PySimpleGUI and i dont know how to print the loop in to a PySimpleGUI window. Could someone help. Thanks in advance -Josh

import PySimpleGUI as sg
import requests

layout = [[sg.Text('What would you like to hear rhymes about: '), sg.InputText()],
      [sg.Submit(), sg.Cancel()]]

window = sg.Window('Rhyme.', layout)
event, values = window.read()

rhyme = values[0]

words = requests.get('https://api.datamuse.com/words?rel_rhy=' + rhyme)

words_json = words.json()
window.close()

layout = [[sg.Text(f'How many rhymes about {rhyme} would you like to hear: '), sg.InputText()],
          [sg.Submit(), sg.Cancel()]]

window = sg.Window('Rhyme.', layout)
event, values = window.read()

num = values[0]

window.close()

layout = [[sg.Text(#I dont Know how to print the list here)

Body:
this code will work for you.

import PySimpleGUI as sg
import requests

layout = [[sg.Text('What would you like to hear rhymes about: '), sg.InputText()],
      [sg.Submit(), sg.Cancel()]]

window = sg.Window('Rhyme.', layout)
event, values = window.read()

rhyme = values[0]

words = requests.get('https://api.datamuse.com/words?rel_rhy=' + rhyme)

words_json = words.json()
window.close()

layout = [[sg.Text(f'How many rhymes about {rhyme} would you like to hear: '), sg.InputText()],
          [sg.Submit(), sg.Cancel()]]

window = sg.Window('Rhyme.', layout)
event, values = window.read()

num = values[0]

window.close()

layout = []
for x in words_json:
    layout = layout + [sg.Text(x['word'])]

layout = [layout]

window = sg.Window('word',layout)

event, values = window.read()

window.close()


问:
Avoid multiple calls to database with C# & EF Core
I have a requirement where I need to display a value based on Id. For that, I am making multiple calls to the database, to different tables. Is it possible to reduce the number of calls?

I have switch conditions based on which call to DB occurs. Below is sample

```<code>foreach (var items in table1)
{
    foreach (var item in items.List)
    {
         switch (item.condition)
         {
             case condition1:
             case condition2:
                 item.nvalue= string.Join(",", _context.table1.Where(x => ids.Contains(x.Id)).Select(x => x.Title));
                 break;

             case condition3:
                 item.nvalue= string.Join(",", _context.tabl2.Where(x => secondIds.Contains(x.Id)).Select(x => x.newvalu));
                 break;

             case condition4:
                 item.nvalue= string.Join(",", _context.tabl3.Where(x => someIds.Contains(x.Id)).Select(x => x.oldvalue));
                 break;

             case condition5:
                 item.nvalue= string.Join(",", _context.tabl4.Where(x=>textIds.Contains(x.Id)).Select(x => x.note));
                 break;

             default:
                 item.nvalue= "";
                 break;
         }
     }
 }
</code>```

Thanks in advance

答:
To reduce number of calls you can at least group your items by condition:</p>

```<code>var groups = table1
    .SelectMany(t => t.List)
    .GroupBy(i => switch (i.condition)
     {
         case condition1:
         case condition2:
             return 1;
         case condition3:
             return 2;
         ......
         default: return 0;
     });
foreach(var group in groups)
{
     string nvalue;
     switch (g.Key)
     {
         case 1:
             nvalue = string.Join(",", _context.table1.Where(x => ids.Contains(x.Id)).Select(x => x.Title));
             break;

         case 2:
             nvalue = string.Join(",", _context.tabl2.Where(x => secondIds.Contains(x.Id)).Select(x => x.newvalu));
             break;
         .....
         default:
             nvalue= string.Empty;
             break;
     }
     foreach(vat item in group)
     {
         item.nvalue = nvalue;
     }
}
</code>```

Body:
I have a requirement where I need to display a value based on Id. For that, I am making multiple calls to the database, to different tables. Is it possible to reduce the number of calls?

I have switch conditions based on which call to DB occurs. Below is sample

foreach (var items in table1)
{
    foreach (var item in items.List)
    {
         switch (item.condition)
         {
             case condition1:
             case condition2:
                 item.nvalue= string.Join(",", _context.table1.Where(x => ids.Contains(x.Id)).Select(x => x.Title));
                 break;

             case condition3:
                 item.nvalue= string.Join(",", _context.tabl2.Where(x => secondIds.Contains(x.Id)).Select(x => x.newvalu));
                 break;

             case condition4:
                 item.nvalue= string.Join(",", _context.tabl3.Where(x => someIds.Contains(x.Id)).Select(x => x.oldvalue));
                 break;

             case condition5:
                 item.nvalue= string.Join(",", _context.tabl4.Where(x=>textIds.Contains(x.Id)).Select(x => x.note));
                 break;

             default:
                 item.nvalue= "";
                 break;
         }
     }
 }

Thanks in advance

Body:
To reduce number of calls you can at least group your items by condition:

var groups = table1
    .SelectMany(t => t.List)
    .GroupBy(i => switch (i.condition)
     {
         case condition1:
         case condition2:
             return 1;
         case condition3:
             return 2;
         ......
         default: return 0;
     });
foreach(var group in groups)
{
     string nvalue;
     switch (g.Key)
     {
         case 1:
             nvalue = string.Join(",", _context.table1.Where(x => ids.Contains(x.Id)).Select(x => x.Title));
             break;

         case 2:
             nvalue = string.Join(",", _context.tabl2.Where(x => secondIds.Contains(x.Id)).Select(x => x.newvalu));
             break;
         .....
         default:
             nvalue= string.Empty;
             break;
     }
     foreach(vat item in group)
     {
         item.nvalue = nvalue;
     }
}


问:
Updating source in PowerQuery: Azure Data Pull via ODBC
I added a source in PowerQuery via ODBC to Azure, pulling data in free form query. On top of that I designed few new columns & measures in PowerBI and created report.

All good until I want to add some more columns in the free form query. My issue is:
 1. If I proceed to edit the query via editing from inside Advanced Editor, it's going to take longer time & error prone as well; testing & retesting until the query is properly written.
 2. Delete the existing source, add new Spark SQL query and run it without hassle. But then, create all the existing measures & columns again in PowerBI.

I don't see any other way to edit the same existing source in a hassle free way and retain my measures & columns of PowerBI intact.

Any pointers will be helpful.Thanks!

答: I got the idea; guess I haven't had considered the editing of Source of the query; screenshot attached.


问:
How to connect on edge to the left-side-mid-height of a vertex
```<code>var vertex = graph.createVertex(null, null, value, x, y, width, height, style);
cell = graph.addCell(vertex, null);

edge = graph.createEdge(null, null, '', parent, cell, graph.createCurrentEdgeStyle());
edge = graph.addEdge(edge, null, parent, cell);
</code>```

How can I tell this edge to be connected to the left-side-mid-height of target cell?

parent and cell are vertex's

答:
Ok , finally found my own answer , just had to add a style to the edge creation

exitX=1;exitY=0.5;exitPerimeter=1;entryX=0;entryY=0.5;entryPerimeter=1;

this style will force the edge to exit from source's right-mid and enter target's left-mid section.

Body:
var vertex = graph.createVertex(null, null, value, x, y, width, height, style);
cell = graph.addCell(vertex, null);

edge = graph.createEdge(null, null, '', parent, cell, graph.createCurrentEdgeStyle());
edge = graph.addEdge(edge, null, parent, cell);

How can I tell this edge to be connected to the left-side-mid-height of target cell?

parent and cell are vertex's


问:
How to return headers of columns that match a criteria for every row in a pandas dataframe?
I have a pandas dataframe df of the form :

```<code>     Col1      Col2      Col3      Col4

0    True      False     True      False
1    False     False     False     False
2    False     True      False     False
3    True      True      True      True
</code>```

Here True and False are boolean values.

I am trying to generate a new pandas dataframe new_df which should look like:

```<code>     Matched_Cols

0    [Col1, Col3]
1    []
2    [Col2]
3    [Col1, Col2, Col3, Col4]
</code>```

What is the most efficient way to achieve this?

答:
Approach #1

Here's with array-data processing -

```<code>def iter_accum(df):
    c = df.columns.values.astype(str)
    return pd.DataFrame({'Matched_Cols':[c[i] for i in df.values]})
</code>```

Sample output -

```<code>In [41]: df
Out[41]:
    Col1   Col2   Col3   Col4
0   True  False   True  False
1  False  False  False  False
2  False   True  False  False
3   True   True   True   True

In [42]: iter_accum(df)
Out[42]:
               Matched_Cols
0              [Col1, Col3]
1                        []
2                    [Col2]
3  [Col1, Col2, Col3, Col4]
</code>```

Approach #2

Another with slicing on array-data and some boolean-indexing -

```<code>def slice_accum(df):
    c = df.columns.values.astype(str)
    a = df.values
    vals = np.broadcast_to(c,a.shape)[a]
    I = np.r_[0,a.sum(1).cumsum()]
    ac = []
    for (i,j) in zip(I[:-1],I[1:]):
        ac.append(vals[i:j])
    return pd.DataFrame({'Matched_Cols':ac})
</code>```

Benchmarking

Other proposed solution(s) -

```<code># @jezrael's soln-1
def jez1(df):
    return df.apply(lambda x: x.index[x].tolist(), axis=1)

# @jezrael's soln-2
def jez2(df):
    return df.dot(df.columns + ',').str.rstrip(',').str.split(',')

# @Shubham Sharma's soln
def Shubham1(df):
    return df.agg(lambda s: s.index[s].values, axis=1)

# @sammywemmy's soln
def sammywemmy1(df):
    return pd.DataFrame({'Matched_Cols':[np.compress(x,y) for x,y in zip(df.to_numpy(),np.tile(df.columns,(len(df),1)))]})
</code>```

Using benchit package (few benchmarking tools packaged together; disclaimer: I am its author) to benchmark proposed solutions.

```<code>import benchit
funcs = [iter_accum,slice_accum,jez1,jez2,Shubham1,sammywemmy1]
in_ = {n:pd.DataFrame(np.random.rand(n,n)>0.5, columns=['Col'+str(i) for i in range(1,n+1)]) for n in [4,20,100,200,500,1000]}
t = benchit.timings(funcs, in_, input_name='Len')
t.rank()
t.plot(logx=True)
</code>```

Body:
I have a pandas dataframe df of the form :

     Col1      Col2      Col3      Col4

0    True      False     True      False
1    False     False     False     False
2    False     True      False     False
3    True      True      True      True

Here True and False are boolean values.

I am trying to generate a new pandas dataframe new_df which should look like:

     Matched_Cols

0    [Col1, Col3]
1    []
2    [Col2]
3    [Col1, Col2, Col3, Col4]

What is the most efficient way to achieve this?

Body:
Approach #1

Here's with array-data processing -

def iter_accum(df):
    c = df.columns.values.astype(str)
    return pd.DataFrame({'Matched_Cols':[c[i] for i in df.values]})

Sample output -

In [41]: df
Out[41]:
    Col1   Col2   Col3   Col4
0   True  False   True  False
1  False  False  False  False
2  False   True  False  False
3   True   True   True   True

In [42]: iter_accum(df)
Out[42]:
               Matched_Cols
0              [Col1, Col3]
1                        []
2                    [Col2]
3  [Col1, Col2, Col3, Col4]

Approach #2

Another with slicing on array-data and some boolean-indexing -

def slice_accum(df):
    c = df.columns.values.astype(str)
    a = df.values
    vals = np.broadcast_to(c,a.shape)[a]
    I = np.r_[0,a.sum(1).cumsum()]
    ac = []
    for (i,j) in zip(I[:-1],I[1:]):
        ac.append(vals[i:j])
    return pd.DataFrame({'Matched_Cols':ac})

Benchmarking

Other proposed solution(s) -

# @jezrael's soln-1
def jez1(df):
    return df.apply(lambda x: x.index[x].tolist(), axis=1)

# @jezrael's soln-2
def jez2(df):
    return df.dot(df.columns + ',').str.rstrip(',').str.split(',')

# @Shubham Sharma's soln
def Shubham1(df):
    return df.agg(lambda s: s.index[s].values, axis=1)

# @sammywemmy's soln
def sammywemmy1(df):
    return pd.DataFrame({'Matched_Cols':[np.compress(x,y) for x,y in zip(df.to_numpy(),np.tile(df.columns,(len(df),1)))]})

Using benchit package (few benchmarking tools packaged together; disclaimer: I am its author) to benchmark proposed solutions.

import benchit
funcs = [iter_accum,slice_accum,jez1,jez2,Shubham1,sammywemmy1]
in_ = {n:pd.DataFrame(np.random.rand(n,n)>0.5, columns=['Col'+str(i) for i in range(1,n+1)]) for n in [4,20,100,200,500,1000]}
t = benchit.timings(funcs, in_, input_name='Len')
t.rank()
t.plot(logx=True)