问:
Specify which version of installed dependency to use with `install.packages`
Trying to install a package on HPC (where I cannot remove root packages) I get:

Error: package or namespace load failed for ‘plotly’ in
  loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]):
  namespace ‘rlang’ 0.3.1 is already loaded, but >= 0.4.0 is required

But I already have installed the latest version in my home and made it the first in the library search paths:

```<code>.libPaths()
[1] "/home/ajabadi/R_libs"
[2] "/usr/local/easybuild/software/R/3.5.0-GCC-6.2.0/lib64/R/library"

packageVersion("rlang", lib.loc=.libPaths()[1])
[1] ‘0.4.4.9000’

packageVersion("rlang", lib.loc=.libPaths()[2])
[1] ‘0.3.1’
</code>```

I was wondering how I can tell install.packages to first look at .libPaths()[1]. I tried R_LIBS_USER = "~/R_libs" in ~/.Renviron but no luck.

答:
For packages available on github (or gitlab accordingly) you can always do:

```<code>devtools::install_github("user/repo", dependencies = FALSE)
</code>```

And then load the more recent version of the dependency.

Body:
Trying to install a package on HPC (where I cannot remove root packages) I get:

Error: package or namespace load failed for ‘plotly’ in
  loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]):
  namespace ‘rlang’ 0.3.1 is already loaded, but >= 0.4.0 is required

But I already have installed the latest version in my home and made it the first in the library search paths:

.libPaths()
[1] "/home/ajabadi/R_libs"
[2] "/usr/local/easybuild/software/R/3.5.0-GCC-6.2.0/lib64/R/library"

packageVersion("rlang", lib.loc=.libPaths()[1])
[1] ‘0.4.4.9000’

packageVersion("rlang", lib.loc=.libPaths()[2])
[1] ‘0.3.1’

I was wondering how I can tell install.packages to first look at .libPaths()[1]. I tried R_LIBS_USER = "~/R_libs" in ~/.Renviron but no luck.

Body:
For packages available on github (or gitlab accordingly) you can always do:

devtools::install_github("user/repo", dependencies = FALSE)

And then load the more recent version of the dependency.


来源: stackexchange

问:
Xamarin.Forms Previewer "Connection is closed"
Just opened the Xamarin.Forms Previewer and it says "Something went wrong, Connection is closed"
Its a fresh Visual Studio 2017 install and a blank Xamarin Forms Project.

Here is a screenshot

Does anyone know how to solve this problem?

答:
Same here with VS 2019 - 16.4.5. Happens over and over again... very annoying. For me its enough to close and reopen the xaml file.

You also may have a look here: https://windowsreport.com/something-went-wrong-connection-closed-xamarin/. And here are some troubleshooting tips from Microsoft

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Remember Password alert for the site
In my website login page I can't get the alert "remember password for the site".I had already enabled remember password for the site from tools->options->security->"remember password for the site" but still it is not working . I am using mozilla 3.6 version</p>

答: It sounds like you're confusing browser settings and website settings. Having the browser remember your users password (at least the type you're referring to) is a setting specific to each browser and not something that your website can control.</p>

Title: Remember Password alert for the site


问:
My device id for AdMob Testing changed (Android)
I have set the device id of the phone I use for adMob testing as a const in my app. My testing device is not my day-to-day device.

Today I wanted to test a use case with a reward video and all of the sudden I get no fill or internal errors.

I took a look into the Log Cat and I saw that the device Id changed

By device Id I am referring to the one that comes in this log:

```<code>I/Ads: Use RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("THIS_ID_HERE") to get test ads on this device.
</code>```

Why does it changed?

Is it because I uninstalled the prod version and installed a dev version of my app?

Does it happens randomly?

Can I prevent this behavior?

答:
Device Id changes if you reset your phone. It may cause when you update your OS.
It does not change randomly.
Uninstalling prod version and installing a dev version should not change your device id(AFAIK).</p>

Body:
I have set the device id of the phone I use for adMob testing as a const in my app. My testing device is not my day-to-day device.

Today I wanted to test a use case with a reward video and all of the sudden I get no fill or internal errors.

I took a look into the Log Cat and I saw that the device Id changed

By device Id I am referring to the one that comes in this log:

I/Ads: Use RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("THIS_ID_HERE") to get test ads on this device.

Why does it changed?

Is it because I uninstalled the prod version and installed a dev version of my app?

Does it happens randomly?

Can I prevent this behavior?


问:
Javascript: How do I use React component globally?
I've made an NPM package for react, it's working fine on Node but it's not working on browser without node.

if I import within node like this:

```<code>import Progress from 'package-name'

// jsx
<Progress /> //working fine
</code>```

It's working fine.

But if I use it from CDN like unpkg, it's not working.

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>

// Package Script
<script src="https://unpkg.com/@delowar/react-circle-progressbar@0.0.9/lib/Progress.js"></script>

<script>
    ...react code...
    <Progress />
    ...react code...
</script>
</code>```

It's showing an error:

Progress is not defined

Can anyone please help me about this issue?

Webpack Configuration:

```<code>var path = require('path');

module.exports = {
    mode: 'production',
    entry: './src/Progress.js',
    output: {
        path: path.resolve('lib'),
        filename: 'Progress.js',
        libraryTarget: 'umd',
        library: 'lib',
        umdNamedDefine: true,
        globalObject: `(typeof self !== 'undefined' ? self : this)`
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /(node_modules)/,
                use: 'babel-loader'
            }
        ]
    }
}
</code>```

Original Repo: https://github.com/delowardev/react-circle-progressbar

答:
You should configure it as external dependency as described in the docs.

Add this to your webpack configuration:

```<code>externals : {
    Progress: 'progress'
}
</code>```

Usage:

import Progress from 'progress';

Body:
I've made an NPM package for react, it's working fine on Node but it's not working on browser without node.

if I import within node like this:

import Progress from 'package-name'

// jsx
<Progress /> //working fine

It's working fine.

But if I use it from CDN like unpkg, it's not working.

// Package Script

It's showing an error:

Progress is not defined

Can anyone please help me about this issue?

Webpack Configuration:

var path = require('path');

module.exports = {
    mode: 'production',
    entry: './src/Progress.js',
    output: {
        path: path.resolve('lib'),
        filename: 'Progress.js',
        libraryTarget: 'umd',
        library: 'lib',
        umdNamedDefine: true,
        globalObject: `(typeof self !== 'undefined' ? self : this)`
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /(node_modules)/,
                use: 'babel-loader'
            }
        ]
    }
}

Original Repo: https://github.com/delowardev/react-circle-progressbar

Body:
You should configure it as external dependency as described in the docs.

Add this to your webpack configuration:

externals : {
    Progress: 'progress'
}

Usage:

import Progress from 'progress';


问:
How to remove all extra spaces while keeping the lines
I need to remove white-spaces while keeping the lines

Before:

```<code>I brought           a            Banana
I sold                a Banana
I           brought a Apple
</code>```

After: NO WHITE SPACES or big space at the begining of the line

```<code>I brought a Banana
I sold a Banana
I brought a Apple
</code>```

All of the tutorials removes the white space but it didn't keep me the lines so it became all the words in one line:

I need to do this because after I use the .replace method in JavaScript, I get a bunch of white spaces but need to keep the lines so I can reorder the words.

答:
Simplest way

console.log(`I brought    a            Banana
I                   sold a Apple
I       sold a             Banana`.replace(/ +/g," "))```

Body:
I need to remove white-spaces while keeping the lines

Before:

I brought           a            Banana
I sold                a Banana
I           brought a Apple

After: NO WHITE SPACES or big space at the begining of the line

I brought a Banana
I sold a Banana
I brought a Apple

All of the tutorials removes the white space but it didn't keep me the lines so it became all the words in one line:

I need to do this because after I use the .replace method in JavaScript, I get a bunch of white spaces but need to keep the lines so I can reorder the words.


问:
Array Index Overload Bug
Why does this code result in the second element of the array being printed as 0, irrespective of the value that was specified in the definition of the integer array object?
The output of the code below is 7 0 3 4 5 6 instead of 7 2 3 4 5 6, what would be the reason for this behavior?</p>

```<code>// Overloading operators for Array class
#include<iostream>
#include<cstdlib>

using namespace std;

// A class to represent an integer array
class Array
{
private:
    int *ptr;
    int size;
public:
    Array(int *, int);

    // Overloading [] operator to access elements in array style
    int &operator[] (int);

    // Utility function to print contents
    void print() const;
};

// Implementation of [] operator.  This function must return a
// reference as array element can be put on left side
int &Array::operator[](int index)
{
    if (index >= size)
    {
        cout << "Array index out of bound, exiting";
        exit(0);
    }
    return ptr[index];
}

// constructor for array class
Array::Array(int *p = NULL, int s = 0)
{
    size = s;
    ptr = NULL;
    if (s != 0)
    {
        ptr = new int[s];
        for (int i = 0; i < s; i++)
            ptr[i] = p[i];
        delete ptr;
    }
}

void Array::print() const
{
    for(int i = 0; i < size; i++)
        cout<<ptr[i]<<" ";
    cout<<endl;
}

// Driver program to test above methods
int main()
{
    int a[] = {1, 2, 3, 4, 5, 6};
    Array arr1(a, 6);
    arr1[0] = 7;
    arr1.print();
    arr1[8] = 6;
    return 0;
}
</code>```

答:
Modified print function to exclude space after last array element.
Modified constructor method declaration to include initialized arguments.
Added additional const version of index[ ] operator overload but don't think it's properly implemented or if it would actually be utilized. </p>

