问:
JQUERY AJAX ---- Pausing for usability reasons but only when nessesary?
I have a LoadingStatus Function that has two options SHOW or HIDE.

The Show triggers to display when the JQUERY POST is made, the HIDE happens after the RESPONSE comes back.

The issue I'm having is that sometimes this happens so fast that it makes for a bad experience. What I thought about doing was putting in a JavaScript PAUSE, but if the POST takes a while to respond it will take even longer because of the PAUSE.

How can I have my SHOW HIDE function work together, to make sure at minimum the SHOW was displayed to the user for at least 1/2 second?

```<code>function saveBanner (action) {

    if (action == 'show') {
        // Display the AJAX Status MSG
        $("#ajaxstatus").css("display","block");
        $("#msg").text('Saving...');
    }
    else if (action == 'hide') {
        $("#ajaxstatus").css("display","none");
        $("#msg").text('');
    }
};
</code>```

Thanks

答:
As of jQuery 1.5, you are able to extend the $.ajax functionality by using prefilters.  I wanted a similar experience where a message was shown a minimum amount of time when an ajax call is made.

By using prefilters, I can now add a property to the ajax call named "delayedSuccess" and pass it a time in milliseconds.  The time that is passed in is the minimum amount of time  the ajax call will wait to call the success function.  For instance, if you passed in 3000 (3 seconds) and the actual ajax call took 1.3 seconds, the success function would be delayed 1.7 seconds.  If the original ajax call lasted more than 3 seconds, the success function would be called immediately.

Here is how I achieved that with an ajax prefilter.

```<code>$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
if (originalOptions.delaySuccess && $.isFunction(originalOptions.success)) {
    var start, stop;
    options.beforeSend = function () {
        start = new Date().getTime();
        if ($.isFunction(originalOptions.beforeSend))
            originalOptions.beforeSend();
    };
    options.success = function (response) {
        var that = this, args = arguments;
        stop = new Date().getTime();

        function applySuccess() {
            originalOptions.success.apply(that, args);
        }

        var difference = originalOptions.delaySuccess - (stop - start);
        if (difference > 0)
            setTimeout(applySuccess, difference);
        else
            applySuccess();
    };
}
});
</code>```

I first check to see if the delaySuccess and success options are set.  If they are, I then override the beforeSend callback in order set the start variable to the current time.  I then override the success function to grab the time after the ajax call has finish and subtract the difference from the original delaySuccess time.  Finally, a timeout is set to the computed time which then calls the original success function.

I found this to be a nice way to achieve this effect and it can easily be used multiple times throughout a site.

Body:
I have a LoadingStatus Function that has two options SHOW or HIDE.

The Show triggers to display when the JQUERY POST is made, the HIDE happens after the RESPONSE comes back.

The issue I'm having is that sometimes this happens so fast that it makes for a bad experience. What I thought about doing was putting in a JavaScript PAUSE, but if the POST takes a while to respond it will take even longer because of the PAUSE.

How can I have my SHOW HIDE function work together, to make sure at minimum the SHOW was displayed to the user for at least 1/2 second?

function saveBanner (action) {

    if (action == 'show') {
        // Display the AJAX Status MSG
        $("#ajaxstatus").css("display","block");
        $("#msg").text('Saving...');
    }
    else if (action == 'hide') {
        $("#ajaxstatus").css("display","none");
        $("#msg").text('');
    }
};

Thanks

Body:
As of jQuery 1.5, you are able to extend the $.ajax functionality by using prefilters.  I wanted a similar experience where a message was shown a minimum amount of time when an ajax call is made.

By using prefilters, I can now add a property to the ajax call named "delayedSuccess" and pass it a time in milliseconds.  The time that is passed in is the minimum amount of time  the ajax call will wait to call the success function.  For instance, if you passed in 3000 (3 seconds) and the actual ajax call took 1.3 seconds, the success function would be delayed 1.7 seconds.  If the original ajax call lasted more than 3 seconds, the success function would be called immediately.

Here is how I achieved that with an ajax prefilter.

$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
if (originalOptions.delaySuccess && $.isFunction(originalOptions.success)) {
    var start, stop;
    options.beforeSend = function () {
        start = new Date().getTime();
        if ($.isFunction(originalOptions.beforeSend))
            originalOptions.beforeSend();
    };
    options.success = function (response) {
        var that = this, args = arguments;
        stop = new Date().getTime();

        function applySuccess() {
            originalOptions.success.apply(that, args);
        }

        var difference = originalOptions.delaySuccess - (stop - start);
        if (difference > 0)
            setTimeout(applySuccess, difference);
        else
            applySuccess();
    };
}
});

I first check to see if the delaySuccess and success options are set.  If they are, I then override the beforeSend callback in order set the start variable to the current time.  I then override the success function to grab the time after the ajax call has finish and subtract the difference from the original delaySuccess time.  Finally, a timeout is set to the computed time which then calls the original success function.

I found this to be a nice way to achieve this effect and it can easily be used multiple times throughout a site.


来源: stackexchange

问:
My css code in Word Press is working for every other page in the website when i only want it to work for 1 page
I have currently made a code in CSS, which I wanted for a particular page but unfortunately, it is working for every other page as well and it makes the other pages look quite broken since the formatting of them goes very odd.

The solutions I have tried so far are:

Using the unique code of the page and making it something like this - * .post-id-17 .stop {code here}
But I got no results from using this solution.

Here is the HTML code:

```<code><!DOCTYPE html>
<html>
<head>
    <title>CountDown</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <link href="https://fonts.googleapis.com/css?family=Poppins&display=swap" rel="stylesheet">
</head>
<body>
    <header>
        <h1>CountDown</h1>
    </header>
    <div class="content">
        <div class="counter"></div>
        <input type="number" id="seconds" placeholder="Seconds">
        <div class="buttons">
            <button class="btn start" id="start" value="1" onclick="check(this)">Start</button>
            <button class="btn start" id="continue" value="1" onclick="check(this)">Continue</button>
            <button class="btn stop" id="stop" value="0" onclick="check(this)">Stop</button>
            <button class="btn start" id="ok" onclick="toSubmit()">Submit</button>
        </div>
    </div>
    <script type="text/javascript" src="main.js"></script>

</body>
</html>
</code>```

Here is the CSS code:

```<code>* .post-id-706 .stop {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}

html, body{
    height: 100%;
}
body{
    width: 100%;
    height: 100%;
    background: linear-gradient(to left top, #0045D6, #00A9f6);
}

header{
    width: 100%;
    height: 13vh;
    background-color: #fff;
    color: #0045F6;
    display: flex;
    justify-content: center;
    align-items: center;
}

.content{
    width: 100%;
    height: 60vh;
    font-size: 3rem;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
}

.content #seconds{
    width: 250px;
    font-size: 2rem;
    padding: 1rem;
    outline: none;
    background: none;
    border: none;
    border-bottom: 3px solid #fff;
    color: #000000;
}

#seconds::placeholder{
    color: #ddd;
    font-size: 1.7rem;
}

.btn{
    background-color: #fff;
    border-radius: 4px;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 0.8rem 1.7rem;
    font-size: 1.2rem;
    font-weight: 700;
}

.start{
    color: #1f0;
}

.stop{
    color: #E00;
}

#start, #stop, #continue{
    display: none;
}

.counter{
    color: #000000;
}
</code>```

Here is the javascript code:

```<code>const container = document.querySelector('.counter');
const buttonsDiv = document.querySelector('.buttons');
const secInput = document.getElementById('seconds');

var seconds;
var remseconds;
var minuts;
var toCount = false;

function toSubmit(){
    display('start');
    remove('seconds');
    remove('ok');
    seconds = Number(secInput.value);
    counting();
}

function display(e){
    document.getElementById(e).style.display = 'block';
}

function remove(e){
    document.getElementById(e).style.display = 'none';
}

function check(stat){
    if(stat.id == "start"){
        display("stop");
        remove("start");
        toCount = true;
    }
    else if(stat.id == "stop"){
        display("continue");
        remove("stop");
        toCount = false
    }
    else{
        display("stop");
        remove("continue");
        toCount =true;
    }
}

function count(){
    if(seconds > 0){
        if(toCount == true){
            seconds--;
            remseconds = seconds % 60;
            minuts = Math.floor(seconds / 60);

            if(minuts < 10){
                minuts = "0" + minuts;
            }

            if(remseconds < 10){
                remseconds = "0" + remseconds;
            }

            container.innerHTML = minuts + " : " + remseconds;
        }
    }
    else{
        container.innerHTML = "DONE!";
        buttonsDiv.style.opacity = "0";
    }
}

function counting(){
    remseconds = seconds % 60;
    minuts = Math.floor(seconds / 60);

    if(remseconds < 10){
        remseconds = "0" + remseconds;
    }

    container.innerHTML = minuts + " : " + remseconds;
    setInterval(count, 1000);
}
</code>```

If you have any ideas in order to solve this issue please let me know.

答:
You can also add a single CSS file with those contents to a single page, specifying a condition in PHP like so in the :

```<code><?php
    if (is_page(id-of-the-page)) {
?>
    <link rel="stylesheet" href="/path/to/stylesheet.css" />
<?php
    }
?>
</code>```

Just make sure to set the correct ID of the page.

ContentLicense: CC BY-SA 4.0