```<code>#include<iostream>
#include<cstdlib>

// A class to represent an integer array
class Array{
private:
    int *ptr;
    std::size_t size;
public:
    Array(int *p = nullptr, std::size_t s = 0);
    Array(const Array&);
    ~Array();
    Array& operator= (Array);

    // Overloading [] operator to access elements in array style
    int &operator[] (std::size_t);

    int const& operator[](std::size_t) const;

    // Utility function to print contents
    void print() const;

    friend void swap(Array& first, Array& second);};

// Implementation of [] operator.  This function must return a
// reference as array element can be put on left side
int &Array::operator[](std::size_t index){
    puts("overload");
    if (index >= size || index < 0){
       throw std::out_of_range("Index out of Range error");
    }
    return ptr[index];
}

int const& Array::operator[](std::size_t index) const{
    puts("const overload");
    if (index >= size || index < 0){
        throw std::out_of_range("Index out of Range error");
    }
    return ptr[index];
}

// constructor for array class
Array::Array(int *p, std::size_t s){
    size = s;
    ptr = nullptr;
    if (s != 0){
        ptr = new int[s];
        for (int i = 0; i < s; i++){
            ptr[i] = p[i];}
    }
}

// destructor for array class
Array::~Array(){
    delete[] ptr;
    ptr = nullptr;}

// copy constructor for array class
Array::Array(const Array& A) {
    size = A.size;
    ptr  = new int[size];
    for (int i = 0; i < size; i++){
        ptr[i] = A.ptr[i];}
}
//swap friend function of assignment operator
void swap(Array& first, Array& second){
    using std::swap;
    swap(first.size, second.size);
    swap(first.ptr, second.ptr);}

//Assignment operator for array class
Array& Array::operator=(Array other){
    swap(*this, other);
    return *this;}

//print function for array elements
void Array::print() const{
    std::cout << "{";
    for(int i = 0; i < size; i++){
        std::cout << ptr[i];
        if (i == size-1){
            continue;}
        std::cout<<" ";
       }
    std::cout<<"}"<< std::endl;}

// Driver program to test above methods
int main()
{
    int a[] = {1, 2, 3, 4, 5, 6};
    Array arr1(a, 6);
    std::cout << arr1[3] << '\n';
    arr1[4] = 7;
    arr1.print();
    Array arr2 = arr1;
    arr2.print();
    arr1[-1] = 4;
    return 0;
}

</code>```

Title: Array Index Overload Bug

Body:
Why does this code result in the second element of the array being printed as 0, irrespective of the value that was specified in the definition of the integer array object?
The output of the code below is 7 0 3 4 5 6 instead of 7 2 3 4 5 6, what would be the reason for this behavior?

// Overloading operators for Array class
#include<iostream>
#include<cstdlib>

using namespace std;

// A class to represent an integer array
class Array
{
private:
    int *ptr;
    int size;
public:
    Array(int *, int);

    // Overloading [] operator to access elements in array style
    int &operator[] (int);

    // Utility function to print contents
    void print() const;
};

// Implementation of [] operator.  This function must return a
// reference as array element can be put on left side
int &Array::operator[](int index)
{
    if (index >= size)
    {
        cout << "Array index out of bound, exiting";
        exit(0);
    }
    return ptr[index];
}

// constructor for array class
Array::Array(int *p = NULL, int s = 0)
{
    size = s;
    ptr = NULL;
    if (s != 0)
    {
        ptr = new int[s];
        for (int i = 0; i < s; i++)
            ptr[i] = p[i];
        delete ptr;
    }
}

void Array::print() const
{
    for(int i = 0; i < size; i++)
        cout<<ptr[i]<<" ";
    cout<<endl;
}

// Driver program to test above methods
int main()
{
    int a[] = {1, 2, 3, 4, 5, 6};
    Array arr1(a, 6);
    arr1[0] = 7;
    arr1.print();
    arr1[8] = 6;
    return 0;
}

Body:
Modified print function to exclude space after last array element.
Modified constructor method declaration to include initialized arguments.
Added additional const version of index[ ] operator overload but don't think it's properly implemented or if it would actually be utilized.

#include<iostream>
#include<cstdlib>

// A class to represent an integer array
class Array{
private:
    int *ptr;
    std::size_t size;
public:
    Array(int *p = nullptr, std::size_t s = 0);
    Array(const Array&);
    ~Array();
    Array& operator= (Array);

    // Overloading [] operator to access elements in array style
    int &operator[] (std::size_t);

    int const& operator[](std::size_t) const;

    // Utility function to print contents
    void print() const;

    friend void swap(Array& first, Array& second);};

// Implementation of [] operator.  This function must return a
// reference as array element can be put on left side
int &Array::operator[](std::size_t index){
    puts("overload");
    if (index >= size || index < 0){
       throw std::out_of_range("Index out of Range error");
    }
    return ptr[index];
}

int const& Array::operator[](std::size_t index) const{
    puts("const overload");
    if (index >= size || index < 0){
        throw std::out_of_range("Index out of Range error");
    }
    return ptr[index];
}

// constructor for array class
Array::Array(int *p, std::size_t s){
    size = s;
    ptr = nullptr;
    if (s != 0){
        ptr = new int[s];
        for (int i = 0; i < s; i++){
            ptr[i] = p[i];}
    }
}

// destructor for array class
Array::~Array(){
    delete[] ptr;
    ptr = nullptr;}

// copy constructor for array class
Array::Array(const Array& A) {
    size = A.size;
    ptr  = new int[size];
    for (int i = 0; i < size; i++){
        ptr[i] = A.ptr[i];}
}
//swap friend function of assignment operator
void swap(Array& first, Array& second){
    using std::swap;
    swap(first.size, second.size);
    swap(first.ptr, second.ptr);}

//Assignment operator for array class
Array& Array::operator=(Array other){
    swap(*this, other);
    return *this;}

//print function for array elements
void Array::print() const{
    std::cout << "{";
    for(int i = 0; i < size; i++){
        std::cout << ptr[i];
        if (i == size-1){
            continue;}
        std::cout<<" ";
       }
    std::cout<<"}"<< std::endl;}

// Driver program to test above methods
int main()
{
    int a[] = {1, 2, 3, 4, 5, 6};
    Array arr1(a, 6);
    std::cout << arr1[3] << '\n';
    arr1[4] = 7;
    arr1.print();
    Array arr2 = arr1;
    arr2.print();
    arr1[-1] = 4;
    return 0;
}


问:
typescript custom component function param throwing warning
I have this piece of code

```<code><GoogleLogin
  onSuccess={responseGoogle => {
    const { email, name } = responseGoogle.profileObj; // error: Property 'profileObj' does not exist on type 'GoogleLoginResponse | GoogleLoginResponseOffline'.
  }}
/>
</code>```

The library is here https://www.npmjs.com/package/react-google-login

What should I do? I tried (responseGoogle:any) it doesn't work.

答:
You have to specify the login response type. It can either be GoogleLoginResponseOffline or GoogleLoginResponse. The property profileObj exists only in GoogleLoginResponse. If you are requesting offline access, the response will only have a code in the response and you should use GoogleLoginResponseOffline type.

```<code><GoogleLogin
        onSuccess={(responseGoogle: GoogleLoginResponse) => {
          const { email, name } = responseGoogle.profileObj;

        }}
      />
</code>```

Body:
I have this piece of code

<GoogleLogin
  onSuccess={responseGoogle => {
    const { email, name } = responseGoogle.profileObj; // error: Property 'profileObj' does not exist on type 'GoogleLoginResponse | GoogleLoginResponseOffline'.
  }}
/>

The library is here https://www.npmjs.com/package/react-google-login

What should I do? I tried (responseGoogle:any) it doesn't work.

Body:
You have to specify the login response type. It can either be GoogleLoginResponseOffline or GoogleLoginResponse. The property profileObj exists only in GoogleLoginResponse. If you are requesting offline access, the response will only have a code in the response and you should use GoogleLoginResponseOffline type.

<GoogleLogin
        onSuccess={(responseGoogle: GoogleLoginResponse) => {
          const { email, name } = responseGoogle.profileObj;

        }}
      />


问:
Unable to use await in an if function
I am writing an application command so members of my server can apply for staff. I am trying to use my friends handler which provides an prompt function. I use await to make sure the question after doesn't execute before the one before it is resolved, but I am unable to use await within the if statement that I have.

I am getting an error Unexpected error: unexpected token call which obviously means something is extra or not supposed to be there.

How would I use await in this case to make sure the next prompt doesn't execute before its supposed to?
Or if that is not possible, any suggestions would be great.

const Discord = require('discord.js');
module.exports = {
    id: 'newapply',
    aliases: ['betaapply'],
    channels: 'any',
    exec: async (call) => {
        try {
        let database = call.client.staffapps
        let applicationApprovalChannel = call.client.channels.get('677649993968123947');
        // Question answer declarations.
        let question1Answer;
        let question2Answer;
        let question3Answer;
        let positionChoice;
        let question5Answer;
        let question6Answer;
        let question7Answer;
        let question8Answer;
        let question9Answer;
        let question10Answer;

        //Questions
        const question1String = `**Question 1:** How old are you?`
        const question2String = `**Question 2:** What timezone do you reside in?`
        const question3String = `**Question 3:** What do you think you bring to the staff team?`
        const question4String = `**Question 4:** Which position are you applying for? \n*Valid Reponses Are: community agent, moderator*`
        const question5CommunityString = `**Question 5C:** How friendly are you on a daily basis?`
        const question6CommunityString = `**Question 6C:** How do you handle stressful situations?`
        const question7CommunityString = `**Question 7C:** How many activities would you be able to arrange for our community?`
        const question8CommunityString = `**Question 8C:** Are you generally a toxic person?`
        const question9CommunityString = `**Question 9C:** Why do you think your a good choice to represent our server?`
        const question10CommunityString = `**Question 10C:** How active do you think you are on a scale of 1-10?`
        const question5ModString = `**Question 5M:** How would you handle rule enforcement in the server?`
        const question6ModString = `**Question 6M:** If your best friend commited a violation of the server rules, would you show bias towards the actions you take on them?`
        const question7ModString = `**Question 7M:** How do you handle stressful situations?`
        const question8ModString = `**Question 8M:** How would you use command sense to pick right from wrong?`
        //place seperator here
        const question9ModSituational = `**Question 9MS:** Edward just posted porn in chat, and his friend Anne is encouraging other people to do the same. How would you react in this situation?`
        const question10ModSituational = `**Question 10MS:** Edward and thetechguy61705 are fighting in chat and its filling up the entire chat. What would be the actions you would take to handle this situation?`
        const question11ModSituational = `**Question 11MS:** DudeCord is claiming that Cudiiz sent a malicious link in DMs. What should you do in this situation?`
        const question12ModSituational = `**Question 12MS:** Two staff members are fighting. How should you react? What actions should you take?`

        const usersDMs = await call.message.author.createDM();

        call.message.channel.send(`Welcome to the LinkCord staff application! The application will now continue in your DMs. Please make sure they are open for me to DM.`)

        //Inital Prompt;;

           //Legal agreement prompt;;

           if (await call.prompt(`Before we begin, please read and accept the following agreement. \nI, **${call.message.author.tag}**, agree that filling out this application in no way, will grant me a position at LinkCord or any of its affiliate(s) unless I am accepted as a member of the staff by a verified member of Administration. \nI, **${call.message.author.tag}** also agree that the decision of the status of your application is **final** and cannot be changed unless proof of unfair judgement is provided. \n\nDo you agree to these terms?`, { time: 45000, channel: usersDMs, filter: ['yes', 'no']}).then((m) => m.content.toLowerCase() === 'no')) {
            return call.message.author.send(`:x: Your application was denied by ${call.client.user.tag} for reason __Didn't accept the legal agreement__`);
          }
        //End Legal Agreement prompt;;

        // Question 1
         await call.prompt(question1String, { time: 30000, channel: usersDMs}).then(question1Msg => {
          question1Answer = question1Msg.content;
        });
        //Question 1 end;

        //question 2;;
         await call.prompt(question2String, { time: 30000, channel: usersDMs}).then(question2Msg => {
          question2Answer = question2Msg.content;
        });
        //question 2 end;;

        //question 3 begin;
        await call.prompt(question3String, { time: 30000, channel: usersDMs}).then(question3Msg => {
            question3Answer = question3Msg.content;
        });
        //question 3 end

        //question 4 begin;

        await call.prompt(question4String, { time: 45000, channel: usersDMs, filter: ['community agent', 'moderator'] }).then(positionInput => {
          if(positionInput.content.toLowerCase() === 'community agent') {

            call.prompt(question5CommunityString, { time: 50000, channel: usersDMs}).then(question5CMsg => {
              question5Answer = question5CMsg.content;
             });
              call.prompt(question6CommunityString, { time: 50000, channel: usersDMs }).then(question6CMsg => {
               question5Answer = question6CMsg.content;
             })
          }
          if(positionInput.content.toLowerCase() === 'moderator') {
            positionChoice = positionInput.content;
            call.messge.author.send('moderators')
          }

        })

        } catch(error) {
            call.message.channel.send(`Oops! That was an error! The issue has been reported to the adminstration team`);
            console.log(error);
        }
    }
};
```

答:
Your issue starts with question 4. You are trying to run code without waiting for the return.

```<code>if (positionInput.content.toLowerCase() === 'community agent') {
    // Won't wait
    call.prompt(question5CommunityString, {
        time: 50000,
        channel: usersDMs
    }).then(question5CMsg => {
        question5Answer = question5CMsg.content; // Won't run we likely already left the scope without waiting for the return
    });

    // Won't wait
    call.prompt(question6CommunityString, {
        time: 50000,
        channel: usersDMs
    }).then(question6CMsg => {
        question5Answer = question6CMsg.content; // Won't run we likely already left the scope without waiting for the return
    });
}

// This will likely run before the code above completes and will send the moderators.
if (positionInput.content.toLowerCase() === 'moderator') {
    positionChoice = positionInput.content;
    call.messge.author.send('moderators')
}
</code>```

Try pulling the code outside of the then statement in the question 4 otherwise you need to chain the promises one after another.

```<code>// Put this somewhere safe up top
let question4Response;

// Your new code:

    then(positionInput => {
        question4Response = positionInput;
    });
}

if (question4Response.content.toLowerCase() === 'community agent') {
    await call.prompt(question5CommunityString, {
        time: 50000,
        channel: usersDMs
    }).then(question5CMsg => {
        question5Answer = question5CMsg.content;
    });

    await call.prompt(question6CommunityString, {
        time: 50000,
        channel: usersDMs
    }).then(question6CMsg => {
        question6Answer = question6CMsg.content;
    })
}
else if (question4Response.content.toLowerCase() === 'moderator') {
    positionChoice = question4Response.content;

    call.messge.author.send('moderators')
}
</code>```

Title: Unable to use await in an if function

Body:
Your issue starts with question 4. You are trying to run code without waiting for the return.

if (positionInput.content.toLowerCase() === 'community agent') {
    // Won't wait
    call.prompt(question5CommunityString, {
        time: 50000,
        channel: usersDMs
    }).then(question5CMsg => {
        question5Answer = question5CMsg.content; // Won't run we likely already left the scope without waiting for the return
    });

    // Won't wait
    call.prompt(question6CommunityString, {
        time: 50000,
        channel: usersDMs
    }).then(question6CMsg => {
        question5Answer = question6CMsg.content; // Won't run we likely already left the scope without waiting for the return
    });
}

// This will likely run before the code above completes and will send the moderators.
if (positionInput.content.toLowerCase() === 'moderator') {
    positionChoice = positionInput.content;
    call.messge.author.send('moderators')
}

Try pulling the code outside of the then statement in the question 4 otherwise you need to chain the promises one after another.

// Put this somewhere safe up top
let question4Response;

// Your new code:

    then(positionInput => {
        question4Response = positionInput;
    });
}

if (question4Response.content.toLowerCase() === 'community agent') {
    await call.prompt(question5CommunityString, {
        time: 50000,
        channel: usersDMs
    }).then(question5CMsg => {
        question5Answer = question5CMsg.content;
    });

    await call.prompt(question6CommunityString, {
        time: 50000,
        channel: usersDMs
    }).then(question6CMsg => {
        question6Answer = question6CMsg.content;
    })
}
else if (question4Response.content.toLowerCase() === 'moderator') {
    positionChoice = question4Response.content;

    call.messge.author.send('moderators')
}


问:
Python. Best way to filter array by date
I have a list of Rest objects. It's django model

```<code>class Rest(models.Model):
   product = models.ForeignKey('Product', models.DO_NOTHING)
   date = models.DateTimeField()
   rest = models.FloatField()
</code>```

I want to select objects from it for today's date. I do it like this. Maybe there is some more convenient and compact way?

```<code>    for rest in rests_list:
      if rest.date.day == datetime.now().day:
         result.append(rest)
</code>```

答:
First - datetime.now().day will get you the day of the month (e.g. 18 if today is 18th March 2020), but you've said you want today's date. The below is on the assumption you want today's date, not the day of the month.

(NOTE: weAreStarDust pointed out that the field is a DateTimeField, not a DateField, which I missed and have updated the answer for)

The way you are doing it right now seems like it might be fetching all of the Rests from the database and then filter them in your application code (assuming rests_listcomes from something likeRest.objects.all()`. Generally, you want to do as much filtering as possible on the database query itself, and as little filtering as possible in the client code.

In this case, what you probably want to do is:

```<code>from datetime import date
Rest.objects.filter(date__date=date.today())
</code>```

That will bring back only the records that have a date of today, which are the ones you want.

If you already have all the rests somehow, and you just want to filter to the ones from today then you can use:

```<code>filter(lambda x: x.date.date() == date.today(), rests_list)
</code>```

That will return a filter object containing only the items in rests_list that have date == date.today(). If you want it as a list, rather than an iterable, you can do:

```<code>list(filter(lambda x: x.date.date() == date.today(), rests_list))
</code>```

or for a tuple:

```<code>tuple(filter(lambda x: x.date.date() == date.today(), rests_list))
</code>```

NOTE:
If you actually want to be storing only a date, I would suggest considering use of a DateField (although not if you want to store any timezone information).
If you want to store a DateTime, I would consider renaming the field from date to datetime, or started_at - calling the field date but having a datetime can be a bit confusing and lead to errors.

Body:
I have a list of Rest objects. It's django model

class Rest(models.Model):
   product = models.ForeignKey('Product', models.DO_NOTHING)
   date = models.DateTimeField()
   rest = models.FloatField()

I want to select objects from it for today's date. I do it like this. Maybe there is some more convenient and compact way?

    for rest in rests_list:
      if rest.date.day == datetime.now().day:
         result.append(rest)

Body:
First - datetime.now().day will get you the day of the month (e.g. 18 if today is 18th March 2020), but you've said you want today's date. The below is on the assumption you want today's date, not the day of the month.

(NOTE: weAreStarDust pointed out that the field is a DateTimeField, not a DateField, which I missed and have updated the answer for)

The way you are doing it right now seems like it might be fetching all of the Rests from the database and then filter them in your application code (assuming rests_listcomes from something likeRest.objects.all()`. Generally, you want to do as much filtering as possible on the database query itself, and as little filtering as possible in the client code.

In this case, what you probably want to do is:

from datetime import date
Rest.objects.filter(date__date=date.today())

That will bring back only the records that have a date of today, which are the ones you want.

If you already have all the rests somehow, and you just want to filter to the ones from today then you can use:

filter(lambda x: x.date.date() == date.today(), rests_list)

That will return a filter object containing only the items in rests_list that have date == date.today(). If you want it as a list, rather than an iterable, you can do:

list(filter(lambda x: x.date.date() == date.today(), rests_list))

or for a tuple:

tuple(filter(lambda x: x.date.date() == date.today(), rests_list))

NOTE:
If you actually want to be storing only a date, I would suggest considering use of a DateField (although not if you want to store any timezone information).
If you want to store a DateTime, I would consider renaming the field from date to datetime, or started_at - calling the field date but having a datetime can be a bit confusing and lead to errors.


问:
Is there no way to access the asp.net Response.Headers in IIS6?
When I try to access Request.Headers I get a "This operation requires IIS integrated pipeline mode." error.

Is there really no way to view the response headers in .net with IIS6?

答: Yes, there really is no way to read the headers in IIS6.  You can only add them using .AddHeader() or clear them using .ClearHeaders()

ContentLicense: CC BY-SA 2.5


问:
CSS Responsive image "shows up fully" on-screen no-stretch background with precise text placement

Testing

```

I'm trying to have an image fully show up based on the size of a screen, and to have text ("Testing" in the textbox class) show up in a precise designated area in the image, as shown above.

Trying to get the above to work with this codepen, but I am defeated to admit that after an hour of fiddling with css, I am nowhere close.

It is pretty frustrating that css doesn't seem to work as expected, where the image doesn't seem to want to nest to full height etc.

答:
Normally, if you call the image in background means need to add the padding-bottom in percentage.. It means the image height/width*100

css

```<code>.fullscreen {
 padding-bottom: 129.411%;
}
</code>```

Body:
Testing

I'm trying to have an image fully show up based on the size of a screen, and to have text ("Testing" in the textbox class) show up in a precise designated area in the image, as shown above.

Trying to get the above to work with this codepen, but I am defeated to admit that after an hour of fiddling with css, I am nowhere close.

It is pretty frustrating that css doesn't seem to work as expected, where the image doesn't seem to want to nest to full height etc.

Body:
Normally, if you call the image in background means need to add the padding-bottom in percentage.. It means the image height/width*100

css

.fullscreen {
 padding-bottom: 129.411%;
}


问:
Curator_cli V5.8 Disable logging?
Can anyone help me to disable logging for curator_cli.
For Example , I have tried the command
Command :

curator_cli  --host localhost show_indices  --filter_list '[{"filtertype":"age","source":"creation_date","direction":"younger","unit":"minutes","unit_count":60,"timestring":"%Y.%m.%d"}]'

Output :
2020-02-17 18:44:50,286 INFO      Instantiating client object
2020-02-17 18:44:50,287 INFO      Testing client connectivity
2020-02-17 18:44:50,290 INFO      Successfully created Elasticsearch client object with provided settings
logstash-2020.02.17

So ,I only want logstash-2020.02.17 as output

答: curator_cli was designed to log to stdout if no log file is specified. You could set --logfile /dev/null or even an actual file to get the desired result. It might even work to set --loglevel CRITICAL or FATAL to shut off the default INFO log level.

Title: Curator_cli V5.8 Disable logging?


问:
Fastest option for reading the data for pandas from S3 bucket?
I am having a dataset of around 400 mb in CSV, In my local i tried several data formats to achieve the fastest reading time. The parquet format partitioned on date turned out to be the best fit.
But when i shifted to S3 bucket, it took so long to read same file using aws data wrangler.

Being new to AWS world i need to know what should be the best method to achieve the fastest running time.
Given :

I have date as one of feature and I can use it to partitioning. Also I need it as a pandas dataframe after reading it .

答:
There is a format called feather, it might help you out.

More details here - link


问:
How to add a top alert banner on Docusaurus 1.x?
I want to show some global message on my Docusaurus site. Something like:

https://codesandbox.io/s/duudl

https://next.ant.design/components/alert/

Is this possible?

答:
You will have to inject the DOM via scripts. An example is React Native website where they injected feedback banners at the bottom of the page - https://facebook.github.io/react-native/docs/getting-started

Look at their repo and the script they used.


问:
Create a Dictionary<int, List<int>> from a Linq query
I have a table in database as follows...

```<code>ID(INT)    Values(VARCHAR(50))
1          200,300
2          100
3          400,500
</code>```

when I query, I need to get this data in a Dictionary>

The code I have so far is...

var x = (from o in Values
         select o).ToDictionary(o=>o.ID, p=>p.Values)

I would like the p.Values to be converted to a List so I also need to perform a Convert.ToInt32() possibly!

Any ideas?

答:
This should work:

```<code>var x =
(from o in Values select o)
.ToDictionary(o => o.ID,
              p => p.Values.Split(',')
                    .Select(x => Convert.ToInt32(x))
                    .ToList());
</code>```

.Select(x => Convert.ToInt32(x)) can be converted to a method group like this ;-) .Select(Convert.ToInt32)