Body:
I have currently made a code in CSS, which I wanted for a particular page but unfortunately, it is working for every other page as well and it makes the other pages look quite broken since the formatting of them goes very odd.

The solutions I have tried so far are:

Using the unique code of the page and making it something like this - * .post-id-17 .stop {code here}
But I got no results from using this solution.

Here is the HTML code:

<!DOCTYPE html>

    <title>CountDown</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <link href="https://fonts.googleapis.com/css?family=Poppins&display=swap" rel="stylesheet">

CountDown

        <input type="number" id="seconds" placeholder="Seconds">

            <button class="btn start" id="start" value="1" onclick="check(this)">Start</button>
            <button class="btn start" id="continue" value="1" onclick="check(this)">Continue</button>
            <button class="btn stop" id="stop" value="0" onclick="check(this)">Stop</button>
            <button class="btn start" id="ok" onclick="toSubmit()">Submit</button>

Here is the CSS code:

* .post-id-706 .stop {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}

html, body{
    height: 100%;
}
body{
    width: 100%;
    height: 100%;
    background: linear-gradient(to left top, #0045D6, #00A9f6);
}

header{
    width: 100%;
    height: 13vh;
    background-color: #fff;
    color: #0045F6;
    display: flex;
    justify-content: center;
    align-items: center;
}

.content{
    width: 100%;
    height: 60vh;
    font-size: 3rem;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
}

.content #seconds{
    width: 250px;
    font-size: 2rem;
    padding: 1rem;
    outline: none;
    background: none;
    border: none;
    border-bottom: 3px solid #fff;
    color: #000000;
}

#seconds::placeholder{
    color: #ddd;
    font-size: 1.7rem;
}

.btn{
    background-color: #fff;
    border-radius: 4px;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 0.8rem 1.7rem;
    font-size: 1.2rem;
    font-weight: 700;
}

.start{
    color: #1f0;
}

.stop{
    color: #E00;
}

#start, #stop, #continue{
    display: none;
}

.counter{
    color: #000000;
}

Here is the javascript code:

const container = document.querySelector('.counter');
const buttonsDiv = document.querySelector('.buttons');
const secInput = document.getElementById('seconds');

var seconds;
var remseconds;
var minuts;
var toCount = false;

function toSubmit(){
    display('start');
    remove('seconds');
    remove('ok');
    seconds = Number(secInput.value);
    counting();
}

function display(e){
    document.getElementById(e).style.display = 'block';
}

function remove(e){
    document.getElementById(e).style.display = 'none';
}

function check(stat){
    if(stat.id == "start"){
        display("stop");
        remove("start");
        toCount = true;
    }
    else if(stat.id == "stop"){
        display("continue");
        remove("stop");
        toCount = false
    }
    else{
        display("stop");
        remove("continue");
        toCount =true;
    }
}

function count(){
    if(seconds > 0){
        if(toCount == true){
            seconds--;
            remseconds = seconds % 60;
            minuts = Math.floor(seconds / 60);

            if(minuts < 10){
                minuts = "0" + minuts;
            }

            if(remseconds < 10){
                remseconds = "0" + remseconds;
            }

            container.innerHTML = minuts + " : " + remseconds;
        }
    }
    else{
        container.innerHTML = "DONE!";
        buttonsDiv.style.opacity = "0";
    }
}

function counting(){
    remseconds = seconds % 60;
    minuts = Math.floor(seconds / 60);

    if(remseconds < 10){
        remseconds = "0" + remseconds;
    }

    container.innerHTML = minuts + " : " + remseconds;
    setInterval(count, 1000);
}

If you have any ideas in order to solve this issue please let me know.

Body:
You can also add a single CSS file with those contents to a single page, specifying a condition in PHP like so in the <head>:

<?php
    if (is_page(id-of-the-page)) {
?>
    <link rel="stylesheet" href="/path/to/stylesheet.css" />
<?php
    }
?>

Just make sure to set the correct ID of the page.


问:
How to add data manually and from other tables to a table in SQL?
I need to insert data into a relation table. I want to add three different types of data. Two ints and a string. The table looks like this:

```<code>drop table if exists Favorite cascade;
create table Favorite (

    id_user int,
    id_serie int,
    since date,
    primary key (id_user, id_serie),
    foreign key (id_user) references User (id_user),
    foreign key (id_serie) references Serie (id_serie)
);
</code>```

Tables User and Serie have been already created and it's values have been already inserted.

I want to insert into table Favorite all the data, making sure Favorite.id_user = User.id_user and also Favorite.id_serie = Serie.id_serie but I also want to add manually the since field.

How can I do this?

```<code>insert into Favorite (id_user, id_serie, since) [What should I type here?];
</code>```