Body:
I have a table in database as follows...

ID(INT)    Values(VARCHAR(50))
1          200,300
2          100
3          400,500

when I query, I need to get this data in a Dictionary>

The code I have so far is...

var x = (from o in Values
         select o).ToDictionary(o=>o.ID, p=>p.Values)

I would like the p.Values to be converted to a List so I also need to perform a Convert.ToInt32() possibly!

Any ideas?

Body:
This should work:

var x =
(from o in Values select o)
.ToDictionary(o => o.ID,
              p => p.Values.Split(',')
                    .Select(x => Convert.ToInt32(x))
                    .ToList());

.Select(x => Convert.ToInt32(x)) can be converted to a method group like this ;-) .Select(Convert.ToInt32)


问:
Cannot Save Data
I was to Try to save any Invoice Card on Database but it not saved

What's Wrong With my code, I was Try to search to solve this but it not solved

Always Blank to database,

The View Form & Post

The Controller

Use Boostrap 3 from AdminLte Template

```<code><?php

namespace App\Http\Controllers;

use App\Kwitansi;
use Illuminate\Http\Request;
use Haruncpi\LaravelIdGenerator\IdGenerator;

class KwitansiController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $kwitansi = Kwitansi::get();
        return view('user.formkwitansi', ['kwitansi' => $kwitansi]);
    }

    public function store(Request $request)
    {
        $kwitansi = new Kwitansi;

        $id = IdGenerator::generate(['table' => 'kwitansis', 'length' => 10, 'prefix' =>'PM-INV-']);
        $kwitansi->received = $request->received;
        $kwitansi->registration = $request->registration;
        $kwitansi->course = $request->course;
        $kwitansi->trasnportation = $request->trasnportation;
        $kwitansi->payment = $request->payment;
        $kwitansi->kota = $request->kota;
        $kwitansi->register_at = $request->register_at;

      $request->validate([
        'sum_rp' => 'required',
        'sum_text' => 'required',
      ]);

      $sum_rp = $request->registration + $request->course + $request->transportation;

      function penyebut($nilai) {
        $nilai = abs($nilai);
        $huruf = array("", "satu", "dua", "tiga", "empat", "lima", "enam", "tujuh", "delapan", "sembilan", "sepuluh", "sebelas");
        $temp = "";
        if ($nilai < 12) {
            $temp = " ". $huruf[$nilai];
        } else if ($nilai <20) {
            $temp = penyebut($nilai - 10). " belas";
        } else if ($nilai < 100) {
            $temp = penyebut($nilai/10)." puluh". penyebut($nilai % 10);
        } else if ($nilai < 200) {
            $temp = " seratus" . penyebut($nilai - 100);
        } else if ($nilai < 1000) {
            $temp = penyebut($nilai/100) . " ratus" . penyebut($nilai % 100);
        } else if ($nilai < 2000) {
            $temp = " seribu" . penyebut($nilai - 1000);
        } else if ($nilai < 1000000) {
            $temp = penyebut($nilai/1000) . " ribu" . penyebut($nilai % 1000);
        } else if ($nilai < 1000000000) {
            $temp = penyebut($nilai/1000000) . " juta" . penyebut($nilai % 1000000);
        } else if ($nilai < 1000000000000) {
            $temp = penyebut($nilai/1000000000) . " milyar" . penyebut(fmod($nilai,1000000000));
        } else if ($nilai < 1000000000000000) {
            $temp = penyebut($nilai/1000000000000) . " trilyun" . penyebut(fmod($nilai,1000000000000));
        }
        return $temp;
    }
    function terbilang($nilai) {
        if($nilai<0) {
            $hasil = "minus ". trim(penyebut($nilai));
        } else {
            $hasil = trim(penyebut($nilai));
        }
        return $hasil;
    }
    $sum_text = $request->sum_rp;

    $kwitansi->sum_rp = $sum_rp;
    $kwitansi->sum_text = terbilang($sum_text);

    $kwitansi->save();

    return redirect('kwitansi')->withSuccess('Added Succesfully');
    }
}
</code>```

The Blade View

Use Form and View in One Page

```<code>@extends('layouts.admin')

@section('title', 'Kwitansi')

@section('css')

<!-- DataTables -->
<link rel="stylesheet" href="{{ asset('adminlte/plugins/datatables-bs4/css/dataTables.bootstrap4.css') }}">
@section('js')
<!-- DataTables -->
<script src="{{ asset('adminlte/plugins/datatables/jquery.dataTables.js') }}"></script>
<script src="{{ asset('adminlte/plugins/datatables-bs4/js/dataTables.bootstrap4.js') }}"></script>
<script>
  $(function () {
    $("#example1").DataTable();
    $('#example2').DataTable({
      "paging": true,
      "lengthChange": false,
      "searching": false,
      "ordering": true,
      "info": true,
      "autoWidth": false,
    });
  });
</script>

@endsection

@section('content')

    <div class="row">
        <div class="col-12">
          <div class="card">
            <div class="card-header">
              <h3 class="card-title">DataTable User</h3>
              @if ($message = Session::get('success'))
              <div class="alert alert-success alert-dismissible">
                  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                  <h5><i class="icon fas fa-check"></i> Alert!</h5>
                  <p>{{ $message }}</p>
              </div>
              @endif
            </div>
            <!-- /.card-header -->
            <div class="card-body">
                <form action="{{ route('kwitansi.store') }}" method="POST" role="form" class="form-horizontal">
                    @csrf
                    <div class="form-group row">
                        <label for="name" class="control-label col-md-2">Terima Dari</label>
                        <div class="col-md-6">
                            <input type="text" name="received" class="form-control" placeholder="Received Form" />
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="registration" class="control-label col-md-2">Biaya Registrasi</label>
                        <div class="col-md-6">
                            <input type="text" name="registration" class="form-control" placeholder="Registration Fee" />
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="course" class="control-label col-md-2">Biaya Kursus</label>
                        <div class="col-md-6">
                            <input type="text" name="course" class="form-control" placeholder="Course Fee" />
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="trasnportation" class="control-label col-md-2">Biaya Transportasi</label>
                        <div class="col-md-6">
                            <input type="text" name="trasnportation" class="form-control" placeholder="Transportation Fee" />
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="payment" class="control-label col-md-2">Pembayaran Untuk</label>
                        <div class="col-md-6">
                            <input type="text" name="payment" class="form-control" placeholder="Payment Of" />
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="register_at" class="control-label col-md-2">Tanggal Registrasi</label>
                        <div class="col-md-6">
                            <input type="text" name="kota"class="form-control" value="Bandung" disabled hidden>
                            <input type="date" name="register_at"class="form-control">
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary" id="btnsubmit">Tambah Data</button>
                    <button type="reset" class="btn btn-warning" id="btncancel">Cancel</button>
                </form>
              <table id="example2" class="table table-bordered table-hover">
                <thead>
                <tr>
                  <th>No.</th>
                  <th>received</th>
                  <th>registration Fee</th>
                  <th>Course Fee</th>
                  <th>Transportation Fee</th>
                  <th>Grand Total</th>
                  <th>Payment of</th>
                  <th>Action</th>
                </tr>
                </thead>
                <tbody>
                @foreach($kwitansi as $k)
                <tr>
                  <td>{{ $k->id }}</td>
                  <td>{{ $k->received }}</td>
                  <td>{{ $k->registration }}</td>
                  <td>{{ $k->course }}</td>
                  <td>{{ $k->transportation }}</td>
                  <td>{{ $k->sum_rp }}</td>
                  <td>{{ $k->payment }}</td>
                  <td>
                    {{-- <a href="{{ route('user.edit', $u->id)}}" class="btn btn-sm btn-outline-warning"><i class="fas fa-edit"></i></a>
                    <a href="{{ route('user.show', $u->id)}}" class="btn btn-sm btn-outline-info"><i class="fas fa-file"></i></a>
                    <form action="{{ route('user.destroy', $u->id)}}" method="post">
                          @csrf
                          @method('DELETE')
                          <button class="btn btn-sm btn-outline-danger" type="submit"><i class="fas fa-trash-alt"></i></button>
                        </form> --}}
                  </td>
                </tr>
                @endforeach
                </tbody>
                <tfoot>
                <tr>
                    <th>No.</th>
                    <th>received</th>
                    <th>registration Fee</th>
                    <th>Course Fee</th>
                    <th>Transportation Fee</th>
                    <th>Grand Total</th>
                    <th>Payment of</th>
                    <th>Action</th>
                </tr>
                </tfoot>
              </table>
            </div>
            <!-- /.card-body -->
          </div>
          <!-- /.card -->
        </div>
        <!-- /.col -->
      </div>
      <!-- /.row -->

@endsection
</code>```

I used form and view in one page are this is the problem

This is my model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Kwitansi extends Model
{
    // $id = IdGenerator::generate(['table' => 'kwitansis', 'length' => 10, 'prefix' =>'PM-INV-']);
    protected $table = 'kwitansis';
    protected $fillable = [
        'received',
        'registration',
        'course',
        'trasnportation',
        'sum_rp',
        'payment',
        'register_at',
    ];
    protected $primarykey = 'id';

    public $increment = false;

    protected $keyType = 'string';
}

```

答:
Ok Thanks Guys For Helping, I Have Solved The Problem.

I Only Delete Some function on Controller adn Worked for Me

```<code>$request->validate([
        'sum_rp' => 'required',
        'sum_text' => 'required',
      ]);

      $sum_rp = $request->registration + $request->course + $request->transportation;

      function penyebut($nilai) {
        $nilai = abs($nilai);
        $huruf = array("", "satu", "dua", "tiga", "empat", "lima", "enam", "tujuh", "delapan", "sembilan", "sepuluh", "sebelas");
        $temp = "";
        if ($nilai < 12) {
            $temp = " ". $huruf[$nilai];
        } else if ($nilai <20) {
            $temp = penyebut($nilai - 10). " belas";
        } else if ($nilai < 100) {
            $temp = penyebut($nilai/10)." puluh". penyebut($nilai % 10);
        } else if ($nilai < 200) {
            $temp = " seratus" . penyebut($nilai - 100);
        } else if ($nilai < 1000) {
            $temp = penyebut($nilai/100) . " ratus" . penyebut($nilai % 100);
        } else if ($nilai < 2000) {
            $temp = " seribu" . penyebut($nilai - 1000);
        } else if ($nilai < 1000000) {
            $temp = penyebut($nilai/1000) . " ribu" . penyebut($nilai % 1000);
        } else if ($nilai < 1000000000) {
            $temp = penyebut($nilai/1000000) . " juta" . penyebut($nilai % 1000000);
        } else if ($nilai < 1000000000000) {
            $temp = penyebut($nilai/1000000000) . " milyar" . penyebut(fmod($nilai,1000000000));
        } else if ($nilai < 1000000000000000) {
            $temp = penyebut($nilai/1000000000000) . " trilyun" . penyebut(fmod($nilai,1000000000000));
        }
        return $temp;
    }
    function terbilang($nilai) {
        if($nilai<0) {
            $hasil = "minus ". trim(penyebut($nilai));
        } else {
            $hasil = trim(penyebut($nilai));
        }
        return $hasil;
    }
    $sum_text = $request->sum_rp;

    $kwitansi->sum_rp = $sum_rp;
    $kwitansi->sum_text = terbilang($sum_text);

</code>```

Only Delete This function and add it to Helper Class

Title: Cannot Save Data

Body:
I was to Try to save any Invoice Card on Database but it not saved

What's Wrong With my code, I was Try to search to solve this but it not solved

Always Blank to database,

The View Form & Post

The Controller

Use Boostrap 3 from AdminLte Template

<?php

namespace App\Http\Controllers;

use App\Kwitansi;
use Illuminate\Http\Request;
use Haruncpi\LaravelIdGenerator\IdGenerator;

class KwitansiController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $kwitansi = Kwitansi::get();
        return view('user.formkwitansi', ['kwitansi' => $kwitansi]);
    }

    public function store(Request $request)
    {
        $kwitansi = new Kwitansi;

        $id = IdGenerator::generate(['table' => 'kwitansis', 'length' => 10, 'prefix' =>'PM-INV-']);
        $kwitansi->received = $request->received;
        $kwitansi->registration = $request->registration;
        $kwitansi->course = $request->course;
        $kwitansi->trasnportation = $request->trasnportation;
        $kwitansi->payment = $request->payment;
        $kwitansi->kota = $request->kota;
        $kwitansi->register_at = $request->register_at;

      $request->validate([
        'sum_rp' => 'required',
        'sum_text' => 'required',
      ]);

      $sum_rp = $request->registration + $request->course + $request->transportation;

      function penyebut($nilai) {
        $nilai = abs($nilai);
        $huruf = array("", "satu", "dua", "tiga", "empat", "lima", "enam", "tujuh", "delapan", "sembilan", "sepuluh", "sebelas");
        $temp = "";
        if ($nilai < 12) {
            $temp = " ". $huruf[$nilai];
        } else if ($nilai <20) {
            $temp = penyebut($nilai - 10). " belas";
        } else if ($nilai < 100) {
            $temp = penyebut($nilai/10)." puluh". penyebut($nilai % 10);
        } else if ($nilai < 200) {
            $temp = " seratus" . penyebut($nilai - 100);
        } else if ($nilai < 1000) {
            $temp = penyebut($nilai/100) . " ratus" . penyebut($nilai % 100);
        } else if ($nilai < 2000) {
            $temp = " seribu" . penyebut($nilai - 1000);
        } else if ($nilai < 1000000) {
            $temp = penyebut($nilai/1000) . " ribu" . penyebut($nilai % 1000);
        } else if ($nilai < 1000000000) {
            $temp = penyebut($nilai/1000000) . " juta" . penyebut($nilai % 1000000);
        } else if ($nilai < 1000000000000) {
            $temp = penyebut($nilai/1000000000) . " milyar" . penyebut(fmod($nilai,1000000000));
        } else if ($nilai < 1000000000000000) {
            $temp = penyebut($nilai/1000000000000) . " trilyun" . penyebut(fmod($nilai,1000000000000));
        }
        return $temp;
    }
    function terbilang($nilai) {
        if($nilai<0) {
            $hasil = "minus ". trim(penyebut($nilai));
        } else {
            $hasil = trim(penyebut($nilai));
        }
        return $hasil;
    }
    $sum_text = $request->sum_rp;

    $kwitansi->sum_rp = $sum_rp;
    $kwitansi->sum_text = terbilang($sum_text);

    $kwitansi->save();

    return redirect('kwitansi')->withSuccess('Added Succesfully');
    }
}

The Blade View

Use Form and View in One Page

@extends('layouts.admin')

@section('title', 'Kwitansi')

@section('css')

<link rel="stylesheet" href="{{ asset('adminlte/plugins/datatables-bs4/css/dataTables.bootstrap4.css') }}">
@section('js')

@endsection

@section('content')

DataTable User

              @if ($message = Session::get('success'))

                  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>

 Alert!

{{ $message }}

              @endif

                <form action="{{ route('kwitansi.store') }}" method="POST" role="form" class="form-horizontal">
                    @csrf

                        Terima Dari

                            <input type="text" name="received" class="form-control" placeholder="Received Form" />

                        Biaya Registrasi

                            <input type="text" name="registration" class="form-control" placeholder="Registration Fee" />

                        Biaya Kursus

                            <input type="text" name="course" class="form-control" placeholder="Course Fee" />

                        Biaya Transportasi

                            <input type="text" name="trasnportation" class="form-control" placeholder="Transportation Fee" />

                        Pembayaran Untuk

                            <input type="text" name="payment" class="form-control" placeholder="Payment Of" />

                        Tanggal Registrasi

                            <input type="text" name="kota"class="form-control" value="Bandung" disabled hidden>
                            <input type="date" name="register_at"class="form-control">

                    <button type="submit" class="btn btn-primary" id="btnsubmit">Tambah Data</button>
                    <button type="reset" class="btn btn-warning" id="btncancel">Cancel</button>
                </form>

                  No.
                  received
                  registration Fee
                  Course Fee
                  Transportation Fee
                  Grand Total
                  Payment of
                  Action

                @foreach($kwitansi as $k)

                  {{ $k->id }}
                  {{ $k->received }}
                  {{ $k->registration }}
                  {{ $k->course }}
                  {{ $k->transportation }}
                  {{ $k->sum_rp }}
                  {{ $k->payment }}

                    {{-- id)}}" class="btn btn-sm btn-outline-warning">
                    id)}}" class="btn btn-sm btn-outline-info">
                    <form action="{{ route('user.destroy', $u->id)}}" method="post">
                          @csrf
                          @method('DELETE')
                          <button class="btn btn-sm btn-outline-danger" type="submit"></button>
                        </form> --}}

                @endforeach

                    No.
                    received
                    registration Fee
                    Course Fee
                    Transportation Fee
                    Grand Total
                    Payment of
                    Action

@endsection

I used form and view in one page are this is the problem

This is my model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Kwitansi extends Model
{
    // $id = IdGenerator::generate(['table' => 'kwitansis', 'length' => 10, 'prefix' =>'PM-INV-']);
    protected $table = 'kwitansis';
    protected $fillable = [
        'received',
        'registration',
        'course',
        'trasnportation',
        'sum_rp',
        'payment',
        'register_at',
    ];
    protected $primarykey = 'id';

    public $increment = false;

    protected $keyType = 'string';
}

Body:
Ok Thanks Guys For Helping, I Have Solved The Problem.

I Only Delete Some function on Controller adn Worked for Me

$request->validate([
        'sum_rp' => 'required',
        'sum_text' => 'required',
      ]);

      $sum_rp = $request->registration + $request->course + $request->transportation;

      function penyebut($nilai) {
        $nilai = abs($nilai);
        $huruf = array("", "satu", "dua", "tiga", "empat", "lima", "enam", "tujuh", "delapan", "sembilan", "sepuluh", "sebelas");
        $temp = "";
        if ($nilai < 12) {
            $temp = " ". $huruf[$nilai];
        } else if ($nilai <20) {
            $temp = penyebut($nilai - 10). " belas";
        } else if ($nilai < 100) {
            $temp = penyebut($nilai/10)." puluh". penyebut($nilai % 10);
        } else if ($nilai < 200) {
            $temp = " seratus" . penyebut($nilai - 100);
        } else if ($nilai < 1000) {
            $temp = penyebut($nilai/100) . " ratus" . penyebut($nilai % 100);
        } else if ($nilai < 2000) {
            $temp = " seribu" . penyebut($nilai - 1000);
        } else if ($nilai < 1000000) {
            $temp = penyebut($nilai/1000) . " ribu" . penyebut($nilai % 1000);
        } else if ($nilai < 1000000000) {
            $temp = penyebut($nilai/1000000) . " juta" . penyebut($nilai % 1000000);
        } else if ($nilai < 1000000000000) {
            $temp = penyebut($nilai/1000000000) . " milyar" . penyebut(fmod($nilai,1000000000));
        } else if ($nilai < 1000000000000000) {
            $temp = penyebut($nilai/1000000000000) . " trilyun" . penyebut(fmod($nilai,1000000000000));
        }
        return $temp;
    }
    function terbilang($nilai) {
        if($nilai<0) {
            $hasil = "minus ". trim(penyebut($nilai));
        } else {
            $hasil = trim(penyebut($nilai));
        }
        return $hasil;
    }
    $sum_text = $request->sum_rp;

    $kwitansi->sum_rp = $sum_rp;
    $kwitansi->sum_text = terbilang($sum_text);

Only Delete This function and add it to Helper Class


问:
When sorting a Angular Material table can you view the data without modifying it?
Angular Material table utilizes a MatTableDataSource method called sortData() to sort the table's data source. (https://material.angular.io/components/table/api#MatTableDataSource). It is an arrow function:

```<code>sortData: ((data: T[], sort: MatSort) => T[])
</code>```

I need to view the sorted data without actually changing the sort. For example,

```<code>this.dataSource.sortData = (sortData) => {
    console.log(sortData);
    return sortData;
};
</code>```

The problem here is that I am overriding the native sort functionality. return sortData returns the original data, without any sorting. All I want to do is observe the sorted data without modifying it. Is it possible to do this?

答: You can do one thing that before sorting the data you can store actual data in another variable and use it.</p>

Body:
Angular Material table utilizes a MatTableDataSource method called sortData() to sort the table's data source. (https://material.angular.io/components/table/api#MatTableDataSource). It is an arrow function:

sortData: ((data: T[], sort: MatSort) => T[])

I need to view the sorted data without actually changing the sort. For example,

this.dataSource.sortData = (sortData) => {
    console.log(sortData);
    return sortData;
};

The problem here is that I am overriding the native sort functionality. return sortData returns the original data, without any sorting. All I want to do is observe the sorted data without modifying it. Is it possible to do this?


问:
Any way to add Google Maps in Flutter for Web?
I am exploring flutter-web and want to add google map in it. Although, I have used google map using google_maps_flutter in flutter-app but that works for Android and iOS.</p>

答:
First, you need the Google Map api keys. Before initializing, you have to have a project in your Google Cloud Platform. Create one if you don't have one.

Next, search for "Javascript Map" and enable it. Otherwise, the api key will shout an error that says the google map service is not activated.

Initialize the google map js sdk in our index.html file located inside web folder of your project tree.

```<code><script src="https://maps.googleapis.com/maps/api/js?key=<YOUR-API-KEY>"></script>
</code>```

And import google_maps in pubspec.yaml file:

```<code>dependencies:
  google_maps: ^3.4.1