Would something like this work (I guess it won't)?

```<code>insert into Favorite (id_user, id_serie, since) select User.id_user, Sere.id_serie from User, Serie values ('2020/02/15');
</code>```

Thanks in advance.

答:
INSERT INTO Favorite (id_user, id_serie, since)
SELECT
    User.id_user,
    Serie.id_serie,
    '2020/02/15'
FROM User, Serie
WHERE ...
```

Body:
I need to insert data into a relation table. I want to add three different types of data. Two ints and a string. The table looks like this:

drop table if exists Favorite cascade;
create table Favorite (

    id_user int,
    id_serie int,
    since date,
    primary key (id_user, id_serie),
    foreign key (id_user) references User (id_user),
    foreign key (id_serie) references Serie (id_serie)
);

Tables User and Serie have been already created and it's values have been already inserted.

I want to insert into table Favorite all the data, making sure Favorite.id_user = User.id_user and also Favorite.id_serie = Serie.id_serie but I also want to add manually the since field.

How can I do this?

insert into Favorite (id_user, id_serie, since) [What should I type here?];

Would something like this work (I guess it won't)?

insert into Favorite (id_user, id_serie, since) select User.id_user, Sere.id_serie from User, Serie values ('2020/02/15');

Thanks in advance.


问:
Nuget Restore of Azure Devops Artifacts from within gulpfile
I'm trying to restore a NuGet package from an Azure Devops Artifact to my local installation as part of a gulpfile script.

However, I'm getting a

Response status code does not indicate success: 401 (Unauthorized).

with:

Unable to load the service index for source https://my-visualstudio-dot-com-npm-feed-here

I've tried creating a nugetauth.npmrc file with the following content:

```<code>registry=https://my-visualstudio-dot-com-npm-feed-here
always-auth=true
</code>```

I then run:

vsts-npm-auth -config nugetauth.npmrc

to generate my new .npmrc file, which I then place in the same directory as my package.json and gulpfile.js files.

When I subsequently run my 'Nuget-restore' task from task runner (with "gulp-nuget-restore": "^0.7.0"), it's failing to authenticate to my feed. What am I missing?

答:
We actually found two ways of resolving this in the end.

One was to use the gulp-nuget task instead, to download a specific version of Nuget.exe (5.0.2) which would then allow us to subsequently run the restore (as I believe that version of Nuget uses the credential provider by default).

The other (which we ended up going with) was to add

```<code>overrideParams.push('/p:NuGetInteractive=true')
</code>```

to the msbuild task. This will prompt users to log in if not authenticated.

Body:
I'm trying to restore a NuGet package from an Azure Devops Artifact to my local installation as part of a gulpfile script.

However, I'm getting a

Response status code does not indicate success: 401 (Unauthorized).

with:

Unable to load the service index for source https://my-visualstudio-dot-com-npm-feed-here

I've tried creating a nugetauth.npmrc file with the following content:

registry=https://my-visualstudio-dot-com-npm-feed-here
always-auth=true

I then run:

vsts-npm-auth -config nugetauth.npmrc

to generate my new .npmrc file, which I then place in the same directory as my package.json and gulpfile.js files.

When I subsequently run my 'Nuget-restore' task from task runner (with "gulp-nuget-restore": "^0.7.0"), it's failing to authenticate to my feed. What am I missing?

Body:
We actually found two ways of resolving this in the end.

One was to use the gulp-nuget task instead, to download a specific version of Nuget.exe (5.0.2) which would then allow us to subsequently run the restore (as I believe that version of Nuget uses the credential provider by default).

The other (which we ended up going with) was to add

overrideParams.push('/p:NuGetInteractive=true')

to the msbuild task. This will prompt users to log in if not authenticated.


问:
VueX update state from action with commit
I'm pretty new to Vuex, can someone tell me why I can't access the state from an action, modify it, and then commit it? I make a "deep" copy of the state array before I change it. What is the alternative best practice way of doing this?

This is my action:

```<code>[Action.UPDATE_CHERRYPICK_SIZE] ({ state, commit }, { recipe, size }) {
    var shoppinglist = [...state.shoppinglist]
    var cp = shoppinglist.find(v => v.recipe.id === recipe.id)
    cp.size = size
    commit(Mutation.SET_SHOPPINGLIST, shoppinglist)
}
</code>```

答:
Only make changes to state in mutations. (That's why it's called mutations.) You don't need to clone the list.  Create a mutation for setting cp size:

```<code>SET_CP_SIZE(state, { cp, size }) {
  cp.size = size;
}
</code>```

And in your action:

```<code>[Action.UPDATE_CHERRYPICK_SIZE] ({ state, commit }, { recipe, size }) {
  var cp = state.shoppinglist.find(v => v.recipe.id === recipe.id)
  commit(Mutation.SET_CP_SIZE, { cp, size })
}
</code>```

This way doesn't use state in the mutation directly, but that's fine.  Instead you are setting cp which is an item of some state array.

Body:
I'm pretty new to Vuex, can someone tell me why I can't access the state from an action, modify it, and then commit it? I make a "deep" copy of the state array before I change it. What is the alternative best practice way of doing this?

This is my action:

[Action.UPDATE_CHERRYPICK_SIZE] ({ state, commit }, { recipe, size }) {
    var shoppinglist = [...state.shoppinglist]
    var cp = shoppinglist.find(v => v.recipe.id === recipe.id)
    cp.size = size
    commit(Mutation.SET_SHOPPINGLIST, shoppinglist)
}

Body:
Only make changes to state in mutations. (That's why it's called mutations.) You don't need to clone the list.  Create a mutation for setting cp size:

SET_CP_SIZE(state, { cp, size }) {
  cp.size = size;
}

And in your action:

[Action.UPDATE_CHERRYPICK_SIZE] ({ state, commit }, { recipe, size }) {
  var cp = state.shoppinglist.find(v => v.recipe.id === recipe.id)
  commit(Mutation.SET_CP_SIZE, { cp, size })
}

This way doesn't use state in the mutation directly, but that's fine.  Instead you are setting cp which is an item of some state array.


问:
Edit/change value in CSV file Python
I am self-learning python and trying to solve this question:

Build a programme that lets a user register with email and password and these information will be stored into users.csv file. After register, a user can use registered email and password to login, a user can change the password after logged in. This is my code:

```<code>import csv
import shutil
from tempfile import NamedTemporaryFile

def registerUser():
    with open('users.csv', mode='w', newline='') as f:
        fieldnames = ['email', 'password']
        #writer = csv.writer(f, delimiter=',')
        print('Please enter your email and password!')
        user_email = input('Enter your new email: ')
        user_pass = input('Enter your new password: ')
        user_pass1 = input('Enter your password again: ')
        if user_pass == user_pass1:
            writer = csv.DictWriter(f, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerow({'email': user_email, 'password': user_pass})
            print('Congrat! You are registered!')
        else:
            print('Please try again!')

def loginUser():
    print('Use your registered email and password to login: ')
    email = input('Email: ')
    password = input('Password:')
    with open('users.csv', mode='r') as f:
        reader = csv.DictReader(f)
        for p in reader:
            if p['email'] == email and p['password'] == password:
                print('Login successfully!')
                return True
            else:
                print('Try again!')
                return False

def changePassword(email = None, edit_password = None):
    filename = 'users.csv'
    temp_file = NamedTemporaryFile(mode='w', delete=False)
    with open(filename, 'rb') as csvfile, temp_file:
        reader = csv.DictReader(csvfile)
        fieldnames = ['email', 'password']
        new_pass = input('Enter new password: ')
        new_pass1 = input('Enter new password again: ')
        writer = csv.DictWriter(temp_file, fieldnames=fieldnames)
        for row in reader:
            if edit_password is not None:
                if new_pass == new_pass1 and row['password'] == edit_password:
                    row['password'] = new_pass
                else:
                    print('Try again!')
            writer.writerow(row)
        shutil.move(temp_file.name, filename)
        return True
    return False

active = True
logged_in = False
# main loop
while active:
    if logged_in:
        print('1. Logout \n 2. Change password \n 3. Quit')
    else:
        print('1. Login \n2. Register \n3. Quit')
    choice = input('What would you like to do?').lower()
    if choice =='register' and logged_in == False:
        registerUser()
    elif choice == 'login' and logged_in == False:
        logged_in = loginUser()
    elif choice =='change' and logged_in == True:
        print('Change password!')
        changePassword()
    elif choice == 'quit':
        active = False
        print('Thanks for using our software!')
    elif choice == 'logout' and logged_in == True:
        logged_in = False
        print('Log out successfully!')
    else:
        print('Try again')
</code>```

However, changePassword function does not work. Any thought would be appreciated.

答:
You can use pandas</p>

```<code>import pandas as pd
df = pd.read_csv('users.csv')
df.loc[df['email'] == user_email, 'password'] = new_pass
df.to_csv('users.csv')
</code>```

Title: Edit/change value in CSV file Python

Body:
I am self-learning python and trying to solve this question:

Build a programme that lets a user register with email and password and these information will be stored into users.csv file. After register, a user can use registered email and password to login, a user can change the password after logged in. This is my code:

import csv
import shutil
from tempfile import NamedTemporaryFile

def registerUser():
    with open('users.csv', mode='w', newline='') as f:
        fieldnames = ['email', 'password']
        #writer = csv.writer(f, delimiter=',')
        print('Please enter your email and password!')
        user_email = input('Enter your new email: ')
        user_pass = input('Enter your new password: ')
        user_pass1 = input('Enter your password again: ')
        if user_pass == user_pass1:
            writer = csv.DictWriter(f, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerow({'email': user_email, 'password': user_pass})
            print('Congrat! You are registered!')
        else:
            print('Please try again!')

def loginUser():
    print('Use your registered email and password to login: ')
    email = input('Email: ')
    password = input('Password:')
    with open('users.csv', mode='r') as f:
        reader = csv.DictReader(f)
        for p in reader:
            if p['email'] == email and p['password'] == password:
                print('Login successfully!')
                return True
            else:
                print('Try again!')
                return False

def changePassword(email = None, edit_password = None):
    filename = 'users.csv'
    temp_file = NamedTemporaryFile(mode='w', delete=False)
    with open(filename, 'rb') as csvfile, temp_file:
        reader = csv.DictReader(csvfile)
        fieldnames = ['email', 'password']
        new_pass = input('Enter new password: ')
        new_pass1 = input('Enter new password again: ')
        writer = csv.DictWriter(temp_file, fieldnames=fieldnames)
        for row in reader:
            if edit_password is not None:
                if new_pass == new_pass1 and row['password'] == edit_password:
                    row['password'] = new_pass
                else:
                    print('Try again!')
            writer.writerow(row)
        shutil.move(temp_file.name, filename)
        return True
    return False

active = True
logged_in = False
# main loop
while active:
    if logged_in:
        print('1. Logout \n 2. Change password \n 3. Quit')
    else:
        print('1. Login \n2. Register \n3. Quit')
    choice = input('What would you like to do?').lower()
    if choice =='register' and logged_in == False:
        registerUser()
    elif choice == 'login' and logged_in == False:
        logged_in = loginUser()
    elif choice =='change' and logged_in == True:
        print('Change password!')
        changePassword()
    elif choice == 'quit':
        active = False
        print('Thanks for using our software!')
    elif choice == 'logout' and logged_in == True:
        logged_in = False
        print('Log out successfully!')
    else:
        print('Try again')

However, changePassword function does not work. Any thought would be appreciated.

Body:
You can use pandas

import pandas as pd
df = pd.read_csv('users.csv')
df.loc[df['email'] == user_email, 'password'] = new_pass
df.to_csv('users.csv')


问:
F# - Extract option from Expr
Is there a way to extract a parameter from an Expr?

An example:

```<code>let hasStringOption (e:Expr<string option>) =
    let myOption : string option = ..some code to get the string option from e
</code>```

How would I get the string option inside the Expr and assign it to myOption?

答:
With FSharp.PowerPack.Linq.dll referenced you can do:

```<code>  open Microsoft.FSharp.Quotations
  open Microsoft.FSharp.Linq.QuotationEvaluation

  let hasStringOption (e:Expr<string option>) =
      let myOption : string option = e.Eval()
      myOption.IsSome

  printfn "%A" (hasStringOption <@ Some "hello" @>)
  printfn "%A" (hasStringOption <@ None @>)
</code>```

However, reportedly this is quite slow and uses LINQ expressions as an intermediary step.

ContentLicense: CC BY-SA 3.0

Title: F# - Extract option from Expr

Body:
Is there a way to extract a parameter from an Expr?

An example:

let hasStringOption (e:Expr<string option>) =
    let myOption : string option = ..some code to get the string option from e

How would I get the string option inside the Expr and assign it to myOption?

Body:
With FSharp.PowerPack.Linq.dll referenced you can do:

  open Microsoft.FSharp.Quotations
  open Microsoft.FSharp.Linq.QuotationEvaluation

  let hasStringOption (e:Expr<string option>) =
      let myOption : string option = e.Eval()
      myOption.IsSome

  printfn "%A" (hasStringOption <@ Some "hello" @>)
  printfn "%A" (hasStringOption <@ None @>)

However, reportedly this is quite slow and uses LINQ expressions as an intermediary step.


问:
Durable function - activity function max. time out
What is the max. time out period of activity function which orchestrator function calls in  Durable function on consumption hosting plan?</p>

答:
The activity function is similar to any function invocation and is bound by the same timeout durations depending on the plan that they are deployed to.

In case of the consumption plan, its 5 minutes by default and can be configured up to 10 minutes by setting the functionTimeout property in host.json.


问:
Create CloudFront Invalidations in Cross AWS account
I have two AWS accounts (E.g. Account A & Account B). I have created a user with and attached a policy (Costumer Managed) Which has the following permission in account A.

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "cloudfront:CreateInvalidation",
            "Resource": "arn:aws:cloudfront::{ACCOUNT-B_ACCOUNT-ID-WITHOUT-HYPHENS}:distribution/{ACCOUNT_B-CF-DISTRIBUTION-ID}"
        }
    ]
}
</code>```

From AWS-CLI (Which is configured with Account A's user) I'm trying to create invalidation for the above mentioned CF distribution ID in Account B. I'm getting access denied.

Do we need any other permission to create invalidation for CF distribution in different AWS account?

答:
Cross account access only available for few AWS Services like Amazon Simple Storage Service (S3) buckets, S3 Glacier vaults, Amazon Simple Notification Service (SNS) topics, and Amazon Simple Queue Service (SQS) queues.

Refer: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html (Role for cross-account access section)

Body:
I have two AWS accounts (E.g. Account A & Account B). I have created a user with and attached a policy (Costumer Managed) Which has the following permission in account A.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "cloudfront:CreateInvalidation",
            "Resource": "arn:aws:cloudfront::{ACCOUNT-B_ACCOUNT-ID-WITHOUT-HYPHENS}:distribution/{ACCOUNT_B-CF-DISTRIBUTION-ID}"
        }
    ]
}