</code>```

And here is how you create a google map widget.

```<code>import 'dart:html';
import 'package:flutter/material.dart';
import 'package:google_maps/google_maps.dart';
import 'dart:ui' as ui;

Widget getMap() {
  String htmlId = "7";

  // ignore: undefined_prefixed_name
  ui.platformViewRegistry.registerViewFactory(htmlId, (int viewId) {
    final myLatlng = LatLng(1.3521, 103.8198);

    final mapOptions = MapOptions()
      ..zoom = 10
      ..center = LatLng(1.3521, 103.8198);

    final elem = DivElement()
      ..id = htmlId
      ..style.width = "100%"
      ..style.height = "100%"
      ..style.border = 'none';

    final map = GMap(elem, mapOptions);

    Marker(MarkerOptions()
      ..position = myLatlng
      ..map = map
      ..title = 'Hello World!'
      );

    return elem;
  });

  return HtmlElementView(viewType: htmlId);
}
</code>```

htmlId - a unique id to name the div element

ui.platformViewRegistry.registerViewFactory - creates a webview in dart

LatLng(1.3521, 103.8198) - class that takes latitude and longitude of a location

DivElement() - class to create a dive element

GMap - creates a google map element

Marker() - the red icon that shows in your LatLng in google map

HtmlElementView() - creates a platform view for Flutter Web

More about google_maps package found here :

https://pub.dev/packages/google_maps

A quick tutorial on how to use it found here :

https://dev.to/happyharis/flutter-web-google-maps-381a

Hope this helps. Thanks

Body:
First, you need the Google Map api keys. Before initializing, you have to have a project in your Google Cloud Platform. Create one if you don't have one.

Next, search for "Javascript Map" and enable it. Otherwise, the api key will shout an error that says the google map service is not activated.

Initialize the google map js sdk in our index.html file located inside web folder of your project tree.

<script src="https://maps.googleapis.com/maps/api/js?key=<YOUR-API-KEY>"></script>

And import google_maps in pubspec.yaml file:

dependencies:
  google_maps: ^3.4.1

And here is how you create a google map widget.

import 'dart:html';
import 'package:flutter/material.dart';
import 'package:google_maps/google_maps.dart';
import 'dart:ui' as ui;

Widget getMap() {
  String htmlId = "7";

  // ignore: undefined_prefixed_name
  ui.platformViewRegistry.registerViewFactory(htmlId, (int viewId) {
    final myLatlng = LatLng(1.3521, 103.8198);

    final mapOptions = MapOptions()
      ..zoom = 10
      ..center = LatLng(1.3521, 103.8198);

    final elem = DivElement()
      ..id = htmlId
      ..style.width = "100%"
      ..style.height = "100%"
      ..style.border = 'none';

    final map = GMap(elem, mapOptions);

    Marker(MarkerOptions()
      ..position = myLatlng
      ..map = map
      ..title = 'Hello World!'
      );

    return elem;
  });

  return HtmlElementView(viewType: htmlId);
}

htmlId - a unique id to name the div element

ui.platformViewRegistry.registerViewFactory - creates a webview in dart

LatLng(1.3521, 103.8198) - class that takes latitude and longitude of a location

DivElement() - class to create a dive element

GMap - creates a google map element

Marker() - the red icon that shows in your LatLng in google map

HtmlElementView() - creates a platform view for Flutter Web

More about google_maps package found here :

https://pub.dev/packages/google_maps

A quick tutorial on how to use it found here :

https://dev.to/happyharis/flutter-web-google-maps-381a

Hope this helps. Thanks


问:
How to remove comma from column values of each csv and then merge?
I have multiple CSVs which I want to merge on certain columns. But before that I need to ensure the column values don't have any commas. So the commas should be replaced by a white space(" ").

So I have a folder that contains the CSVs. I am able to load them and merge them on columns town, city and state. So this is what I do

```<code>os.chdir('/Users/cho/Downloads/census/')
dfs = [pd.read_csv(f) for f in os.listdir(os.getcwd()) if f.endswith('csv')
df = reduce(lambda left,right: pd.merge(left,right,on=['town', 'city', 'state']), dfs)
df.to_csv('multicsv.csv', sep=',', encoding='utf-8', index=False)
</code>```

But I also I want to include the additional operation of replacing commas with space for each column values. I know I can do it separately by doing something like

```<code># I get the list of columns for each dataframe
cols = ['col1', 'col2', ..., 'colN']

# pass them to df.replace(), specifying each char and it's replacement:
df[cols] = df[cols].replace({'\$': '', ',': ''}, regex=True)
</code>```

But how do I include this step as part of merging operation?

答:
I think better is replace values in list comprehension for create list of DataFrames dfs:

```<code>os.chdir('/Users/cho/Downloads/census/')

cols = ['col1', 'col2', ..., 'colN']
dfs = [pd.read_csv(f).replace({'\$': '', ',': ''}, regex=True)
          for f in os.listdir(os.getcwd()) if f.endswith('csv')]

df = reduce(lambda left,right: pd.merge(left,right,on=['town', 'city', 'state']), dfs)
df.to_csv('multicsv.csv', sep=',', encoding='utf-8', index=False)
</code>```

Body:
I have multiple CSVs which I want to merge on certain columns. But before that I need to ensure the column values don't have any commas. So the commas should be replaced by a white space(" ").

So I have a folder that contains the CSVs. I am able to load them and merge them on columns town, city and state. So this is what I do

os.chdir('/Users/cho/Downloads/census/')
dfs = [pd.read_csv(f) for f in os.listdir(os.getcwd()) if f.endswith('csv')
df = reduce(lambda left,right: pd.merge(left,right,on=['town', 'city', 'state']), dfs)
df.to_csv('multicsv.csv', sep=',', encoding='utf-8', index=False)

But I also I want to include the additional operation of replacing commas with space for each column values. I know I can do it separately by doing something like

# I get the list of columns for each dataframe
cols = ['col1', 'col2', ..., 'colN']

# pass them to df.replace(), specifying each char and it's replacement:
df[cols] = df[cols].replace({'\$': '', ',': ''}, regex=True)

But how do I include this step as part of merging operation?

Body:
I think better is replace values in list comprehension for create list of DataFrames dfs:

os.chdir('/Users/cho/Downloads/census/')

cols = ['col1', 'col2', ..., 'colN']
dfs = [pd.read_csv(f).replace({'\$': '', ',': ''}, regex=True)
          for f in os.listdir(os.getcwd()) if f.endswith('csv')]

df = reduce(lambda left,right: pd.merge(left,right,on=['town', 'city', 'state']), dfs)
df.to_csv('multicsv.csv', sep=',', encoding='utf-8', index=False)


答:
As docs says

For datetime fields, casts the value as date. Allows chaining additional field lookups. Takes a date value.

```<code>from datetime import datetime
Rest.objects.filter(date__date = datetime.now().day)
</code>```

Title: Python. Best way to filter array by date

Body:
As docs says

For datetime fields, casts the value as date. Allows chaining additional field lookups. Takes a date value.

from datetime import datetime
Rest.objects.filter(date__date = datetime.now().day)


问:
How does authorization and authentication work in Azure SQL server?
I see a couple of different options for access control in Azure SQL server. There is a panel on Azure called access control (IAM) where roles like contributor/reader can be assigned to users.

The second place is the SQL server security artifacts which can be viewed in SSMS. Understanding how one of these policies works is straightforward, but how do these two policies work in tandem?

答:
According your comment, please look at this Azure SQL database document: An overview of Azure SQL Database security capabilities:

This article outlines the basics of securing the data tier of an application using Azure SQL Database. The security strategy described follows the layered defense-in-depth approach as shown in the picture below, and moves from the outside in:

It will help you learn from the Azure SQL database security. To know more about the access control and Authorization.

Azure also gives the security best practices to teach you how to use these them.

Reference: Azure SQL Database security best practices playbook. This document provides guidance on how to solve common security requirements for new or existing applications using Azure SQL Database.

Hope this helps.


问:
"Emulator: PANIC: Broken AVD system path. Check your ANDROID_SDK_ROOT value [C:\Android\sdk]!" in Android Studio
I could use the emulator properly two days ago and now it does not work.

I understand there are many people facing this problem. I have read many of them and tried the solutions stated there (set/change the environment variable of ANDROID_SDK_ROOT & ANDROID_HOME, re-install Android Studio, check avd file, etc.), but did not solve the problem.

My sdk file is in C:\Android\sdk and that is the place where Android SDK Manager in Android Studio found Android SDK as is existing. I have set ANDROID_SDK_ROOT value to C:\Android\sdk. I do not know what else to do. Is there anyone who knows how to resolve this?

I am using Android Studio 3.5.3 on Windows 10.

Thank you in advance for your reply.

答:
https://github.com/flutter/flutter/issues/24988

https://www.reddit.com/r/AndroidQuestions/comments/6of9kp/error_when_starting_emulator_panic_broken_avd/dkgzing/

https://inneka.com/programming/android/panic-broken-avd-system-path-check-your-android_sdk_root-value/

You might not need to setup path. Try to run without path.


问:
SwiftUI - Cannot assign a variable inside observeSingleEvent of Firebase. Returns nil
I am trying to load data from Firebase into my data model class QuoteBook inside the observeSingleEvent like so :

```<code>struct SceneView: View {
    @Binding var showSceneView: Bool

    var databaseRef : DatabaseReference
    @State var quoteBookDaily : QuoteBook?

    var body: some View {
        ZStack {
            GeometryReader { geometry in
                ZStack {
                    Text(self.quoteBookDaily?.title ?? "Make sure you are connected to the internet").font(Font.custom("ShadowsIntoLight", size:30)).multilineTextAlignment(.center).lineSpacing(5).padding()
                    VStack {
                        HStack {
                            Button(action:{self.backPressed()}) {
                                Image("icons8-back-24").renderingMode(.original).resizable().aspectRatio(contentMode: .fit).frame(width: 24, height: 24, alignment: .leading)
                            }.padding()
                            Spacer()
                            Button(action:{self.takeScreenshot()}) {
                                Image("icons8-screenshot-26").renderingMode(.original).resizable().aspectRatio(contentMode: .fit).frame(width: 26, height: 26, alignment: .leading)
                            }.padding()
                        }
                        Spacer()
                    }
                }
            }
        }.onAppear() {

        }
    }

    init(showSceneView : Binding<Bool>) {
        self._showSceneView = showSceneView
        self.databaseRef = Database.database().reference()
        self.initDataFromFirebase()
    }

    func backPressed() {
        self.showSceneView = false
    }

    func takeScreenshot() {

    }

    func initDataFromFirebase() {
        let quoteBook = QuoteBook() // <--- This is not null

        databaseRef.observeSingleEvent(of: .value, with: {(snapshot) in
            let value = snapshot.value as? NSDictionary
            let msg1 = value?["msg1"] as? String ?? " "
            let msg2 = value?["msg2"] as? String ?? " "
            let msg3 = value?["msg3"] as? String ?? " "
            let msg4 = value?["msg4"] as? String ?? " "
            let msg5 = value?["msg5"] as? String ?? " "
            let msg6 = value?["msg6"] as? String ?? " "
            let msg7 = value?["msg7"] as? String ?? " "
            let msg8 = value?["msg8"] as? String ?? " "
            let msg9 = value?["msg9"] as? String ?? " "
            let msg10 = value?["msg10"] as? String ?? " "
            let msg11 = value?["msg11"] as? String ?? " "
            let name = value?["name"] as? String ?? " "

            quoteBook.msg.append(msg1)
            quoteBook.msg.append(msg2)
            quoteBook.msg.append(msg3)
            quoteBook.msg.append(msg4)
            quoteBook.msg.append(msg5)
            quoteBook.msg.append(msg6)
            quoteBook.msg.append(msg7)
            quoteBook.msg.append(msg8)
            quoteBook.msg.append(msg9)
            quoteBook.msg.append(msg10)
            quoteBook.msg.append(msg11)
            quoteBook.title = name

            self.quoteBookDaily = quoteBook
            print(self.quoteBookDaily!.msg[0]) // So why is this null?? <--- Fatal error : Unexpectedly found nil while unwrapping an Optional value

        })
    }
}

struct SceneView_Previews: PreviewProvider {
    static var previews: some View {
        SceneView(showSceneView : .constant(false))
    }
}
</code>```

The constant quoteBook declared in the initDataFromFirebase is not null, but when I assign it to self.quoteBookDaily and try to print one of its properties, it throws an error saying it's null. I don't understand why it's saying that when I am just reassigning a non null object to another object, therefore it shouldn't be null...

答:
I cannot test your code, but try the following

1) give initial value for @State

```<code>@State var quoteBookDaily : QuoteBook? = nil
</code>```

2) update state in UI thread

```<code>...
quoteBook.title = name

DispatchQueue.main.async {
    self.quoteBookDaily = quoteBook
    print(self.quoteBookDaily!.msg[0])
}
</code>```

if this will not be enough, because here might be some racing effect, then move initial loading in onAppear (because @State finally linked to view, when view is placed into hierarchy, so there is possibility that your data appears before quoteBookDaily is ready to accept them)

```<code>}.onAppear() {
    self.initDataFromFirebase()
}
</code>```

Body:
I am trying to load data from Firebase into my data model class QuoteBook inside the observeSingleEvent like so :

struct SceneView: View {
    @Binding var showSceneView: Bool

    var databaseRef : DatabaseReference
    @State var quoteBookDaily : QuoteBook?

    var body: some View {
        ZStack {
            GeometryReader { geometry in
                ZStack {
                    Text(self.quoteBookDaily?.title ?? "Make sure you are connected to the internet").font(Font.custom("ShadowsIntoLight", size:30)).multilineTextAlignment(.center).lineSpacing(5).padding()
                    VStack {
                        HStack {
                            Button(action:{self.backPressed()}) {
                                Image("icons8-back-24").renderingMode(.original).resizable().aspectRatio(contentMode: .fit).frame(width: 24, height: 24, alignment: .leading)
                            }.padding()
                            Spacer()
                            Button(action:{self.takeScreenshot()}) {
                                Image("icons8-screenshot-26").renderingMode(.original).resizable().aspectRatio(contentMode: .fit).frame(width: 26, height: 26, alignment: .leading)
                            }.padding()
                        }
                        Spacer()
                    }
                }
            }
        }.onAppear() {

        }
    }

    init(showSceneView : Binding<Bool>) {
        self._showSceneView = showSceneView
        self.databaseRef = Database.database().reference()
        self.initDataFromFirebase()
    }

    func backPressed() {
        self.showSceneView = false
    }

    func takeScreenshot() {

    }

    func initDataFromFirebase() {
        let quoteBook = QuoteBook() // <--- This is not null

        databaseRef.observeSingleEvent(of: .value, with: {(snapshot) in
            let value = snapshot.value as? NSDictionary
            let msg1 = value?["msg1"] as? String ?? " "
            let msg2 = value?["msg2"] as? String ?? " "
            let msg3 = value?["msg3"] as? String ?? " "
            let msg4 = value?["msg4"] as? String ?? " "
            let msg5 = value?["msg5"] as? String ?? " "
            let msg6 = value?["msg6"] as? String ?? " "
            let msg7 = value?["msg7"] as? String ?? " "
            let msg8 = value?["msg8"] as? String ?? " "
            let msg9 = value?["msg9"] as? String ?? " "
            let msg10 = value?["msg10"] as? String ?? " "
            let msg11 = value?["msg11"] as? String ?? " "
            let name = value?["name"] as? String ?? " "

            quoteBook.msg.append(msg1)
            quoteBook.msg.append(msg2)
            quoteBook.msg.append(msg3)
            quoteBook.msg.append(msg4)
            quoteBook.msg.append(msg5)
            quoteBook.msg.append(msg6)
            quoteBook.msg.append(msg7)
            quoteBook.msg.append(msg8)
            quoteBook.msg.append(msg9)
            quoteBook.msg.append(msg10)
            quoteBook.msg.append(msg11)
            quoteBook.title = name

            self.quoteBookDaily = quoteBook
            print(self.quoteBookDaily!.msg[0]) // So why is this null?? <--- Fatal error : Unexpectedly found nil while unwrapping an Optional value

        })
    }
}

struct SceneView_Previews: PreviewProvider {
    static var previews: some View {
        SceneView(showSceneView : .constant(false))
    }
}

The constant quoteBook declared in the initDataFromFirebase is not null, but when I assign it to self.quoteBookDaily and try to print one of its properties, it throws an error saying it's null. I don't understand why it's saying that when I am just reassigning a non null object to another object, therefore it shouldn't be null...

Body:
I cannot test your code, but try the following

1) give initial value for @State

@State var quoteBookDaily : QuoteBook? = nil

2) update state in UI thread

...
quoteBook.title = name

DispatchQueue.main.async {
    self.quoteBookDaily = quoteBook
    print(self.quoteBookDaily!.msg[0])
}

if this will not be enough, because here might be some racing effect, then move initial loading in onAppear (because @State finally linked to view, when view is placed into hierarchy, so there is possibility that your data appears before quoteBookDaily is ready to accept them)

}.onAppear() {
    self.initDataFromFirebase()
}


问:
v8::internal::V8::FatalProcessOutOfMemory error during AWS Amplify React js app cloning
I have developed the React js web application using AWS Amplify. I get this error during the cloning process of the amplify build.

```<code>2020-02-17T05:40:19.634Z [INFO]: Resolving deltas:  96% (85/88)
2020-02-17T05:40:19.642Z [INFO]: Resolving deltas: 100% (88/88)
2020-02-17T05:40:19.644Z [INFO]: Resolving deltas: 100% (88/88), done.
2020-02-17T05:40:19.662Z [INFO]: # Switching to commit: 2891d42cdf67d009c8cb84ec42db471b5aaae537
2020-02-17T05:40:19.669Z [INFO]: Note: checking out '2891d42cdf67d009c8cb84ec42db471b5aaae537'.
                                 You are in 'detached HEAD' state. You can look around, make experimental
                                 changes and commit them, and you can discard any commits you make in this
                                 state without impacting any branches by performing another checkout.
                                 If you want to create a new branch to retain commits you create, you may
                                 do so (now or later) by using -b with the checkout command again. Example:
                                 git checkout -b <new-branch-name>
                                 HEAD is now at 2891d42 add bowen email