From AWS-CLI (Which is configured with Account A's user) I'm trying to create invalidation for the above mentioned CF distribution ID in Account B. I'm getting access denied.

Do we need any other permission to create invalidation for CF distribution in different AWS account?


问:
Persist BERT model on disk as pickle file
I have managed to get the BERT model to work on johnsnowlabs-spark-nlp library. I am able to save the "trained model" on disk as follows.

Fit Model

```<code>df_bert_trained = bert_pipeline.fit(textRDD)

df_bert=df_bert_trained.transform(textRDD)
</code>```

save model

```<code>df_bert_trained.write().overwrite().save("/home/XX/XX/trained_model")
</code>```

However,

First, as per the docs here https://nlp.johnsnowlabs.com/docs/en/concepts, it's stated that one can load the model as

```<code>EmbeddingsHelper.load(path, spark, format, reference, dims, caseSensitive)
</code>```

but it's unclear to me what the variable "reference" represents at this point.

Second, has anyone managed to save the BERT embeddings as a pickle file in python?

答:
In Spark NLP, BERT comes as a pre-trained model. It means it's already a model that was trained, fit, etc. and saved in the right format.

That's being said, there is no reason to fit or save it again. You can, however, save the result of it once you transform your DataFrame to a new DataFrame that has BERT embeddings for each token.

Example:

Start a Spark Session in spark-shell with Spark NLP package

spark-shell --packages JohnSnowLabs:spark-nlp:2.4.0
```

<pre class="lang-scala prettyprint-override"><code>import com.johnsnowlabs.nlp.annotators._
import com.johnsnowlabs.nlp.base._

val documentAssembler = new DocumentAssembler()
      .setInputCol("text")
      .setOutputCol("document")

    val sentence = new SentenceDetector()
      .setInputCols("document")
      .setOutputCol("sentence")

    val tokenizer = new Tokenizer()
      .setInputCols(Array("sentence"))
      .setOutputCol("token")

    // Download and load the pretrained BERT model
    val embeddings = BertEmbeddings.pretrained(name = "bert_base_cased", lang = "en")
      .setInputCols("sentence", "token")
      .setOutputCol("embeddings")
      .setCaseSensitive(true)
      .setPoolingLayer(0)

    val pipeline = new Pipeline()
      .setStages(Array(
        documentAssembler,
        sentence,
        tokenizer,
        embeddings
      ))

// Test and transform

   val testData = Seq(
      "I like pancakes in the summer. I hate ice cream in winter.",
      "If I had asked people what they wanted, they would have said faster horses"
    ).toDF("text")

    val predictionDF = pipeline.fit(testData).transform(testData)

</code>```

The predictionDF is a DataFrame that contains BERT embeddings for each token inside your dataset. The BertEmbeddings pre-trained models are coming from TF Hub, which means they are the exact same pre-trained weights published by Google. All 5 models are available:

bert_base_cased (en)

bert_base_uncased (en)

bert_large_cased (en)

bert_large_uncased (en)

bert_multi_cased (xx)

Let me know if you have any questions or problems and I'll update my answer.

References:

https://github.com/JohnSnowLabs/spark-nlp

https://github.com/JohnSnowLabs/spark-nlp-models

https://github.com/JohnSnowLabs/spark-nlp-workshop

Body:
I have managed to get the BERT model to work on johnsnowlabs-spark-nlp library. I am able to save the "trained model" on disk as follows.

Fit Model

df_bert_trained = bert_pipeline.fit(textRDD)

df_bert=df_bert_trained.transform(textRDD)

save model

df_bert_trained.write().overwrite().save("/home/XX/XX/trained_model")

However,

First, as per the docs here https://nlp.johnsnowlabs.com/docs/en/concepts, it's stated that one can load the model as

EmbeddingsHelper.load(path, spark, format, reference, dims, caseSensitive)

but it's unclear to me what the variable "reference" represents at this point.

Second, has anyone managed to save the BERT embeddings as a pickle file in python?

Body:
In Spark NLP, BERT comes as a pre-trained model. It means it's already a model that was trained, fit, etc. and saved in the right format.

That's being said, there is no reason to fit or save it again. You can, however, save the result of it once you transform your DataFrame to a new DataFrame that has BERT embeddings for each token.

Example:

Start a Spark Session in spark-shell with Spark NLP package

spark-shell --packages JohnSnowLabs:spark-nlp:2.4.0

import com.johnsnowlabs.nlp.annotators._
import com.johnsnowlabs.nlp.base._

val documentAssembler = new DocumentAssembler()
      .setInputCol("text")
      .setOutputCol("document")

    val sentence = new SentenceDetector()
      .setInputCols("document")
      .setOutputCol("sentence")

    val tokenizer = new Tokenizer()
      .setInputCols(Array("sentence"))
      .setOutputCol("token")

    // Download and load the pretrained BERT model
    val embeddings = BertEmbeddings.pretrained(name = "bert_base_cased", lang = "en")
      .setInputCols("sentence", "token")
      .setOutputCol("embeddings")
      .setCaseSensitive(true)
      .setPoolingLayer(0)

    val pipeline = new Pipeline()
      .setStages(Array(
        documentAssembler,
        sentence,
        tokenizer,
        embeddings
      ))

// Test and transform

   val testData = Seq(
      "I like pancakes in the summer. I hate ice cream in winter.",
      "If I had asked people what they wanted, they would have said faster horses"
    ).toDF("text")

    val predictionDF = pipeline.fit(testData).transform(testData)

The predictionDF is a DataFrame that contains BERT embeddings for each token inside your dataset. The BertEmbeddings pre-trained models are coming from TF Hub, which means they are the exact same pre-trained weights published by Google. All 5 models are available:

bert_base_cased (en)

bert_base_uncased (en)

bert_large_cased (en)

bert_large_uncased (en)

bert_multi_cased (xx)

Let me know if you have any questions or problems and I'll update my answer.

References:

https://github.com/JohnSnowLabs/spark-nlp

https://github.com/JohnSnowLabs/spark-nlp-models

https://github.com/JohnSnowLabs/spark-nlp-workshop


问:
Where's definitive reference on string formatting
does anyone know of a good online resource that simply and definitevly explains how to use the string formatter method...?

I need to write a series of "records" into a set ascii text files. I need to "delimit" each "record" with a cr-lf sequence in a windows 2008 server environment.
Therefore I'm trying to figure out how to add a \r\n character string at the end of each "record". I tried a "record_string.append(CR) and LF" ; but it didn't work.

Thanks much

Guy

答:
The documentation on the Formatter class appears to be comprehensive.

It has this to say about line separators:

Line Separator

The conversion does not correspond to any argument.

'n' -   the platform-specific line separator as returned by System.getProperty("line.separator").
Flags, width, and precision are not applicable. If any are provided an IllegalFormatFlagsException, IllegalFormatWidthException, and IllegalFormatPrecisionException, respectively will be thrown.


问:
Full Screen Mobile Menu and Scroll limit to its contents
Good morning,

I made a Mobile menu that is activated by clicking on a button on the main page.

This one takes the whole page. On the other hand, I have to limit the scroll so that I don't see the whole page. I need to be able to scroll the content of the menu, so the fixed position doesn't help.
How can I force the viewport to the content of my div when it is in display: block?

The first solution I tried is Here.

But I don't want the menu to have infinite scroll, only on its content

The second that I've tried is Here.

Thank you in advance, I've tried various solutions, but nothing works yet.

答:
You are on right track its not the scroll which menu have its you body
  element scroll please see below example, i just make some borders to
  clear you

If you see inner scroll is menu scroll while the outer one is your body scroll as menu is is inside body that why its visible

$("button").click(function(){
    $("body").toggleClass("over");
    $(".menu").addClass("active");
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    height: 100%;
    background-color: red;
    overflow: auto;
}
.over{
 overflow: hidden;
}
.menu {
    position: fixed;
    top: 0;
    left: 0;
    display: block;
    /* width: auto; */
    /* height: 100%; */
    margin: 0;
    padding: 0;
    background-color: white;
    z-index: 1;
    border: 1px solid;
    right: 0;
    bottom: 0;
    padding: 10px;
    overflow-y: scroll;

display:none;
}
.menu.active{
  display: block;
}</code>```

<button>Toggle menu</button>

  Menu

```

Body:
You are on right track its not the scroll which menu have its you body
  element scroll please see below example, i just make some borders to
  clear you

If you see inner scroll is menu scroll while the outer one is your body scroll as menu is is inside body that why its visible

$("button").click(function(){
    $("body").toggleClass("over");
    $(".menu").addClass("active");
  });

body {
    height: 100%;
    background-color: red;
    overflow: auto;
}
.over{
 overflow: hidden;
}
.menu {
    position: fixed;
    top: 0;
    left: 0;
    display: block;
    /* width: auto; */
    /* height: 100%; */
    margin: 0;
    padding: 0;
    background-color: white;
    z-index: 1;
    border: 1px solid;
    right: 0;
    bottom: 0;
    padding: 10px;
    overflow-y: scroll;

display:none;
}
.menu.active{
  display: block;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<button>Toggle menu</button>
<div class="menu">
  Menu

</div>
</body>


问:
Actual mechanics of Maven dependency resolution?
I believe I understand the concept behind dependency management in Maven, and I have seen it work so flawlessly.  However, I am not sure how this gets resolved in practice.  For example, if I show a dependency with a groupId of org.apache.httpcomponents, how does Maven know where to download the corresponding artifact from, if it is not available locally?

And if I create an artifact locally, and give it a nice URIish groupId, how does Maven know that artifact does not need to be downloaded from anywhere?

答:
Maven caches all external artifacts in its local repository and also puts all interally built artifacts into the local repository. This is the first place to look.

Artifacts not present there, or those which need an update and drawn from the configured external repositories. If nothing is configured, MavenCentral is used.


答:
Would something like this work (I guess it won't)?

Yes, what you ask will work pretty well.

Is this what you are looking for?

```<code>INSERT INTO table3 (table1.column1, table1.column2, table2.column3, ...)
SELECT table1.column1, table1.column2, table2.column3, 'constant value' ...
FROM table1, table 2
WHERE condition;
</code>```

Go here for more
https://www.w3schools.com/sql/sql_insert_into_select.asp

Title: How to add data manually and from other tables to a table in SQL?

Body:
Would something like this work (I guess it won't)?

Yes, what you ask will work pretty well.

Is this what you are looking for?

INSERT INTO table3 (table1.column1, table1.column2, table2.column3, ...)
SELECT table1.column1, table1.column2, table2.column3, 'constant value' ...
FROM table1, table 2
WHERE condition;

Go here for more
https://www.w3schools.com/sql/sql_insert_into_select.asp


问:
Extract all the recurring element of XML using java
My XML looks like below and I need to extract multiple ID element in
   an output xml:-

```<code><?xml version="1.0" encoding="utf-8"?>
<Stock>
    <PIdentification>
    <CatalogVersion></CatalogVersion>
    <AccountID></AccountID>
    <CustomerId></CustomerId>
    </ProviderIdentification>
    <Product>
        <ArticleName>Monitors</ArticleName>
        <BaseUnit></BaseUnit>
        <Notes></Notes>
        <ID>11f13e2e-ae97-45b5-a9a9-23fa7f6bb767</ID>
        <ID>b22834c0-a570-4e6b-97c3-5067a14d118d</ID>
        <ID>ed458593-5e1a-4dc1-94f0-a66eeef2dd79</ID>
        <ID>d25584a9-1db2-48cf-9a70-9b81e5a7e7f2</ID>
    </Product>
</Stock>
</code>```

I have used "Nodelist" to extract "ID" but I am getting just one element
    and not all 4, below is the part of the code:-

```<code>{
    Node IDNode = element.getElementsByTagName("ID").item(0);
    IDXml = toStringXml(IDNode , true);
}
</code>```

I am not able to reiterate for look to get all the IDs, please let me
   know how to get all ID, any help is appreciated.

```<code>    private static String toStringXml(Node elt, boolean xmlDeclaration)
    throws TransformerException {
     TransformerFactory transformerFactory = TransformerFactory
        .newInstance();
    Transformer transformer = transformerFactory.newTransformer();

    if(xmlDeclaration)
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    DOMSource source = new DOMSource(elt);
    StreamResult result = new StreamResult(new StringWriter());
    transformer.transform(source, result);

    return result.getWriter().toString();
    }
</code>```

答:
You got all id's but you are only looking at first item with .item(id).

Method getElementsByTageName("ID") returns you NodeList so you can got trough all ids for example like that:

```<code>File xmlFile = new File("src/main/resources/example.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document element = dBuilder.parse(xmlFile);

NodeList list = element.getElementsByTagName("ID");
for (int i = 0; i < list.getLength(); i++){
    Node specificIDNode = list.item(i);
    System.out.println(specificIDNode.getTextContent());
}
</code>```

Body:
My XML looks like below and I need to extract multiple ID element in
   an output xml:-

<?xml version="1.0" encoding="utf-8"?>
<Stock>
    <PIdentification>
    <CatalogVersion></CatalogVersion>
    <AccountID></AccountID>
    <CustomerId></CustomerId>
    </ProviderIdentification>
    <Product>
        <ArticleName>Monitors</ArticleName>
        <BaseUnit></BaseUnit>
        <Notes></Notes>
        <ID>11f13e2e-ae97-45b5-a9a9-23fa7f6bb767</ID>
        <ID>b22834c0-a570-4e6b-97c3-5067a14d118d</ID>
        <ID>ed458593-5e1a-4dc1-94f0-a66eeef2dd79</ID>
        <ID>d25584a9-1db2-48cf-9a70-9b81e5a7e7f2</ID>
    </Product>
</Stock>

I have used "Nodelist" to extract "ID" but I am getting just one element
    and not all 4, below is the part of the code:-

{
    Node IDNode = element.getElementsByTagName("ID").item(0);
    IDXml = toStringXml(IDNode , true);
}

I am not able to reiterate for look to get all the IDs, please let me
   know how to get all ID, any help is appreciated.

    private static String toStringXml(Node elt, boolean xmlDeclaration)
    throws TransformerException {
     TransformerFactory transformerFactory = TransformerFactory
        .newInstance();
    Transformer transformer = transformerFactory.newTransformer();

    if(xmlDeclaration)
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    DOMSource source = new DOMSource(elt);
    StreamResult result = new StreamResult(new StringWriter());
    transformer.transform(source, result);

    return result.getWriter().toString();
    }

Body:
You got all id's but you are only looking at first item with .item(id).

Method getElementsByTageName("ID") returns you NodeList so you can got trough all ids for example like that:

File xmlFile = new File("src/main/resources/example.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document element = dBuilder.parse(xmlFile);

NodeList list = element.getElementsByTagName("ID");
for (int i = 0; i < list.getLength(); i++){
    Node specificIDNode = list.item(i);
    System.out.println(specificIDNode.getTextContent());
}


问:
os_log, logging subsystem and objectiveC not compiling
I'm working on a project that has swift and objectiveC. I'd like to use os_log, but can't figure it out.
I can get the log to work to the default log, but if I try to create a custom log then the compiler complains about not knowing about OSLog in my objC files

Here is the swift extension:

```<code>import os.log

 extension OSLog {
    private static var subsystem = Bundle.main.bundleIdentifier!

     static let main = OSLog(subsystem: subsystem, category: "main")
}
</code>```

In my objectiveC file I import the -Swift.h file and it can see other swift class I have, but still can't see OSLog.
os_log_debug([OSLog main], "message");

gets the following errors:
- Use of undeclared identifier 'Log'; did you mean 'log'?
- Bad receiver-type 'void (*)(id, ...)'

I'm clearly missing something ...

答:
Try to add @objc before extension:

@objc extension OSLog {
    private static var subsystem = Bundle.main.bundleIdentifier!

    static let main = OSLog(subsystem: subsystem, category: "main")
}

```

Body:
I'm working on a project that has swift and objectiveC. I'd like to use os_log, but can't figure it out.
I can get the log to work to the default log, but if I try to create a custom log then the compiler complains about not knowing about OSLog in my objC files

Here is the swift extension:

import os.log

 extension OSLog {
    private static var subsystem = Bundle.main.bundleIdentifier!

     static let main = OSLog(subsystem: subsystem, category: "main")
}

In my objectiveC file I import the -Swift.h file and it can see other swift class I have, but still can't see OSLog.
os_log_debug([OSLog main], "message");

gets the following errors:
- Use of undeclared identifier 'Log'; did you mean 'log'?
- Bad receiver-type 'void (*)(id, ...)'

I'm clearly missing something ...


问:
Input clicked, add class Angular 8
I have an array which produces a set of questions. It displays them as radio buttons.

Here is the HTML

```<code>          <div *ngSwitchCase="'radio'">
            <ul>
              <li
                *ngFor="let option of question.options"
                class="col-12 col-sm-6 p-0 purchase-type"
              >
                <input
                  class="form-control"
                  id="{{ option.id }}"
                  formControlName="{{ question.name }}"
                  value="{{ option.value }}"
                  type="radio"
                  (click)="clickEvent()"
                  [ngClass]="status ? 'success' : 'danger'"
                />
                <label for="{{ option.id }}" class="btn btn-choice {{ option.class }}">
                  <span class="hidden-xs">{{ option.id }} </span
                  ><span class="hidden-xs"> (</span> {{ option.label
                  }}<span class="hidden-xs">)</span></label
                >
              </li>
            </ul>
          </div>
</code>```

Boolean inside the .ts

```<code>  status: boolean = false;
  clickEvent() {
    this.status = !this.status;
  }
</code>```

As this is in an array, i'm struggling to toggle a class between each. At the moment, when I select any radio button, all radio button elements get the same class applied.

How would I only apply this to the radio button clicked?

Pretty new to Angular. Appreciate any help or suggestions.

Thanks in advance

答:
If you have radio buttons you want to style once toggled (chosen), there are a few ways you could do it. One way would be as follows.

Listen to the formControl Value

```<code><input [formControlName]="radio" value="value" [ngClass]="form.controls.get('radio').value == 'value' ? 'active' : 'inactive'"></input>
</code>```

You could also make the radio input into a component.

Component

Then give it a generic template reference and check if it is checked.

(Warning: this one may be a little more complicated as you have to pass formControlName and fromGroup down, either as Inputs or implementing controlValueAccessor)

```<code><input #radio [ngClass]="radio.checked ? 'active' : 'inactive'"></input>
</code>```

Or you could call a function in typescript to resolve it as well.

Function

```<code><input [formControlName]="radio" value="value" [ngClass]="checked(value) ? 'active' : 'inactive'"></input>

checked(value) {
    if(value == this.form.control['radio'].value) {
        return true
    } else {
        return false
    }

}
</code>```

I am sure there are other tidier ways as well, but hopefully the above is helpful.

Title: Input clicked, add class Angular 8

Body:
I have an array which produces a set of questions. It displays them as radio buttons.

Here is the HTML

                <input
                  class="form-control"
                  id="{{ option.id }}"
                  formControlName="{{ question.name }}"
                  value="{{ option.value }}"
                  type="radio"
                  (click)="clickEvent()"
                  [ngClass]="status ? 'success' : 'danger'"
                />

                  {{ option.id }}  ( {{ option.label
                  }})

Boolean inside the .ts

  status: boolean = false;
  clickEvent() {
    this.status = !this.status;
  }

As this is in an array, i'm struggling to toggle a class between each. At the moment, when I select any radio button, all radio button elements get the same class applied.

How would I only apply this to the radio button clicked?

Pretty new to Angular. Appreciate any help or suggestions.

Thanks in advance

Body:
If you have radio buttons you want to style once toggled (chosen), there are a few ways you could do it. One way would be as follows.

Listen to the formControl Value

<input [formControlName]="radio" value="value" [ngClass]="form.controls.get('radio').value == 'value' ? 'active' : 'inactive'"></input>

You could also make the radio input into a component.

Component

Then give it a generic template reference and check if it is checked.

(Warning: this one may be a little more complicated as you have to pass formControlName and fromGroup down, either as Inputs or implementing controlValueAccessor)

<input #radio [ngClass]="radio.checked ? 'active' : 'inactive'"></input>

Or you could call a function in typescript to resolve it as well.

Function

<input [formControlName]="radio" value="value" [ngClass]="checked(value) ? 'active' : 'inactive'"></input>

checked(value) {
    if(value == this.form.control['radio'].value) {
        return true
    } else {
        return false
    }

}

I am sure there are other tidier ways as well, but hopefully the above is helpful.


问:
Count the Number of Changes in a Date Column based on another Attribute
Hi everyone I have faced a problem during my data validation. I need to have the number of changes in a date column for every unique variable in name column. For example:

```<code>student.data <- data.frame(student_id = c (1:7),
                            student_name=c("Rick","Rick","Michelle","Michelle","Rick","Michelle","John"),
                            mark = c(623.3,515.2,611.0,729.0,843.25,459.4,846.65),
                            date_of_exam = as.Date(c("2014-01-01","2013-09-23","2014-11-15","2014-05-11", "2014-01-01","2016-04-14","2015-05-12")))
</code>```

I know for a fact that it is kind of complicated but the result must be:

```<code>>table

>"Rick"
1
>"Michelle"
2
>"John"
0
</code>```

thanks in advance for your help.

答:
data.table way :

```<code>library(data.table)

setDT(student.data)
student.data[, .(change = uniqueN(date_of_exam) - 1), student_name]

#   student_name change
#1:         Rick      1
#2:     Michelle      2
#3:         John      0
</code>```

Or in base R :

```<code>aggregate(date_of_exam~student_name,student.data, function(x) length(unique(x)) - 1)
</code>```

Body:
Hi everyone I have faced a problem during my data validation. I need to have the number of changes in a date column for every unique variable in name column. For example:

student.data <- data.frame(student_id = c (1:7),
                            student_name=c("Rick","Rick","Michelle","Michelle","Rick","Michelle","John"),
                            mark = c(623.3,515.2,611.0,729.0,843.25,459.4,846.65),
                            date_of_exam = as.Date(c("2014-01-01","2013-09-23","2014-11-15","2014-05-11", "2014-01-01","2016-04-14","2015-05-12")))

I know for a fact that it is kind of complicated but the result must be:

>table

>"Rick"
1
>"Michelle"
2
>"John"
0

thanks in advance for your help.

Body:
data.table way :

library(data.table)

setDT(student.data)
student.data[, .(change = uniqueN(date_of_exam) - 1), student_name]

#   student_name change
#1:         Rick      1
#2:     Michelle      2
#3:         John      0

Or in base R :

aggregate(date_of_exam~student_name,student.data, function(x) length(unique(x)) - 1)


问:
First value of my PHP Array is returned as 'null' when it has a value
I'd really like some help with the following MySQL / PHP problem (maybe bug?)

I'm trying to retrieve and display an array of data from my database using MySQL / PHP, but when I echo out the array, it returns the first value as 'null'.

So, even though the database has the following info:

```<code>"Example 1", "Example 2", "Example 3"...
</code>```

The php echos out:

```<code>"null", "Example 2, "Example 3"
</code>```

I would imagine this would be a common problem, but I haven't managed to find the required information elsewhere on the internet, so I'm hoping you kind folks can help.

My PHP

```<code>/* If connection to database, run sql statement. */
if ($conn) {
    $fetch = mysql_query("SELECT column FROM table WHERE approved = '1' ");

    // declare empty array to fill later
    $result = array();

    // make sure the MySQL pointer is looking at the first row
    mysql_data_seek($fetch, 0);

    while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {

        foreach ($row as $value) {

            $row_array = $value;

            // push info into new array with just the value
            array_push($result, $row_array);
        }
    }
}
/* Free connection resources. */
mysql_close($conn);

/* Toss back results as json encoded array. */
echo json_encode($result);
</code>```

UPDATE

New code courtesy of Mark B:

```<code>if ($conn)
{
$sql = "SELECT column_name FROM table WHERE comment_approved = '1' ";
$query = mysql_query($sql) or die(mysql_error());

$result = array();
while ($row = mysql_fetch_assoc($query)) {
    $result[] = $row['column_name'];

}

}

/* Free connection resources. */
mysql_close($conn);

/* Toss back results as json encoded array. */
echo json_encode($result);
</code>```

NOTE:

The 'null' problem still occurs with or without the:

```<code> mysql_data_seek($fetch, 0);
</code>```

as that appears to do nothing.

Any help would be great!

SOLVED

Thanks to Mark B who pointed out that the problem was probably in the database rather than the PHP, it turned out there was the character ` lurking where there should have been a '. This caused the information to appear 'null'.

答: You could try removing mysql_data_seek($fetch, 0); as the pointer will already be on the first record if you have just made the query.</p>

Body:
I'd really like some help with the following MySQL / PHP problem (maybe bug?)

I'm trying to retrieve and display an array of data from my database using MySQL / PHP, but when I echo out the array, it returns the first value as 'null'.

So, even though the database has the following info:

"Example 1", "Example 2", "Example 3"...

The php echos out:

"null", "Example 2, "Example 3"

I would imagine this would be a common problem, but I haven't managed to find the required information elsewhere on the internet, so I'm hoping you kind folks can help.

My PHP

/* If connection to database, run sql statement. */
if ($conn) {
    $fetch = mysql_query("SELECT column FROM table WHERE approved = '1' ");

    // declare empty array to fill later
    $result = array();

    // make sure the MySQL pointer is looking at the first row
    mysql_data_seek($fetch, 0);

    while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {

        foreach ($row as $value) {

            $row_array = $value;

            // push info into new array with just the value
            array_push($result, $row_array);
        }
    }
}
/* Free connection resources. */
mysql_close($conn);

/* Toss back results as json encoded array. */
echo json_encode($result);

UPDATE

New code courtesy of Mark B:

if ($conn)
{
$sql = "SELECT column_name FROM table WHERE comment_approved = '1' ";
$query = mysql_query($sql) or die(mysql_error());

$result = array();
while ($row = mysql_fetch_assoc($query)) {
    $result[] = $row['column_name'];

}

}

/* Free connection resources. */
mysql_close($conn);

/* Toss back results as json encoded array. */
echo json_encode($result);

NOTE:

The 'null' problem still occurs with or without the:

 mysql_data_seek($fetch, 0);

as that appears to do nothing.

Any help would be great!

SOLVED

Thanks to Mark B who pointed out that the problem was probably in the database rather than the PHP, it turned out there was the character ` lurking where there should have been a '. This caused the information to appear 'null'.


问:
Python: how to save different .csv for each ID in a pandas dataframe?
I have a dataframe df that looks like the following:

```<code>df
    ID    val
0    A     3
1    A     2
2    B     0
3    B     5
4    B     4
</code>```

I would like to save different dataframes for each users. This is what I am doing

```<code>for i in pd.unique(df['ID']):
      tmp = df[df['ID']==i]
      tmp.to_csv('%s.csv'%i)
</code>```

However I have a very large dataframe and 14k ID. I would like to know if there is a better way to do it.

答:
I think your solution is good, here is alternative:

```<code>for i, g in df.groupby('ID', sort=False):
    g.to_csv('{}.csv'.format(i), index=False)
</code>```

Or solution with f-strings:

```<code>for i, g in df.groupby('ID', sort=False):
    g.to_csv(f'{i}.csv', index=False)
</code>```

Body:
I have a dataframe df that looks like the following:

df
    ID    val
0    A     3
1    A     2
2    B     0
3    B     5
4    B     4

I would like to save different dataframes for each users. This is what I am doing

for i in pd.unique(df['ID']):
      tmp = df[df['ID']==i]
      tmp.to_csv('%s.csv'%i)

However I have a very large dataframe and 14k ID. I would like to know if there is a better way to do it.

Body:
I think your solution is good, here is alternative:

for i, g in df.groupby('ID', sort=False):
    g.to_csv('{}.csv'.format(i), index=False)

Or solution with f-strings:

for i, g in df.groupby('ID', sort=False):
    g.to_csv(f'{i}.csv', index=False)


问:
RedirectToRoute not working in ASP.NET MVC project
I am building a somewhat complex ASP.NET MVC website with multiple controllers. In the Index()-method/handler of each controller I perform some validation and redirect to the default route in case of an error so the user gets redirected to the default page of the website when something goes wrong.
However, for some reason the redirect just doesn't work. I use RedirectToRoute("Default") to redirect to the default route but somehow the Index()-method of the controller I am currently in just gets called again and no redirect is happening. This results in an infinite loop and at some point the browser displays a redirect error.
I have the default route defined as follows:

```<code>routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}",
    defaults: new { controller = "Home", action = "Index" }
</code>```

Why does it not redirect to the Index-action of the Home-controller?

答:
Because you are redirecting to the same route as you are now. The defaults that are specified on the "Default" route only apply when there are no values for "controller" and "action", which is not the case - you are running inside a specific action of a controller.
Probably what you want is to redirect to the root of your app, which is normally where you go to in the first place (your "Default" route seems to indicate that).</p>

Body:
I am building a somewhat complex ASP.NET MVC website with multiple controllers. In the Index()-method/handler of each controller I perform some validation and redirect to the default route in case of an error so the user gets redirected to the default page of the website when something goes wrong.
However, for some reason the redirect just doesn't work. I use RedirectToRoute("Default") to redirect to the default route but somehow the Index()-method of the controller I am currently in just gets called again and no redirect is happening. This results in an infinite loop and at some point the browser displays a redirect error.
I have the default route defined as follows:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}",
    defaults: new { controller = "Home", action = "Index" }

Why does it not redirect to the Index-action of the Home-controller?


问:
How to make context variable dynamic in django template
Is it possible to append 2 context variables together into a single context variable that is calculated at run-time?
For example: if I have  {{contextA}} (which equals 1) and {{contextB}} (which equals 'building') and I wanted to add these together to get context {{1building}} How would I do this?
I have tried:

{{contextA + contextB}}

{{{{contextA}} + {{contextB}}}}

{{contextA |add: contextB}}

{{contextA contextB}}

I suppose this is not possible and this needs to be done in the view using python, but it would be ideal if I could just combine context variables in the template.

答:
U can use {% with template tag as follows (docs here -> https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#with)

{% with newvar=contextA|add:contextB %}
    {{ newvar }}
{% endwith %}
```

<p><code>newvar</code> will have a new value if into a forloop where contextA or contextB change it's value.</p>

<p>As you want to show the value of a context variable with it's name equal to <code>newvar</code> value, the way to accomplish it is to create a custom template tag as follows:</p>

<pre class="lang-py prettyprint-override"><code>
@register.simple_tag(takes_context=True)
def dynvarvalue(context, dynvarname):
    """ Returns the value of dynvarname into the context """
    return context.get(dynvarname, None)
</code>```

I did a small proof of concept:

```<code>{% with 1building='1 building value' contextA='1' contextB='building' %}
  {% dynvarvalue contextA|add:contextB %}
{% endwith %}
</code>```

Which produces the following output, which I think is what you are asking for:

```<code>1 building value
</code>```

Hope this helps.

Note: take into account that if both variables can be transformed to an integer, they will not be concatenated and will be summed as docs says (https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#add)

Note2: I think there are some security caveats to take into account doing this.

Body:
U can use {% with template tag as follows (docs here -> https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#with)

{% with newvar=contextA|add:contextB %}
    {{ newvar }}
{% endwith %}

newvar will have a new value if into a forloop where contextA or contextB change it's value.

As you want to show the value of a context variable with it's name equal to newvar value, the way to accomplish it is to create a custom template tag as follows:

@register.simple_tag(takes_context=True)
def dynvarvalue(context, dynvarname):
    """ Returns the value of dynvarname into the context """
    return context.get(dynvarname, None)

I did a small proof of concept:

{% with 1building='1 building value' contextA='1' contextB='building' %}
  {% dynvarvalue contextA|add:contextB %}
{% endwith %}

Which produces the following output, which I think is what you are asking for:

1 building value

Hope this helps.

Note: take into account that if both variables can be transformed to an integer, they will not be concatenated and will be summed as docs says (https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#add)

Note2: I think there are some security caveats to take into account doing this.


问:
NgbDatepicker show months and years only
I am developing an app using Bootstrap 4 components, powered by Angular 4, and i have trouble configuring the NgbDatepicker directive to show only the months and years, not the days - like for credit cards.

I want to select only the month and year, i don't care about choosing a specific day.

My input looks like this:

```

<input id="demodate" type="text" name="demodate" ngbDatepicker
#startDateDp="ngbDatepicker" [(ngModel)]="modelDate"/>

```

I tried all the properties listed for the directive listed here

https://ng-bootstrap.github.io/#/components/datepicker

but none of  them seem to help me.
Any ideas?

答:
There is a request for that:

https://github.com/ng-bootstrap/ng-bootstrap/issues/1811

As of now (Feb/2020), this is not supported yet.

Body:
I am developing an app using Bootstrap 4 components, powered by Angular 4, and i have trouble configuring the NgbDatepicker directive to show only the months and years, not the days - like for credit cards.

I want to select only the month and year, i don't care about choosing a specific day.

My input looks like this:

<input id="demodate" type="text" name="demodate" ngbDatepicker
#startDateDp="ngbDatepicker" [(ngModel)]="modelDate"/>

I tried all the properties listed for the directive listed here

https://ng-bootstrap.github.io/#/components/datepicker

but none of  them seem to help me.
Any ideas?


问:
Static Parsing: Tell if Two Javascript Functions are the Same
I am looking for a way, using static analysis of two JavaScript functions, to tell if they are the same. Let me define multiple definitions of "the same".

Level 1: The functions are the same except for possible different whitespace, e.g. TABS, CR, LF and SPACES.

Level 2 The functions may have different whitespace like Level 1, but also may have different variable names.

Level 3 ???

For level one, I think I could just remove all (non-literal, which may be tough) whitespace from each string containing the two JS function definitions, and then compare the strings.

For level two, I think I would need to use something like SpiderMonkey's parser to generate a two parse trees, and then write a comparer which walks the trees and allows variables to have different names.

[Edit] Williham, makes a good point below. I do mean identical. Now, I'm looking for some practical strategies, particularly with regards to using parse trees.

答:
Reedit:

To expound on my suggestion for determining identical functions, the following flow can be suggested:

Level 1: Remove any whitespace that is not part of a string literal; insert newlines after each {, ; and } and compare. If equal; the functions are identical, if not:

Level 2: Move all variable declarations and assignments that don't depend on the state of other variables defined in the same scope to the start of the scope they are declared in (or if not wanting to actually parse the JS; the start of the braces); and order them by line length; treating all variable names as being 4 characters long, and falling back to alphabetical ordering ignoring variable names in case of tied lengths. Reorder all collections in alphabetical order, and rename all variables vSNN, where v is literal, S is the number of nested braces and NN is the order in which the variable was encountered.

Compare; if equal, the functions are identical, if not:

Level 3: Replace all string literals with "sNN", where " and s are literal, and NN is the order in which the string was encountered. Compare; if equal, the functions are identical, if not:

Level 4: Normalize the names of any functions known to be the same by using the name of the function with the highest priority according to alphabetical order (in the example below, any calls to p_strlen() would be replaced with c_strlen(). Repeat re-orderings as per level 1 if necessary. Compare; if equal, the functions are identical, if not; the functions are almost certainly not identical.

Original answer:

I think you'll find that you mean "identical", not "the same".

The difference, as you'll find, is critical:

Two functions are identical if, following some manner of normalization, (removing non-literal whitespace, renaming and reordering variables to a normalized order, replacing string literals with placeholders, …) they compare to literally equal.

Two functions are the same if, when called for any given input value they give the same return value. Consider, in the general case, a programming language which has counted, zero-terminated strings (hybrid Pascal/C strings, if you will). A function p_strlen(str) might look at the character count of the string and return that. A function c_strlen(str) might count the number of characters in the string and return that.

While these functions certainly won't be identical, they will be the same: For any given (valid) input value they will give the same value.

My point is:

Determining wether two functions are identical (what you seem to want to achieve) is a (moderately) trivial problem, done as you describe.

Determining wether two functions are truly the same (what you might actually want to achieve) is non-trivial; in fact, it's downright Hard, probably related to the Halting Problem, and not something that can be done with static analysis.

Edit: Of course, functions that are identical are also the same; but in a highly specific and rarely useful way for complete analysis.


问:
Map() function only return last value?
This is data I wanna get :

```<code>    "buttons":[
           {
              "name":"Screen1",
              "display":"Screen1",
              "command":"Screen1"
           },
           {
              "name":"Screen2",
              "display":"Screen2",
              "command":"Screen2"
           },
           {
              "name":"Screen3",
              "display":"Screen3",
              "command":"Screen3"
           }
        ]
     },
</code>```

My code to get data buttons :

```<code>let btnConmand = '';
  let btnName = '';
  let btntest = data.map(ele => {
    if(ele.id == '0100') {
      ele.component[0].buttons.map(btns => {
        btnName = btns.name;
      });
    }
    return btnName ;

  }).join('');
 console.log(btntest)
</code>```

When I write console.log(btntest), it only return last value? How do I get all the values?

答:
I think you want some thing like this.

1) When you use map always return the updated value in map function

```<code>let btntest = data
  .flatMap(ele => {
    let btns = [];
    if (ele.id == "0100") {
      btns = ele.component[0].buttons.map(btns => btns.name);
    }
    return btns;
  })
  .join("");
console.log(btntest);
</code>```

Title: Map() function only return last value?

Body:
This is data I wanna get :

    "buttons":[
           {
              "name":"Screen1",
              "display":"Screen1",
              "command":"Screen1"
           },
           {
              "name":"Screen2",
              "display":"Screen2",
              "command":"Screen2"
           },
           {
              "name":"Screen3",
              "display":"Screen3",
              "command":"Screen3"
           }
        ]
     },

My code to get data buttons :

let btnConmand = '';
  let btnName = '';
  let btntest = data.map(ele => {
    if(ele.id == '0100') {
      ele.component[0].buttons.map(btns => {
        btnName = btns.name;
      });
    }
    return btnName ;

  }).join('');
 console.log(btntest)

When I write console.log(btntest), it only return last value? How do I get all the values?

Body:
I think you want some thing like this.

1) When you use map always return the updated value in map function

let btntest = data
  .flatMap(ele => {
    let btns = [];
    if (ele.id == "0100") {
      btns = ele.component[0].buttons.map(btns => btns.name);
    }
    return btns;
  })
  .join("");
console.log(btntest);


问:
Counteract a bootstrap / select2 rendering delay?
I'm using bootstrap on a site, and using the following code on load to turn my select boxes into select2 dropdowns

```<code>$("select").select2();
</code>```

However when any page with a select dropdown loads, there's a brief delay where the original can be seen before the select2 replacement is drawn in. This is quite jarring as elements of the forms on my pages move around.

Is there a way to generate the select2 HTML in my backend (ASP MVC3) and write it out to the page in such a way that the select2 plugin will still hook up all the behaviours correctly?

答:
Per @roryok's answer, CSS is rendered first so the best solution is to hide the form until after select2 loads.

However you should use visibility:hidden; rather than display:none; so Select2 can access the form input width when rendering its own DOM additons.

Body:
I'm using bootstrap on a site, and using the following code on load to turn my select boxes into select2 dropdowns

$("select").select2();

However when any page with a select dropdown loads, there's a brief delay where the original can be seen before the select2 replacement is drawn in. This is quite jarring as elements of the forms on my pages move around.

Is there a way to generate the select2 HTML in my backend (ASP MVC3) and write it out to the page in such a way that the select2 plugin will still hook up all the behaviours correctly?


问:
Can I bind directly to SQLite table?
I have a Xamarin app on Android. There is SQLite database using sqlite-net-pcl nuget. It has table Items.

Can I bind directly to it eg list.ItemsSource = Database.Items so the changes in the table are reflected automatically in the list?

Since sql-lite-pcl is ORM - it should be possible theoretically..

答:
the consensus here is that it is not possible. I asked on the GitHub to implement it though there was no response for a week.

I would probably write a wrapper myself and post it here later.

But as it stands at the moment the answer is - no

Title: Can I bind directly to SQLite table?


问:
Facebook Graph API - get a photos album ID
I'm writing an application that uploads a photo to facebook. I'm not supplying an album ID so an album is created on behalf of my app.

My question is: how do I get the album ID the photo was uploaded to?

When I GET the the photo information the album isn't present in the JSON which was my hope.

答:
Long, clunky, but theoretically valid way:
http://graph.facebook.com/userid/albumswill get you a list of all the albums the user lets you see, then you can search the album objects (api here) for created_times that match the time you created the album, which you can store when you create the album.

This is almost certainly a horrible way to do it, but it should work.


问:
how can I build Widgets using flutter?
View screen shot here

I need to build this kind of widget to my flutter application.The widget should be can bring across the screen. is its possible? Then How can I do that?
Thanks in advance!

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

    void main() {
        runApp(MyApp());
    }

    class MyApp extends StatelessWidget {

    @override
    Widget build(BuildContext context) {

    return MaterialApp(
        home: Scaffold(
            appBar: AppBar(
            title: Text(“First Widgets")),
        body: myWidget(),
        ),
        );
      }
    }

    Widget myWidget() {
      return Text(
        "Hello, World!",
      );
    }
}
</code>```

Title: how can I build Widgets using flutter?


问:
Github Actions and git clone issue
Having some problems using git clone from within a Github Actions, i get the following no matter what i try:

The code that fails in my main.yml:

```<code>jobs:
 terraform:
   name: 'Terraform with Github Actions!'
   runs-on: ubuntu-latest
   steps:
   - name: 'Login to Azure'
    uses: azure/login@v1
    with:
      creds: ${{ secrets.AZURE_CREDENTIALS }}
  - name: 'Checkout'
    uses: actions/checkout@master
  - name: 'Preparing blueprint-environment'
    run: |
      snip
      git clone git@github.com:ourcompany/whateverrepo.git
</code>```

Error message:

git@github.com: Permission denied (publickey).

Ive seen many posts on adding ssh-keys, but thats locally, not in a ubuntu-release running from Github actions - what am i missing here? I cant generate ssh-keys and add the private key on the fly to the Github repo-settings, how can i fix this?

答:
If you need to checkout two repositories I would recommend using checkout again to a relative path. See the documentation to checkout multiple repos side by side. You may need to use a repo scoped Personal Access Token (PAT)

```<code>  - name: 'Checkout'
    uses: actions/checkout@v2
  - name: 'Preparing blueprint-environment'
    uses: actions/checkout@v2
    with:
      token: ${{ secrets.PAT }}
      repository: ourcompany/whateverrepo
      path: whateverrepo
</code>```

If it's really necessary, Deploy keys can be used to clone a repository via SSH.

Create a new SSH key pair for your repository. Do not set a passphrase.

Copy the contents of the public key (.pub file) to a new repository deploy key and check the box to "Allow write access."

Add a secret to the repository containing the entire contents of the private key.

As shown in the example below, configure actions/checkout to use the deploy key you have created.

```<code>    steps:
      - uses: actions/checkout@v2
        with:
          ssh-key: ${{ secrets.SSH_PRIVATE_KEY }}
</code>```

Title: Github Actions and git clone issue

Body:
Having some problems using git clone from within a Github Actions, i get the following no matter what i try:

The code that fails in my main.yml:

jobs:
 terraform:
   name: 'Terraform with Github Actions!'
   runs-on: ubuntu-latest
   steps:
   - name: 'Login to Azure'
    uses: azure/login@v1
    with:
      creds: ${{ secrets.AZURE_CREDENTIALS }}
  - name: 'Checkout'
    uses: actions/checkout@master
  - name: 'Preparing blueprint-environment'
    run: |
      snip
      git clone git@github.com:ourcompany/whateverrepo.git

Error message:

git@github.com: Permission denied (publickey).

Ive seen many posts on adding ssh-keys, but thats locally, not in a ubuntu-release running from Github actions - what am i missing here? I cant generate ssh-keys and add the private key on the fly to the Github repo-settings, how can i fix this?

Body:
If you need to checkout two repositories I would recommend using checkout again to a relative path. See the documentation to checkout multiple repos side by side. You may need to use a repo scoped Personal Access Token (PAT)

  - name: 'Checkout'
    uses: actions/checkout@v2
  - name: 'Preparing blueprint-environment'
    uses: actions/checkout@v2
    with:
      token: ${{ secrets.PAT }}
      repository: ourcompany/whateverrepo
      path: whateverrepo

If it's really necessary, Deploy keys can be used to clone a repository via SSH.

Create a new SSH key pair for your repository. Do not set a passphrase.

Copy the contents of the public key (.pub file) to a new repository deploy key and check the box to "Allow write access."

Add a secret to the repository containing the entire contents of the private key.

As shown in the example below, configure actions/checkout to use the deploy key you have created.

    steps:
      - uses: actions/checkout@v2
        with:
          ssh-key: ${{ secrets.SSH_PRIVATE_KEY }}