2020-02-17T05:40:19.669Z [INFO]: # Checking for Git submodules at: /codebuild/output/src577764799/src/morning-admin-panel/.gitmodules
2020-02-17T05:40:19.715Z [INFO]: # Retrieving cache...
2020-02-17T05:40:23.250Z [INFO]: # Extracting cache...
2020-02-17T05:40:33.333Z [INFO]: # Extraction completed
bool) [/root/.nvm/versions/node/v10.16.0/bin/node]
                                    4: 0xafff44 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [/root/.nvm/versions/node/v10.16.0/bin/node]
                                    5: 0xef4152  [/root/.nvm/versions/node/v10.16.0/bin/node]
                                    6: 0xef4258 v8::internal::Heap::CheckIneffectiveMarkCompact(unsigned long, double) [/root/.nvm/versions/node/v10.16.0/bin/node]
                                    7: 0xf00332 v8::internal::Heap::PerformGarbageCollection(v8::internal::GarbageCollector, v8::GCCallbackFlags) [/root/.nvm/versions/node/v10.16.0/bin/node]
                                    8: 0xf00c64 v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [/root/.nvm/versions/node/v10.16.0/bin/node]
                                    9: 0xf038d1 v8::internal::Heap::AllocateRawWithRetryOrFail(int, v8::internal::AllocationSpace, v8::internal::AllocationAlignment) [/root/.nvm/versions/node/v10.16.0/bin/node]
                                    10: 0xeccd54 v8::internal::Factory::NewFillerObject(int, bool, v8::internal::AllocationSpace) [/root/.nvm/versions/node/v10.16.0/bin/node]
                                    11: 0x116cede v8::internal::Runtime_AllocateInNewSpace(int, v8::internal::Object**, v8::internal::Isolate*) [/root/.nvm/versions/node/v10.16.0/bin/node]
                                    12: 0x1ee0996dbe1d
2020-02-17T05:44:01.944Z [WARNING]: error Command failed with exit code 1.
2020-02-17T05:44:01.944Z [INFO]: info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
2020-02-17T05:44:01.950Z [ERROR]: !!! Build failed
2020-02-17T05:44:01.950Z [ERROR]: !!! Non-Zero Exit Code detected
2020-02-17T05:44:01.950Z [INFO]: # Starting environment caching...
2020-02-17T05:44:01.952Z [INFO]: # Uploading environment cache artifact...
2020-02-17T05:44:02.041Z [INFO]: # Environment caching completed
</code>```

I'm using "react": "^16.12.0", "aws-amplify": "^2.2.0", and Nodejs v12.13.1

答:
I noticed that in my development environment I was using Nodejs v12.13.1. But amplify used Node v10

```<code># Use the standard Amazon Linux base, provided by ECR/KaOS
# It points to the standard shared Amazon Linux image, with a versioned tag.
FROM 137112412989.dkr.ecr.us-west-2.amazonaws.com/amazonlinux:2
MAINTAINER Amazon AWS

# Framework Versions
ENV VERSION_NODE_8=8.12.0
ENV VERSION_NODE_10=10.16.0
ENV VERSION_NODE_12=12
ENV VERSION_NODE_DEFAULT=$VERSION_NODE_10
ENV VERSION_RUBY_2_4=2.4.6
ENV VERSION_RUBY_2_6=2.6.3
ENV VERSION_BUNDLER=2.0.1
ENV VERSION_RUBY_DEFAULT=$VERSION_RUBY_2_4
ENV VERSION_HUGO=0.55.6
ENV VERSION_YARN=1.16.0
ENV VERSION_AMPLIFY=1.12.0

# UTF-8 Environment
ENV LANGUAGE en_US:en
ENV LANG=en_US.UTF-8
ENV LC_ALL en_US.UTF-8

## Install OS packages
RUN touch ~/.bashrc
</code>```

I had to change the amplify.yml to change the Nodejs version.

```<code>version: 0.1
backend:
  phases:
    build:
      commands:
        - '# Execute Amplify CLI with the helper script'
        - amplifyPush --simple
frontend:
  phases:
    preBuild:
      commands:
        - nvm use 12
        - yarn install
    build:
      commands:
        - nvm use 12
        - yarn run build
  artifacts:
    baseDirectory: build
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*
</code>```

Body:
I have developed the React js web application using AWS Amplify. I get this error during the cloning process of the amplify build.

2020-02-17T05:40:19.634Z [INFO]: Resolving deltas:  96% (85/88)
2020-02-17T05:40:19.642Z [INFO]: Resolving deltas: 100% (88/88)
2020-02-17T05:40:19.644Z [INFO]: Resolving deltas: 100% (88/88), done.
2020-02-17T05:40:19.662Z [INFO]: # Switching to commit: 2891d42cdf67d009c8cb84ec42db471b5aaae537
2020-02-17T05:40:19.669Z [INFO]: Note: checking out '2891d42cdf67d009c8cb84ec42db471b5aaae537'.
                                 You are in 'detached HEAD' state. You can look around, make experimental
                                 changes and commit them, and you can discard any commits you make in this
                                 state without impacting any branches by performing another checkout.
                                 If you want to create a new branch to retain commits you create, you may
                                 do so (now or later) by using -b with the checkout command again. Example:
                                 git checkout -b <new-branch-name>
                                 HEAD is now at 2891d42 add bowen email
2020-02-17T05:40:19.669Z [INFO]: # Checking for Git submodules at: /codebuild/output/src577764799/src/morning-admin-panel/.gitmodules
2020-02-17T05:40:19.715Z [INFO]: # Retrieving cache...
2020-02-17T05:40:23.250Z [INFO]: # Extracting cache...
2020-02-17T05:40:33.333Z [INFO]: # Extraction completed
bool) [/root/.nvm/versions/node/v10.16.0/bin/node]
                                    4: 0xafff44 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [/root/.nvm/versions/node/v10.16.0/bin/node]
                                    5: 0xef4152  [/root/.nvm/versions/node/v10.16.0/bin/node]
                                    6: 0xef4258 v8::internal::Heap::CheckIneffectiveMarkCompact(unsigned long, double) [/root/.nvm/versions/node/v10.16.0/bin/node]
                                    7: 0xf00332 v8::internal::Heap::PerformGarbageCollection(v8::internal::GarbageCollector, v8::GCCallbackFlags) [/root/.nvm/versions/node/v10.16.0/bin/node]
                                    8: 0xf00c64 v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [/root/.nvm/versions/node/v10.16.0/bin/node]
                                    9: 0xf038d1 v8::internal::Heap::AllocateRawWithRetryOrFail(int, v8::internal::AllocationSpace, v8::internal::AllocationAlignment) [/root/.nvm/versions/node/v10.16.0/bin/node]
                                    10: 0xeccd54 v8::internal::Factory::NewFillerObject(int, bool, v8::internal::AllocationSpace) [/root/.nvm/versions/node/v10.16.0/bin/node]
                                    11: 0x116cede v8::internal::Runtime_AllocateInNewSpace(int, v8::internal::Object**, v8::internal::Isolate*) [/root/.nvm/versions/node/v10.16.0/bin/node]
                                    12: 0x1ee0996dbe1d
2020-02-17T05:44:01.944Z [WARNING]: error Command failed with exit code 1.
2020-02-17T05:44:01.944Z [INFO]: info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
2020-02-17T05:44:01.950Z [ERROR]: !!! Build failed
2020-02-17T05:44:01.950Z [ERROR]: !!! Non-Zero Exit Code detected
2020-02-17T05:44:01.950Z [INFO]: # Starting environment caching...
2020-02-17T05:44:01.952Z [INFO]: # Uploading environment cache artifact...
2020-02-17T05:44:02.041Z [INFO]: # Environment caching completed

I'm using "react": "^16.12.0", "aws-amplify": "^2.2.0", and Nodejs v12.13.1

Body:
I noticed that in my development environment I was using Nodejs v12.13.1. But amplify used Node v10

# Use the standard Amazon Linux base, provided by ECR/KaOS
# It points to the standard shared Amazon Linux image, with a versioned tag.
FROM 137112412989.dkr.ecr.us-west-2.amazonaws.com/amazonlinux:2
MAINTAINER Amazon AWS

# Framework Versions
ENV VERSION_NODE_8=8.12.0
ENV VERSION_NODE_10=10.16.0
ENV VERSION_NODE_12=12
ENV VERSION_NODE_DEFAULT=$VERSION_NODE_10
ENV VERSION_RUBY_2_4=2.4.6
ENV VERSION_RUBY_2_6=2.6.3
ENV VERSION_BUNDLER=2.0.1
ENV VERSION_RUBY_DEFAULT=$VERSION_RUBY_2_4
ENV VERSION_HUGO=0.55.6
ENV VERSION_YARN=1.16.0
ENV VERSION_AMPLIFY=1.12.0

# UTF-8 Environment
ENV LANGUAGE en_US:en
ENV LANG=en_US.UTF-8
ENV LC_ALL en_US.UTF-8

## Install OS packages
RUN touch ~/.bashrc

I had to change the amplify.yml to change the Nodejs version.

version: 0.1
backend:
  phases:
    build:
      commands:
        - '# Execute Amplify CLI with the helper script'
        - amplifyPush --simple
frontend:
  phases:
    preBuild:
      commands:
        - nvm use 12
        - yarn install
    build:
      commands:
        - nvm use 12
        - yarn run build
  artifacts:
    baseDirectory: build
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*


问:
ContentLoadingProgressBar is not displaying for a minimum amount of time before hiding
I'm trying to use ContentLoadingProgressBar to display 1 second before hiding itself. However I can't seem to find any examples of how to use it correctly with a recyclerview.

So I've tried using just testing it, but I can't get it to display for a minimum amount of time. How would I do so?

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.core.widget.ContentLoadingProgressBar
        android:id="@+id/main_progressbar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        style="?android:attr/progressBarStyleLarge"
        android:visibility="visible"/>

</RelativeLayout>
</code>```

I've simply just tried doing it like this:

```<code>mProgressBar.show();
mProgressBar.hide();
</code>```

However it's not displaying for 1 second before hiding. It just hides automatically.

答:
```<code>mProgressBar.show();
Handler().postDelayed({
  mProgressBar.hide();
}, 1000)
</code>```

Body:
I'm trying to use ContentLoadingProgressBar to display 1 second before hiding itself. However I can't seem to find any examples of how to use it correctly with a recyclerview.

So I've tried using just testing it, but I can't get it to display for a minimum amount of time. How would I do so?

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.core.widget.ContentLoadingProgressBar
        android:id="@+id/main_progressbar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        style="?android:attr/progressBarStyleLarge"
        android:visibility="visible"/>

</RelativeLayout>

I've simply just tried doing it like this:

mProgressBar.show();
mProgressBar.hide();

However it's not displaying for 1 second before hiding. It just hides automatically.