问:
Why are multiple inquirer prompts running concurrently even outside of the method they are in?
I am attempting to create a command line interface that prompts users to enter or retrieve data from a database.

So far the only methods I have written are for the info needed from the user to create new database rows. However when one of the inquirer prompts is called, the rest of the following prompts also execute, even when not in the same method.

```<code>class Query {
    constructor () {
        this.options = ['View All Departments', 'View All Roles', 'View All Employees', 'Add Department', 'Add Role', 'Add Employee', 'Update Employee Role']
    };

    optionsMenu() {
        inquirer.prompt({
            type: 'list',
            message: 'What would you like to do next?',
            choices: this.options,
            name: 'userOption'
        })
        .then((res) => {
            switch(res.userOption) {
                case 'View All Departments':
                    this.viewDept();
                case 'View All Roles':
                    this.viewRoles();
                case 'View All Employees':
                    this.viewEmp();
                case 'Add Department':
                    this.addDept();
                case 'Add Role':
                    this.addRole();
                case 'Add Employee':
                    this.addEmp();
                case 'Update Employee Role':
                    this.updateEmp();
            }
        })
    }

    viewDept() {}

    viewRoles() {}

    viewEmp() {}

    async addDept() {
        const inquiry = await inquirer.prompt({
            type: 'input',
            message: 'What is the name of the new department?',
            name: 'department'
        })

        const newDept = new Department(inquiry.department);
        newDept.insertDept().then(() => {
            this.optionsMenu();
        });
    }

    async addRole() {
        //Query DB for available departments to tie to the role being added
        const departments = await mysql.db.promise().query('SELECT * FROM department').then((results) => {return results[0]});

        //Map departments into an array for the inquirer question
        const departmentChoice = departments.map(x => x.name)

        //Query DB for roles
        const roleQuery = await mysql.db.promise().query('SELECT * FROM role').then((results) => {return results[0]});

        //Map roles into an array for the inquirer validation
        const roles = roleQuery.map(x => x.title.toLowerCase());

        //Inquirer prompts for role information from User
        const inquiry = await inquirer.prompt([
            {
                type: 'input',
                message: 'What is the name of the role you would like to add?',
                name: 'role',
                validate: (input) => {
                    //Check input against existing roles to make sure it is unique
                    let lowercase = input.toLowerCase
                    if (roles.includes(lowercase)) {
                        return 'Role already exists'
                    } else {
                        return true;
                    }
                }
            },
            {
                type: 'list',
                message: 'Which department does the role belong to?',
                choices: departmentChoice,
                name: 'department'
            },
            {
                type: 'number',
                message: 'What is the salary of the new role?',
                name: 'salary'
            }
        ])

        //Loop through deparments array to find matching department id
        for(const i = 0; i < departments.length; i++) {
            if (Object.values(departments[i]).includes(inquiry.department)) {
                const newRole = new Role(inquiry.role, departments[i].id, inquiry.salary)
                newRole.insertRole().then(() => {this.optionsMenu()})
            }
        }
    }

    async addEmp() {
        //Query DB for roles
        const roleQuery = await mysql.db.promise().query('SELECT * FROM role').then((results) => {return results[0]});

        //Map roles into an array for the inquirer question
        const roleChoice = roleQuery.map(x => x.title);

        //Query DB for employees
        const employeeQuery = await mysql.db.promise().query('SELECT * FROM employee').then((results) => {return results[0]});

        //Map employees into an array for the inquirer question
        const employeeChoice = employeeQuery.map(x => x.first_name + " " + x.last_name);

        //Add 'None' as an option for employees
        employeeChoice.push('None');

        const inquiry = await inquirer.prompt([
            {
                type: 'input',
                message: "What is the employee's first name?",
                name: 'firstName',
                validate: (input) => {
                    if (!input) {
                        return 'First name cannot be blank.'
                    } else {
                        return true;
                    }
                }
            },
            {
                type: 'input',
                message: "What is the employee's last name?",
                name: 'lastName',
                validate: (input) => {
                    if (!input) {
                        return 'Last name cannot be blank.'
                    } else {
                        return true;
                    }
                }
            },
            {
                type: 'list',
                message: "Which role will the employee take?",
                choices: roleChoice,
                name: 'role'
            },
            {
                type: 'list',
                message: "Enter the employee's manager:",
                choices: employeeChoice,
                name: 'manager'
            }
        ])
    }

    updateEmp() {}
}
</code>```

答:
When setting up switch statement, you must put a break after every case.

What happens if I forgot a break?

If you forget a break then the script will run from the case where the criterion is met and will run the cases after that regardless if a criterion was met.

Body:
I am attempting to create a command line interface that prompts users to enter or retrieve data from a database.

So far the only methods I have written are for the info needed from the user to create new database rows. However when one of the inquirer prompts is called, the rest of the following prompts also execute, even when not in the same method.

class Query {
    constructor () {
        this.options = ['View All Departments', 'View All Roles', 'View All Employees', 'Add Department', 'Add Role', 'Add Employee', 'Update Employee Role']
    };

    optionsMenu() {
        inquirer.prompt({
            type: 'list',
            message: 'What would you like to do next?',
            choices: this.options,
            name: 'userOption'
        })
        .then((res) => {
            switch(res.userOption) {
                case 'View All Departments':
                    this.viewDept();
                case 'View All Roles':
                    this.viewRoles();
                case 'View All Employees':
                    this.viewEmp();
                case 'Add Department':
                    this.addDept();
                case 'Add Role':
                    this.addRole();
                case 'Add Employee':
                    this.addEmp();
                case 'Update Employee Role':
                    this.updateEmp();
            }
        })
    }

    viewDept() {}

    viewRoles() {}

    viewEmp() {}

    async addDept() {
        const inquiry = await inquirer.prompt({
            type: 'input',
            message: 'What is the name of the new department?',
            name: 'department'
        })

        const newDept = new Department(inquiry.department);
        newDept.insertDept().then(() => {
            this.optionsMenu();
        });
    }

    async addRole() {
        //Query DB for available departments to tie to the role being added
        const departments = await mysql.db.promise().query('SELECT * FROM department').then((results) => {return results[0]});

        //Map departments into an array for the inquirer question
        const departmentChoice = departments.map(x => x.name)

        //Query DB for roles
        const roleQuery = await mysql.db.promise().query('SELECT * FROM role').then((results) => {return results[0]});

        //Map roles into an array for the inquirer validation
        const roles = roleQuery.map(x => x.title.toLowerCase());

        //Inquirer prompts for role information from User
        const inquiry = await inquirer.prompt([
            {
                type: 'input',
                message: 'What is the name of the role you would like to add?',
                name: 'role',
                validate: (input) => {
                    //Check input against existing roles to make sure it is unique
                    let lowercase = input.toLowerCase
                    if (roles.includes(lowercase)) {
                        return 'Role already exists'
                    } else {
                        return true;
                    }
                }
            },
            {
                type: 'list',
                message: 'Which department does the role belong to?',
                choices: departmentChoice,
                name: 'department'
            },
            {
                type: 'number',
                message: 'What is the salary of the new role?',
                name: 'salary'
            }
        ])

        //Loop through deparments array to find matching department id
        for(const i = 0; i < departments.length; i++) {
            if (Object.values(departments[i]).includes(inquiry.department)) {
                const newRole = new Role(inquiry.role, departments[i].id, inquiry.salary)
                newRole.insertRole().then(() => {this.optionsMenu()})
            }
        }
    }

    async addEmp() {
        //Query DB for roles
        const roleQuery = await mysql.db.promise().query('SELECT * FROM role').then((results) => {return results[0]});

        //Map roles into an array for the inquirer question
        const roleChoice = roleQuery.map(x => x.title);

        //Query DB for employees
        const employeeQuery = await mysql.db.promise().query('SELECT * FROM employee').then((results) => {return results[0]});

        //Map employees into an array for the inquirer question
        const employeeChoice = employeeQuery.map(x => x.first_name + " " + x.last_name);

        //Add 'None' as an option for employees
        employeeChoice.push('None');

        const inquiry = await inquirer.prompt([
            {
                type: 'input',
                message: "What is the employee's first name?",
                name: 'firstName',
                validate: (input) => {
                    if (!input) {
                        return 'First name cannot be blank.'
                    } else {
                        return true;
                    }
                }
            },
            {
                type: 'input',
                message: "What is the employee's last name?",
                name: 'lastName',
                validate: (input) => {
                    if (!input) {
                        return 'Last name cannot be blank.'
                    } else {
                        return true;
                    }
                }
            },
            {
                type: 'list',
                message: "Which role will the employee take?",
                choices: roleChoice,
                name: 'role'
            },
            {
                type: 'list',
                message: "Enter the employee's manager:",
                choices: employeeChoice,
                name: 'manager'
            }
        ])
    }

    updateEmp() {}
}


来源: stackexchange

问:
What are all possible permissions taken by apps?
There are two types of app permissions in case of android apps

Install time permissions- apps take permission while being installed (run at startup, install shortcuts, run in background etc.)

Run time permissions- Users give permission to the app (gallery, camera, contacts etc.)

Can you please give me the separate lists of all the permissions?
Also, how to know which permissions are taken by an app?

答:
The complete list of all permissions available to an app is available here. For runtime permissions you should search for all permissions in the provided link with the Protection level equal to dangerous. For example ACCESS_MEDIA_LOCATION is a runtime (dangerous) permission as stated here.

If you want to check that a specific permission is granted or not, use the following code snippet:

```<code>boolean isGranted = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_MEDIA_LOCATION) == PackageManager.PERMISSION_GRANTED
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The complete list of all permissions available to an app is available here. For runtime permissions you should search for all permissions in the provided link with the Protection level equal to dangerous. For example ACCESS_MEDIA_LOCATION is a runtime (dangerous) permission as stated here.

If you want to check that a specific permission is granted or not, use the following code snippet:

boolean isGranted = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_MEDIA_LOCATION) == PackageManager.PERMISSION_GRANTED


问:
Sql Server CDC (Change Data Capture) Apply the data changes to the backedup database
We had a requirement to enable all tables CDC and migrate the updates to the database backup which were taken prior to enabling CDC.

Step 1: Take the database backup at x point time.

Step 2: Enable CDC on the database and Enable CDC on all the tables.

Step 3: After the Y point of time we would need to merge data
changes to the database backup we took at step 1. i.e (X to Y point of time changes needs to be merged to the backed-up database.)

Could you please help me out on this?.

答:
Well, for starters you have step 1 and 2 in the wrong order.
You should start CDC before making the reference backup because the other way around there is a gap of missing changes. It is better to have duplicate changes than missing change would you not agree? (dup insert gives dup error, dup update just re-applies, dup delete just finds nothing to delete which is fine).

There are several (for fee) 3rd party solutions to handle this solution, and possibly some shareware. Please study your options before reinventing the wheel so to speak with all the possible errors that go with that.
One such solution is Qlik Replicate which they picked up from Attunity (where I used to work).
Good luck.
Hein.


问:
How to disable header view in ListView
Anybody knows how to disable the header view in list view?
I need to add a header into a list view and make it not clickable.
For adapter it's pretty simple: return false in isEnabled(int position) method but I didn't find an appropriate function for list headers/footers. Setting enabled flag for header view didn't help, nor did specifying "android:descendantFocusability="blocksDescendants"" in header's xml

答:
use these methods to add header and footer in list:</p>

```<code>list.addFooterView(v);
list.addHeaderView(v, data, isSelectable);
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to disable header view in ListView

Body:
use these methods to add header and footer in list:

list.addFooterView(v);
list.addHeaderView(v, data, isSelectable);


问:
AWS RDS Data API executeStatement not return column names
I'm playing with the New Data API for Amazon Aurora Serverless

Is it possible to get the table column names in the response?

If for example I run the following query in a user table with the columns id, first_name, last_name, email, phone:

const sqlStatement = `
    SELECT *
    FROM user
    WHERE id = :id
`;
const params = {
    secretArn: <mySecretArn>,
    resourceArn: <myResourceArn>,
    database: <myDatabase>,
    sql: sqlStatement,
    parameters: [
        {
            name: "id",
            value: {
                "stringValue": 1
            }
        }
    ]
};
let res = await this.RDS.executeStatement(params)
console.log(res);
```
<p>I'm getting a response like this one, So I need to guess which column corresponds with each value:</p>
<pre class="lang-json prettyprint-override"><code>{
    "numberOfRecordsUpdated": 0,
    "records": [
        [
            {
                "longValue": 1
            },
            {
                "stringValue": "Nicolas"
            },
            {
                "stringValue": "Perez"
            },
            {
                "stringValue": "example@example.com"
            },
            {
                "isNull": true
            }
        ]
    ]
}
</code>```

I would like to have a response like this one:

{
    id: 1,
    first_name: "Nicolas",
    last_name: "Perez",
    email: "example@example.com",
    phone: null
}
```

update1

I have found an npm module that wrap Aurora Serverless Data API and simplify the development

答:
Similar to the other answers, but if you are using Python/Boto3:

def parse_data_service_response(res):
    columns = [column['name'] for column in res['columnMetadata']]

    parsed_records = []
    for record in res['records']:
        parsed_record = {}
        for i, cell in enumerate(record):
            key = columns[i]
            value = list(cell.values())[0]
            parsed_record[key] = value
        parsed_records.append(parsed_record)

    return parsed_records
```

Body:
I'm playing with the New Data API for Amazon Aurora Serverless

Is it possible to get the table column names in the response?

If for example I run the following query in a user table with the columns id, first_name, last_name, email, phone:

const sqlStatement = `
    SELECT *
    FROM user
    WHERE id = :id
`;
const params = {
    secretArn: <mySecretArn>,
    resourceArn: <myResourceArn>,
    database: <myDatabase>,
    sql: sqlStatement,
    parameters: [
        {
            name: "id",
            value: {
                "stringValue": 1
            }
        }
    ]
};
let res = await this.RDS.executeStatement(params)
console.log(res);

I'm getting a response like this one, So I need to guess which column corresponds with each value:

{
    "numberOfRecordsUpdated": 0,
    "records": [
        [
            {
                "longValue": 1
            },
            {
                "stringValue": "Nicolas"
            },
            {
                "stringValue": "Perez"
            },
            {
                "stringValue": "example@example.com"
            },
            {
                "isNull": true
            }
        ]
    ]
}

I would like to have a response like this one:

{
    id: 1,
    first_name: "Nicolas",
    last_name: "Perez",
    email: "example@example.com",
    phone: null
}

update1

I have found an npm module that wrap Aurora Serverless Data API and simplify the development


问:
How to get-adgroup members by their Name or SamAccountName
i would like to extract members from an AD Group that contains Members and security group.

```<code>Example, Group_A:
User1
User2
User3
Group_B
</code>```

When I run my script, it shows:

CN=User1,OU=Users,DC=Contoso,DC=com
CN=User2,OU=Users,DC=Contoso,DC=com
CN=User3,OU=Users,DC=Contoso,DC=com
CN=Group_B,OU=Users,DC=Contoso,DC=com

Is there another way to show their Name and/or SamAccountname?

```<code>$Groups =
@"
GroupNames;
Group_A
"@ | ConvertFrom-Csv -Delimiter ';'

$ADGroups =
Foreach ($Group in $Groups){
Get-ADGroup $Group.GroupNames -Server contoso.com -Properties Members }

$ADGroups.Members
</code>```

答:
Get-ADGroupMember has two parameters you can use for that. samaccountname, and name.

Simply do the following:

```<code>Get-ADGroupMember -identity $ADGroup | select-object SamAccountName, Name
</code>```

Or in your code snippet:

```<code>Foreach ($group in $groups) {
Get-AdGroup -identity $group | select-object Samaccountname, Name }
</code>```

Of course you could add:

```<code>Get-AdGroup -identity $group | select-object Samaccountname, Name | export-csv C:\mypath\report.csv
</code>```

Body:
i would like to extract members from an AD Group that contains Members and security group.

Example, Group_A:
User1
User2
User3
Group_B

When I run my script, it shows:

CN=User1,OU=Users,DC=Contoso,DC=com
CN=User2,OU=Users,DC=Contoso,DC=com
CN=User3,OU=Users,DC=Contoso,DC=com
CN=Group_B,OU=Users,DC=Contoso,DC=com

Is there another way to show their Name and/or SamAccountname?

$Groups =
@"
GroupNames;
Group_A
"@ | ConvertFrom-Csv -Delimiter ';'

$ADGroups =
Foreach ($Group in $Groups){
Get-ADGroup $Group.GroupNames -Server contoso.com -Properties Members }

$ADGroups.Members

Body:
Get-ADGroupMember has two parameters you can use for that. samaccountname, and name.

Simply do the following:

Get-ADGroupMember -identity $ADGroup | select-object SamAccountName, Name

Or in your code snippet:

Foreach ($group in $groups) {
Get-AdGroup -identity $group | select-object Samaccountname, Name }

Of course you could add:

Get-AdGroup -identity $group | select-object Samaccountname, Name | export-csv C:\mypath\report.csv


问:
How do I write a .txt file with the same name as the input file?
I provide a video as an input to my system, it processes the video and then it writes some information into a .txt file. How do I name the .txt file exactly the same as the video file name?</p>
```<code>    # getting input video
    ap = argparse.ArgumentParser()
    ap.add_argument("-i", "--input", required=True,
                    help="path to input video")
    ap.add_argument("-o", "--output", required=True,
                    help="path to output video")

    args = vars(ap.parse_args())

    # capturing the video frames from input video
    vs = cv2.VideoCapture(args["input"])

    # writing the output folder and txt file

    outputfile_dir = os.path.join(os.getcwd(),'output')
    if not os.path.exists(outputfile_dir):
        os.makedirs(outputfile_dir)
        os.chmod(outputfile_dir , 0o777)
    outputFilename=os.path.join(outputfile_dir,"demofile.txt")
</code>```

答:
from pathlib import Path

def to_txt(filename: Path) -> Path:
    """Changes a filename for an arbitrary
    file to a filename with a *.txt suffix.
    """

    return filename.parent / f'{filename.stem}.txt'

filename = Path('dir1/videos/my_video-12.avi')
txt_file = to_txt(filename)
print(txt_file)
```

Explanation

pathlib is part of Python's standard library and provides object-oriented access to path-like objects. I.e. you can hadle file and directory paths as objects with methods and properties for common operations on those types of objects. For further details, read the docs.

What the function to_txt() does is, it takes such a path-like object, namely the path to the video file as input. It then extracts the paths to the video's parent directory by accessing the property filename.parent, which returns another pathlib.Path object to the directory containing the file. So for any file named dir1/videos/my_video-12.avi, this part returns dir1/videos.

You can access a pathlib.Path's file name without the leading directories and without its suffix via the property Path.stem.
In the f-string f'{filename.stem}.txt', we access this property and concatenate it with our new suffix '.txt', so that for any file named dir1/videos/my_video-12.avi, this part returns my_video-12.txt.

As you can see, what we're missing is the path to the folder containing the file, which we extracted earlier.
By using the / operator, we can join pathlib.Path objects with other pathlib.Path, or as in this case, with str objects, so that the result will be a pathlib.Path object with the full path to the file on the right hand side of /. Which leaves us with dir1/videos/my_video-12.txt.

Body:
I provide a video as an input to my system, it processes the video and then it writes some information into a .txt file. How do I name the .txt file exactly the same as the video file name?

    # getting input video
    ap = argparse.ArgumentParser()
    ap.add_argument("-i", "--input", required=True,
                    help="path to input video")
    ap.add_argument("-o", "--output", required=True,
                    help="path to output video")

    args = vars(ap.parse_args())

    # capturing the video frames from input video
    vs = cv2.VideoCapture(args["input"])

    # writing the output folder and txt file

    outputfile_dir = os.path.join(os.getcwd(),'output')
    if not os.path.exists(outputfile_dir):
        os.makedirs(outputfile_dir)
        os.chmod(outputfile_dir , 0o777)
    outputFilename=os.path.join(outputfile_dir,"demofile.txt")

Body:
from pathlib import Path

def to_txt(filename: Path) -> Path:
    """Changes a filename for an arbitrary
    file to a filename with a *.txt suffix.
    """

    return filename.parent / f'{filename.stem}.txt'

filename = Path('dir1/videos/my_video-12.avi')
txt_file = to_txt(filename)
print(txt_file)

Explanation

pathlib is part of Python's standard library and provides object-oriented access to path-like objects. I.e. you can hadle file and directory paths as objects with methods and properties for common operations on those types of objects. For further details, read the docs.

What the function to_txt() does is, it takes such a path-like object, namely the path to the video file as input. It then extracts the paths to the video's parent directory by accessing the property filename.parent, which returns another pathlib.Path object to the directory containing the file. So for any file named dir1/videos/my_video-12.avi, this part returns dir1/videos.

You can access a pathlib.Path's file name without the leading directories and without its suffix via the property Path.stem.
In the f-string f'{filename.stem}.txt', we access this property and concatenate it with our new suffix '.txt', so that for any file named dir1/videos/my_video-12.avi, this part returns my_video-12.txt.

As you can see, what we're missing is the path to the folder containing the file, which we extracted earlier.
By using the / operator, we can join pathlib.Path objects with other pathlib.Path, or as in this case, with str objects, so that the result will be a pathlib.Path object with the full path to the file on the right hand side of /. Which leaves us with dir1/videos/my_video-12.txt.


问:
XDocument how can I comment an Element
I just want to know how I can comment an entire element using XDocument.</p>

```<code>XDocument doc = XDocument.Parse("<configuration>
      <connectionString>
          ...
      </connectionString>
<configuration>");

/*Something like that*/ doc.Root.Element("connectionStrings").NodeType = XComment; /*??*/
</code>```

答:
And if anyone wants to know how to do multiline:

```<code>public static  class Extensions
{
    internal static void AddMultilineComment(this XDocument xDoc, string[] lines)
    {
        var builder = new List<string> { Environment.NewLine };
        builder.AddRange(lines);
        builder.Add(Environment.NewLine);
        xDoc.Add(new XComment(string.Join(Environment.NewLine, builder)));
    }
}
</code>```

Usage:

```<code>[TestMethod]
public void TryIt()
{
    var xDoc = new XDocument();
    xDoc.AddMultilineComment(
        new string[]
        {
            "This excellent post answered my original ",
            "question, so then it seemed like a handy",
            "thing to write a multiline extension!",
        });
    xDoc.Add(
        new XElement("connectionString",
            new XAttribute("uri", $"{new Uri("https://www.ivsoftware.com")}")));
}
</code>```

Result:

Title: XDocument how can I comment an Element

Body:
I just want to know how I can comment an entire element using XDocument.

XDocument doc = XDocument.Parse("<configuration>
      <connectionString>
          ...
      </connectionString>
<configuration>");

/*Something like that*/ doc.Root.Element("connectionStrings").NodeType = XComment; /*??*/

Body:
And if anyone wants to know how to do multiline:

public static  class Extensions
{
    internal static void AddMultilineComment(this XDocument xDoc, string[] lines)
    {
        var builder = new List<string> { Environment.NewLine };
        builder.AddRange(lines);
        builder.Add(Environment.NewLine);
        xDoc.Add(new XComment(string.Join(Environment.NewLine, builder)));
    }
}

Usage:

[TestMethod]
public void TryIt()
{
    var xDoc = new XDocument();
    xDoc.AddMultilineComment(
        new string[]
        {
            "This excellent post answered my original ",
            "question, so then it seemed like a handy",
            "thing to write a multiline extension!",
        });
    xDoc.Add(
        new XElement("connectionString",
            new XAttribute("uri", $"{new Uri("https://www.ivsoftware.com")}")));
}

Result:


问:
Create specific bean dependant on property
Lets say i have two beans:

class MyBean implements BeanInterface(){}

class MyBean2 implements BeanInterface(){}

And if specific property exists, i want to create MyBean, otherwise I want to create MyBean2(). How can i do this?

```<code>@Bean
@ConditionalOnProperty(name = "property.validation")
public BeanInterface beanInterface() {
    return new MyBean();
}
</code>```

works if I want to create MyBean if property exists, but how do I create MyBean2 if it doesn't?

```<code>@Bean
@ConditionalOnMissingBean(MyBean.class)
public BeanInterface beanInterface() {
    return new MyBean2();
}
</code>```

complains that method with same name exists, and if i understand it correctly, the methods name need to be camelCase name of the bean.

How do i do this?

Thanks

//edit i tried:

```<code>@Bean
@ConditionalOnProperty(name = "property.validation")
@Order(1)
public BeanInterface beanInterface() {
    return new MyBean();
}

@Bean("beanInterface")
@ConditionalOnMissingBean(MyBean.class)
@Order(2)
public BeanInterface beanInterface() {
    return new MyBean2();
}
</code>```

but it didnt work, second bean is not getting created when property is missing.

答:
Spring and Spring boot provide a a following solution: If you need to choose one implementation of the interface at runtime, than you inject all implementations and choose appropriate one at runtime. Assuming that you have an interface DataSource with multiple implementations here is how you inject them all:

```<code>@Autowired
private List<DataSource> dataSources;
</code>```

You can read about this solution here.
This is a standard solution, but I really don't like it as it is waistful to inject all implementations. So, I wrote a feature that is available as part of MgntUtils open-source library. That feature allows you to create a static factory per each interface, and once you add any implementation of that interface declared as a Bean, that implementation will be added automatically at start up into a relevant factory. So, instead of injecting all implementations in your class you at runtime take from the factory needed implementation. I think it is much more elegant solution, and it has been battle-tested and it works well. Here is Javadoc that explains the concept and has a detailed example on how to use it: Lifecycle management. Also here is the article that describes this feature in detail: Non-intrusive access to "Orphaned" Beans in Spring framework. The library is available as Maven artifact at Maven central ad also on Github including javadoc and source code. In the source code there is a working example on how to use this feature

Body:
Lets say i have two beans:

class MyBean implements BeanInterface(){}

class MyBean2 implements BeanInterface(){}

And if specific property exists, i want to create MyBean, otherwise I want to create MyBean2(). How can i do this?

@Bean
@ConditionalOnProperty(name = "property.validation")
public BeanInterface beanInterface() {
    return new MyBean();
}

works if I want to create MyBean if property exists, but how do I create MyBean2 if it doesn't?

@Bean
@ConditionalOnMissingBean(MyBean.class)
public BeanInterface beanInterface() {
    return new MyBean2();
}

complains that method with same name exists, and if i understand it correctly, the methods name need to be camelCase name of the bean.

How do i do this?

Thanks

//edit i tried:

@Bean
@ConditionalOnProperty(name = "property.validation")
@Order(1)
public BeanInterface beanInterface() {
    return new MyBean();
}

@Bean("beanInterface")
@ConditionalOnMissingBean(MyBean.class)
@Order(2)
public BeanInterface beanInterface() {
    return new MyBean2();
}

but it didnt work, second bean is not getting created when property is missing.

Body:
Spring and Spring boot provide a a following solution: If you need to choose one implementation of the interface at runtime, than you inject all implementations and choose appropriate one at runtime. Assuming that you have an interface DataSource with multiple implementations here is how you inject them all:

@Autowired
private List<DataSource> dataSources;

You can read about this solution here.
This is a standard solution, but I really don't like it as it is waistful to inject all implementations. So, I wrote a feature that is available as part of MgntUtils open-source library. That feature allows you to create a static factory per each interface, and once you add any implementation of that interface declared as a Bean, that implementation will be added automatically at start up into a relevant factory. So, instead of injecting all implementations in your class you at runtime take from the factory needed implementation. I think it is much more elegant solution, and it has been battle-tested and it works well. Here is Javadoc that explains the concept and has a detailed example on how to use it: Lifecycle management. Also here is the article that describes this feature in detail: Non-intrusive access to "Orphaned" Beans in Spring framework. The library is available as Maven artifact at Maven central ad also on Github including javadoc and source code. In the source code there is a working example on how to use this feature


问:
Solr facet counts are not correct, how to deduplicate
We are using two solrs to index the files. Sometimes one article is indexed in both solrs because we do update. It cause a problem that the facet counts are not correct due to these duplicated articles. How can I de-duplicate the counts?</p>

答:
My advise would be not to keep duplicated articles. So you need a method to identify this duplicates articles and deleted it form one SOLR.

If you don't want to delete duplicate articles you still  need to keep track of them.
Knowing which articles from SOLR1 are duplicates in SOLR2 will help you de-duplicate the counts like this:

create an extra field in SOLR1 named :

```<code>IsDuplicateField = true, if article is duplicated in SOLR2
                 = false, otherwise
</code>```

when you do the query to SOLR1 add: IsDuplicatedField=true to facets.

when retrieving result just decrease the total number of facet counts with total number of IsDuplicateField from SOLR1.

In this situation the facet IsDuplicateField will retrieve all the articles that are duplicated and match your query.

Good luck !

Body:
My advise would be not to keep duplicated articles. So you need a method to identify this duplicates articles and deleted it form one SOLR.

If you don't want to delete duplicate articles you still  need to keep track of them.
Knowing which articles from SOLR1 are duplicates in SOLR2 will help you de-duplicate the counts like this:

create an extra field in SOLR1 named :

IsDuplicateField = true, if article is duplicated in SOLR2
                 = false, otherwise

when you do the query to SOLR1 add: IsDuplicatedField=true to facets.

when retrieving result just decrease the total number of facet counts with total number of IsDuplicateField from SOLR1.

In this situation the facet IsDuplicateField will retrieve all the articles that are duplicated and match your query.

Good luck !


问:
Invalid value for createPaymentMethod: card should be an object or element
I'm trying to create a payment method using nextJs library from stripe, like this:

```<code>import React, { FunctionComponent } from 'react';
import type { DisplaySettingsProps } from '@company/frontoffice/types';
import { Row, Col,  Input } from '@company/ui';
import { useIntl } from '@company/frontoffice/providers';

import messages from './payment.lang';

import { loadStripe } from '@stripe/stripe-js';
import {
  Elements,
  useStripe,
  useElements,
  CardElement,

} from '@stripe/react-stripe-js';

/* Make sure to call `loadStripe` outside of a component’s render to avoid. recreating the `Stripe` object on every render. */
const stripePromise = loadStripe(
  'pk_test_51JzJxAGAsaImrqUbu1pKDHiCSaq9A0sZTgpV6Li3sd8yYrCCVvPhCPfZ3i9JJ8ySgY5Uhceu6iGxlgylx2vuXBj100SpHqClA8'
);

const PaymentForm: FunctionComponent = () => {
  const stripe = useStripe();
  const elements = useElements();

  const f = useIntl();

  const handleSubmit = async (e) => {
    e.preventDefault();
    console.log('inside handleSubmit');

    if (!stripe || !elements) {
      console.log('!stripe || !elements');
      return;
    }

    const cardElement = elements.getElement(CardElement);

    /*
    Returns:
    result.paymentMethod: a PaymentMethod was created successfully.
    result.error: there was an error.
    */
    const { paymentMethod, error: backendError } = await stripe.createPaymentMethod({
      type: 'card',
      card: cardElement,
      billing_details: {
        name: 'Jenny Rosen',
      },
    });

    if (backendError) {
      console.error(backendError.message);
      return;
    }
  };

  return (
    <Elements stripe={stripePromise}>
      <form
        onSubmit={(e) => {
          console.log('handleSubmit');
          handleSubmit(e);
        }}
      >
        <Row mb={4}>
          <Col col={12}>
            <Input label={f(messages.name)} placeholder={f(messages.name)} required={true} />
          </Col>
        </Row>
        <Row>
          <Col>
            <CardElement />
          </Col>
        </Row>
        <Row>
          <button>[submit /]</button>
        </Row>
      </form>
    </Elements>
  );
};

export type StripePaymentFormProps = DisplaySettingsProps & {
  displaySettings: any /* TODO */;
};

const StripePaymentForm: FunctionComponent<StripePaymentFormProps> = () => {
  return (
    <Elements stripe={stripePromise}>
      <PaymentForm />
    </Elements>
  );
};

export default StripePaymentForm;
</code>```

Which prints out this form:

But when I hit the submit button I see this error in the developer's console:

v3:1 Uncaught (in promise) IntegrationError: Invalid value for createPaymentMethod: card should be an object or element. You specified: null.

And If I console.log(cardElement) prints out null

Any idea why?

-EDIT-

I'm experiencing the same if I split the CardElement into CardNumber, CardExpiry and CardCVC (Which is actually the way I need it)

```<code>    /* global fetch */
    import React, { FunctionComponent } from 'react';
    import type { DisplaySettingsProps } from '@company/frontoffice/types';

    import { Row, Col, Text, Image, Input } from '@company/ui';
    import { StyledInput } from './styledPayment';
    import StripeInput from './Stripeinput';
    import messages from './payment.lang';
    import { useIntl } from '@company/frontoffice/providers';

    import { loadStripe } from '@stripe/stripe-js';
    import {
      Elements,
      useStripe,
      useElements,
      CardNumberElement,
      CardCvcElement,
      CardExpiryElement,
    } from '@stripe/react-stripe-js';

    /* Make sure to call `loadStripe` outside of a component’s render to avoid. recreating the `Stripe` object on every render. */
    const stripePromise = loadStripe(
      'pk_test_51JzJxAGAsaImrqUbu1pKDHiCSaq9A0sZTgpV6Li3sd8yYrCCVvPhCPfZ3i9JJ8ySgY5Uhceu6iGxlgylx2vuXBj100SpHqClA8'
    );

    const PaymentForm: FunctionComponent = () => {
      const stripe = useStripe();
      const elements = useElements();

      const f = useIntl();

      const handleSubmit = async (e) => {
        e.preventDefault();
        console.log('inside handleSubmit');

        if (!stripe || !elements) {
          console.log('!stripe || !elements');
          return;
        }

        // what we had
        const cardNumber = elements.getElement(CardNumberElement);
        const cardCVC = elements.getElement(CardCvcElement);
        const cardExpiry = elements.getElement(CardExpiryElement);

        console.log(cardNumber, cardCVC, cardExpiry);

        const { paymentMethod, error: backendError } = await stripe.createPaymentMethod({
          type: 'card',
          card: cardNumber,
          billing_details: {
            name: 'Jenny Rosen',
          },
        });

        /* Create payment intent on server */
        const { error: backendError_, clientSecret } = await fetch('/create-payment-intent', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            paymentMethodType: 'card',
            currency: 'eur',
          }),
        }).then((r) => r.json());

        if (backendError) {
          console.error(backendError.message);
          return;
        }

        if (backendError_) {
          console.error(backendError_.message);
          return;
        }

        console.log(`clientSecret generated: ${clientSecret}`);
        // Confirm de payment on the client
        const { error: stripeError, paymentIntent, error } = await stripe.confirmCardPayment(
          clientSecret,
          {
            payment_method: {
              card: cardNumber,
            },
          }
        );

        if (stripeError) {
          console.error(stripeError.message);
          return;
        }

        console.log(`PaymentIntent ${paymentIntent.id} is ${paymentIntent.status}`);

        // what we had
        console.log(cardExpiry);
      };

      return (
        <Elements stripe={stripePromise}>
          <form
            onSubmit={(e) => {
              handleSubmit(e);
            }}
          >
            <Row mb={4}>
              <Col col={12}>
                <Input label={f(messages.name)} placeholder={f(messages.name)} required={true} />
              </Col>
            </Row>
            <Row mb={4}>
              <Col col={12}>
                <StyledInput
                  label={f(messages.number)}
                  placeholder={f(messages.number)}
                  required={true}
                  InputProps={{
                    inputComponent: StripeInput,
                    inputProps: {
                      component: CardNumberElement,
                    },
                  }}
                />
              </Col>
            </Row>

            <Row colGap={5} mb={4}>
              <Col col={[12, 6]}>
                <StyledInput
                  label={f(messages.expiry)}
                  placeholder={f(messages.expiry)}
                  required={true}
                  InputProps={{
                    inputComponent: StripeInput,
                    inputProps: {
                      component: CardExpiryElement,
                    },
                  }}
                />
              </Col>
              <Col col={[10, 5]}>
                <StyledInput
                  label={f(messages.security)}
                  placeholder="CVC"
                  required={true}
                  InputProps={{
                    inputComponent: StripeInput,
                    inputProps: {
                      component: CardCvcElement,
                    },
                  }}
                />
                <Text as="p" fontSize="xs" color="text2" mt={2}>
                  {f(messages.securitySub)}
                </Text>
              </Col>
              <Col col={[2, 1]}>
                {/* Todo - replace the scr when we receive from design (already requested) */}
                <Image
                  mt={[6, 6]}
                  display="block"
                  mx="auto"
                  width="size10"
                  maxWidth="sizeFull"
                  src="card-cvc.png"
                  alt="Credit card cvc icon"
                />
              </Col>
            </Row>
            <Row>
              <button>[submit /]</button>
            </Row>
          </form>
        </Elements>
      );
    };

    export type StripePaymentFormProps = DisplaySettingsProps & {
      displaySettings: any /* TODO */;
    };

    const StripePaymentForm: FunctionComponent<StripePaymentFormProps> = () => {
      return (
        <Elements stripe={stripePromise}>
          <PaymentForm />
        </Elements>
      );
    };

export default StripePaymentForm;
</code>```

Providing this form:

Beeing all 3 console.log's null

And the stripeinput: (just to style them)

```<code>    import React, { FunctionComponent, useRef, useImperativeHandle } from 'react';

    type StripeInputPrpps = {
      component: any; // todo type this
      inputRef: any; // todo type this
      props: any; // todo type this
    };

    const StripeInput: FunctionComponent<StripeInputPrpps> = ({
      component: Component,
      inputRef,
      ...props
    }) => {
      const elementRef = useRef();

      /* Todo - obtain this values from theme.props */
      const color = 'rgb(19, 40, 72)';
      const placeholderColor = 'rgb(137, 147, 164)';

      const inputStyle = {
        color: color,
        '::placeholder': {
          color: placeholderColor,
        },
      };

      useImperativeHandle(inputRef, () => ({
        focus: () => {
          if (elementRef && elementRef.current) {
            elementRef.current.focus;
          }
        },
      }));

      return (
        <Component
          onReady={(element) => (elementRef.current = element)}
          options={{
            style: {
              base: inputStyle,
            },
          }}
          {...props}
        />
      );
    };

    export default StripeInput;
</code>```

答:
In my case, i had a loader replacing the payment component once payment button was pressed which disrupted the stripe flow! i removed the loader , then it worked fine.

2hrs wasted successfully

Body:
I'm trying to create a payment method using nextJs library from stripe, like this:

import React, { FunctionComponent } from 'react';
import type { DisplaySettingsProps } from '@company/frontoffice/types';
import { Row, Col,  Input } from '@company/ui';
import { useIntl } from '@company/frontoffice/providers';

import messages from './payment.lang';

import { loadStripe } from '@stripe/stripe-js';
import {
  Elements,
  useStripe,
  useElements,
  CardElement,

} from '@stripe/react-stripe-js';

/* Make sure to call `loadStripe` outside of a component’s render to avoid. recreating the `Stripe` object on every render. */
const stripePromise = loadStripe(
  'pk_test_51JzJxAGAsaImrqUbu1pKDHiCSaq9A0sZTgpV6Li3sd8yYrCCVvPhCPfZ3i9JJ8ySgY5Uhceu6iGxlgylx2vuXBj100SpHqClA8'
);

const PaymentForm: FunctionComponent = () => {
  const stripe = useStripe();
  const elements = useElements();

  const f = useIntl();

  const handleSubmit = async (e) => {
    e.preventDefault();
    console.log('inside handleSubmit');

    if (!stripe || !elements) {
      console.log('!stripe || !elements');
      return;
    }

    const cardElement = elements.getElement(CardElement);

    /*
    Returns:
    result.paymentMethod: a PaymentMethod was created successfully.
    result.error: there was an error.
    */
    const { paymentMethod, error: backendError } = await stripe.createPaymentMethod({
      type: 'card',
      card: cardElement,
      billing_details: {
        name: 'Jenny Rosen',
      },
    });

    if (backendError) {
      console.error(backendError.message);
      return;
    }
  };

  return (
    <Elements stripe={stripePromise}>
      <form
        onSubmit={(e) => {
          console.log('handleSubmit');
          handleSubmit(e);
        }}
      >
        <Row mb={4}>
          <Col col={12}>
            <Input label={f(messages.name)} placeholder={f(messages.name)} required={true} />
          </Col>
        </Row>
        <Row>
          <Col>
            <CardElement />
          </Col>
        </Row>
        <Row>
          <button>[submit /]</button>
        </Row>
      </form>
    </Elements>
  );
};

export type StripePaymentFormProps = DisplaySettingsProps & {
  displaySettings: any /* TODO */;
};

const StripePaymentForm: FunctionComponent<StripePaymentFormProps> = () => {
  return (
    <Elements stripe={stripePromise}>
      <PaymentForm />
    </Elements>
  );
};

export default StripePaymentForm;

Which prints out this form:

But when I hit the submit button I see this error in the developer's console:

v3:1 Uncaught (in promise) IntegrationError: Invalid value for createPaymentMethod: card should be an object or element. You specified: null.

And If I console.log(cardElement) prints out null

Any idea why?

-EDIT-

I'm experiencing the same if I split the CardElement into CardNumber, CardExpiry and CardCVC (Which is actually the way I need it)

    /* global fetch */
    import React, { FunctionComponent } from 'react';
    import type { DisplaySettingsProps } from '@company/frontoffice/types';

    import { Row, Col, Text, Image, Input } from '@company/ui';
    import { StyledInput } from './styledPayment';
    import StripeInput from './Stripeinput';
    import messages from './payment.lang';
    import { useIntl } from '@company/frontoffice/providers';

    import { loadStripe } from '@stripe/stripe-js';
    import {
      Elements,
      useStripe,
      useElements,
      CardNumberElement,
      CardCvcElement,
      CardExpiryElement,
    } from '@stripe/react-stripe-js';

    /* Make sure to call `loadStripe` outside of a component’s render to avoid. recreating the `Stripe` object on every render. */
    const stripePromise = loadStripe(
      'pk_test_51JzJxAGAsaImrqUbu1pKDHiCSaq9A0sZTgpV6Li3sd8yYrCCVvPhCPfZ3i9JJ8ySgY5Uhceu6iGxlgylx2vuXBj100SpHqClA8'
    );

    const PaymentForm: FunctionComponent = () => {
      const stripe = useStripe();
      const elements = useElements();

      const f = useIntl();

      const handleSubmit = async (e) => {
        e.preventDefault();
        console.log('inside handleSubmit');

        if (!stripe || !elements) {
          console.log('!stripe || !elements');
          return;
        }

        // what we had
        const cardNumber = elements.getElement(CardNumberElement);
        const cardCVC = elements.getElement(CardCvcElement);
        const cardExpiry = elements.getElement(CardExpiryElement);

        console.log(cardNumber, cardCVC, cardExpiry);

        const { paymentMethod, error: backendError } = await stripe.createPaymentMethod({
          type: 'card',
          card: cardNumber,
          billing_details: {
            name: 'Jenny Rosen',
          },
        });

        /* Create payment intent on server */
        const { error: backendError_, clientSecret } = await fetch('/create-payment-intent', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            paymentMethodType: 'card',
            currency: 'eur',
          }),
        }).then((r) => r.json());

        if (backendError) {
          console.error(backendError.message);
          return;
        }

        if (backendError_) {
          console.error(backendError_.message);
          return;
        }

        console.log(`clientSecret generated: ${clientSecret}`);
        // Confirm de payment on the client
        const { error: stripeError, paymentIntent, error } = await stripe.confirmCardPayment(
          clientSecret,
          {
            payment_method: {
              card: cardNumber,
            },
          }
        );

        if (stripeError) {
          console.error(stripeError.message);
          return;
        }

        console.log(`PaymentIntent ${paymentIntent.id} is ${paymentIntent.status}`);

        // what we had
        console.log(cardExpiry);
      };

      return (
        <Elements stripe={stripePromise}>
          <form
            onSubmit={(e) => {
              handleSubmit(e);
            }}
          >
            <Row mb={4}>
              <Col col={12}>
                <Input label={f(messages.name)} placeholder={f(messages.name)} required={true} />
              </Col>
            </Row>
            <Row mb={4}>
              <Col col={12}>


问:
How to select from list and click submit button then go to link "in HTML"
I found this code for my project. I want to change this to open website with click on submit button

```<code><html>
<body>
<form action="/action_page.php" method="get">
  <label for="cars">Choose a Site:</label>
  <select id="site" name="site">
    <option value="Google">Google</option>
    <option value="Yahoo">Yahoo</option>
    <option value="MSN">MSN</option>
  </select>
  <input type="submit">
</form>
</body>
</html>
</code>```

for example: when select "Google" from list, with click on "submit" button open "www.google.com" that exist on "action_page.php"

I dont have "action_page.php" code

答:
Firstly, I modified your html code:

```<code><html>
<body>
<form method="get">
  <label for="cars">Choose a Site:</label>
  <select id="site" name="site">
    <option value="Google">Google</option>
    <option value="Yahoo">Yahoo</option>
    <option value="MSN">MSN</option>
  </select>
</form>
<button type="button" id="button" >Submit</button>

<script src="script1.js"></script>
</body>
</html>
</code>```

Made a button outside of the form and referenced the external js file script1.js

Then I created the js file and added this code to it:

var select = document.getElementById('site');

document.getElementById("button").onclick = function(){
    var value = select.value
    if (value == "Google")
    {
        window.location.href = "https://www.google.com/";
    }
    else if (value == "Yahoo")
    {
        window.location.href = "https://www.yahoo.com/";
    }
    else if (value == "MSN")
    {
        window.location.href = "https://www.msn.com/";
    }
};
```

It finds the select tag and the button from the html script, checks if the button was pressed and redirects to the corresponding website based on the dropdown selection.

Body:
I found this code for my project. I want to change this to open website with click on submit button

<form action="/action_page.php" method="get">
  Choose a Site:
  <select id="site" name="site">
    <option value="Google">Google</option>
    <option value="Yahoo">Yahoo</option>
    <option value="MSN">MSN</option>
  </select>
  <input type="submit">
</form>

for example: when select "Google" from list, with click on "submit" button open "www.google.com" that exist on "action_page.php"

I dont have "action_page.php" code

Body:
Firstly, I modified your html code:

<html>
<body>
<form method="get">
  <label for="cars">Choose a Site:</label>
  <select id="site" name="site">
    <option value="Google">Google</option>
    <option value="Yahoo">Yahoo</option>
    <option value="MSN">MSN</option>
  </select>
</form>
<button type="button" id="button" >Submit</button>

<script src="script1.js"></script>
</body>
</html>

Made a button outside of the form and referenced the external js file script1.js

Then I created the js file and added this code to it:

var select = document.getElementById('site');

document.getElementById("button").onclick = function(){
    var value = select.value
    if (value == "Google")
    {
        window.location.href = "https://www.google.com/";
    }
    else if (value == "Yahoo")
    {
        window.location.href = "https://www.yahoo.com/";
    }
    else if (value == "MSN")
    {
        window.location.href = "https://www.msn.com/";
    }
};

It finds the select tag and the button from the html script, checks if the button was pressed and redirects to the corresponding website based on the dropdown selection.


问:
Please help to translate code Pascal to JS?
I have task: On a sheet of paper, a rectangle is drawn along the grid lines. After that, the number of grid nodes located inside, but not on the border of the rectangles, and the number of single grid segments inside the rectangle were counted. Write a program that uses this data to determine the size of a rectangle.

I have this code in Pascal:

```<code>var
K,N,i,j:integer;
begin
readln(K,N);
for i:=1 to trunc(sqrt(K)) do
if K mod i = 0 then
begin
if i*(K div i+1)+(K div i)*(i+1)=N then writeln(i+1,' ',K div i+1);
end;
end.
</code>```

And this my code in JavaScript:

const a = [1000, 2065]

function Sum(K, N) {
  for (i = 1; i < Math.trunc(Math.sqrt(K)); i++) {
    if (K % i === 0 && i * (Math.floor(K / (i) + 1) + Math.floor(K / i) * (i + 1)) === N) {
      break;
    }
  }
  console.log(i + 1, Math.floor(K / (i)) + 1)
}
Sum(a[0], a[1]);```

Can you help why my answers in JavaScript are wrong?

答:
Not exactely sure what you're trying to achieve but this javascript code produces the same output (26, 41) as your pascal version does:

See onlinegdb.com!

const K = 1000, N = 2065;
for (let i=1; i<Math.trunc(Math.sqrt(K)); i++)
  if (K % i === 0)
    if (i*(K / i+1)+(K / i)*(i+1) === N)
        console.log(i+1, K / i+1);```

I think you have messed something up with the brackets in Math.floor or something similar.

Body:
I have task: On a sheet of paper, a rectangle is drawn along the grid lines. After that, the number of grid nodes located inside, but not on the border of the rectangles, and the number of single grid segments inside the rectangle were counted. Write a program that uses this data to determine the size of a rectangle.

I have this code in Pascal:

var
K,N,i,j:integer;
begin
readln(K,N);
for i:=1 to trunc(sqrt(K)) do
if K mod i = 0 then
begin
if i*(K div i+1)+(K div i)*(i+1)=N then writeln(i+1,' ',K div i+1);
end;
end.

And this my code in JavaScript:

const a = [1000, 2065]

function Sum(K, N) {
  for (i = 1; i < Math.trunc(Math.sqrt(K)); i++) {
    if (K % i === 0 && i * (Math.floor(K / (i) + 1) + Math.floor(K / i) * (i + 1)) === N) {
      break;
    }
  }
  console.log(i + 1, Math.floor(K / (i)) + 1)
}
Sum(a[0], a[1]);

Can you help why my answers in JavaScript are wrong?

Body:
Not exactely sure what you're trying to achieve but this javascript code produces the same output (26, 41) as your pascal version does:

See onlinegdb.com!

const K = 1000, N = 2065;
for (let i=1; i<Math.trunc(Math.sqrt(K)); i++)
  if (K % i === 0)
    if (i*(K / i+1)+(K / i)*(i+1) === N)
        console.log(i+1, K / i+1);

I think you have messed something up with the brackets in Math.floor or something similar.


问:
Invalid object name 'sys.dm_exec_input_buffer'
I'm trying to start a script in SQL Server 2014, but it can't find the object in question.

This is the query I am trying to initiate:

```<code>SELECT * FROM sys.dm_exec_input_buffer(@@SPID, NULL);
</code>```

Error message:

Msg 208, Level 16, State 1, Line 1

Invalid object name 'sys.dm_exec_input_buffer'.

答:
You need to be on at least Service Pack 2. If you're on an earlier service pack, it's time to patch.

Here's a link to Service Pack 3

Here's a link to the most recent update for SP3

Please apply both, in that order.

Body:
I'm trying to start a script in SQL Server 2014, but it can't find the object in question.

This is the query I am trying to initiate:

SELECT * FROM sys.dm_exec_input_buffer(@@SPID, NULL);

Error message:

Msg 208, Level 16, State 1, Line 1

Invalid object name 'sys.dm_exec_input_buffer'.


问:
Which is better to use: $arrayName['literal'] or $arrayName[literal]?
Both are working fine. I'm just curious how php parse the two. Do they have difference on speed, efficiency, etc. Why does php allow us to use both?</p>

答: $arrayName[literal] is bad because if you have constant named literal, you'll get unexpected results. When it's no constant named literal, php transforms literal to string 'literal'</p>


问:
Output variables of Lambda function as Cloudformation parameters in Codepipeline
I have a Codepipeline, and I am trying to pass the output variables of a Lambda function as a parameter of the next stage, a Cloudformation action, in this pipeline. Does anyone know if it can be done?</p>

答: I found a way. I used a Lambda function to create my Cloudformation stack. The User parameters of this Lambda are the output variables of the previous Lambda, and can be inserted as parameters to the Cloudformation stack.</p>


问:
pulsar-client couldn't be installed
I cannot install pulsar-client as it is mentioned in the documentation at all:

```<code>pip3 install pulsar-client
</code>```

Collecting pulsar-client ERROR: Could not find a version that
  satisfies the requirement pulsar-client (from versions: none) ERROR:
  No matching distribution found for pulsar-client

```<code>pip3 install pulsar-client==2.4.0
</code>```

Collecting pulsar-client==2.4.0 ERROR: Could not find a version that
  satisfies the requirement pulsar-client==2.4.0 (from versions: none)
  ERROR: No matching distribution found for pulsar-client==2.4.0

I am on Windows 10, python 3 version.

tried both python 2 and 3 versions.

答:
You may need to build the C++ client if you are on an unusual platform.  More platforms have support for the pre-built Python.

We are on 2.10.0 now and the client works in more environments.

If you can't use the Python client, you can try Go, Java, C#, or others.

Pulsar clusters can also accept MQTT, Kafka, Websockets, and other protocols if you need to.

https://pulsar.apache.org/docs/en/client-libraries/

https://github.com/tspannhw/SpeakerProfile

Title: pulsar-client couldn't be installed

Body:
I cannot install pulsar-client as it is mentioned in the documentation at all:

pip3 install pulsar-client

Collecting pulsar-client ERROR: Could not find a version that
  satisfies the requirement pulsar-client (from versions: none) ERROR:
  No matching distribution found for pulsar-client

pip3 install pulsar-client==2.4.0

Collecting pulsar-client==2.4.0 ERROR: Could not find a version that
  satisfies the requirement pulsar-client==2.4.0 (from versions: none)
  ERROR: No matching distribution found for pulsar-client==2.4.0

I am on Windows 10, python 3 version.

tried both python 2 and 3 versions.


问:
Azure Monitor Workbook Query - retrieve data from Azure REST API Synapse Data Plane
trying to build a Workbook retrieving data from Azure REST API about Synapse Pipelines, which belongs to another endpoint (https://dev.azuresynapse.net) not like Azure Resource Manager API (https://management.azure.com). In Monitor Workbook query there is a special data source "Azure Resource Manager" for Azure RM API, which works perfectly for me since an authentication/authorization is built-in (works in background). However for Synapse Data Plane API (because of another endpoint) is usage of "Custom Endpoint" query data source eventually required. Here the bearer (access) token has to be requested beforehand separately from https://login.microsoftonline.com/{tenantId}/oauth2/token. If I try to implement it through a separate Query it doesn't work because of CORS (see picture attached), not supported by login.microsoftonline.com (the request works probably via AJAX).The same construct for Synapse works very well in Postman.
Can anyone please tell me how can I implement such API Request in the Workbook?

Regards
Ivan

access token request Query (Error message)

答:
I have found a workaround to retrieve the configuration data from synapse workspace (triggers, pipelines, linkedServices etc.) using Azure Monitor Workbook custom endpoint (query data source). It is applicable only if your synapse workspace linked to git via Azure DevOps service. In this case you can grab the config information relevant to production environment using Azure DevOps API as follows:

https://dev.azure.com/{organization}/_apis/git/repositories/{repositoryId}/items?scopePath={Path}/TemplateForWorkspace.json&version=workspace_publish&download=true&api-version=6.0&Authorization Basic=BASE64PATSTRING

for that purpose you have to issue a token on the DevOps side. CORS policies are not a problem for such request as it is GET not PUT one


问:
onLongPress is not working same as onClick
I am passing onLongPress on a Component that has the same function as onClick. I have used useState for both. When I long press the item it opens the menu but again if I Long press the menu stays open.

     const resetNavItems = () => {
            setIsFirstComponentOpen(false);
            setIsSecondComponentOpen(false);
        }

    const onClickItem = useCallback(index => {
        resetNavItems();

        if (index === 2) {
            setIsFirstComponentOpen(!FirstComponentOpen);
        } else if (index === 3) {
            setIsSecondComponentOpen(!SecondComponentOpen);
        }
    });

    <TouchableOpacity onLongPress={onClickItem} />
```

答:
Your opposite of !isMembersTrayOpen and !isMoreTrayOpen will always be true because your resetNavItems is called to always set it to false. You could try:

```<code>const [FirstComponentOpen, setIsFirstComponentOpen] = useState(false)
const [SecondComponentOpen, setIsSecondComponentOpen] = useState(false)

const onClickItem = useCallback(index => {
  index === 2 ? setIsFirstComponentOpen(true) : setIsFirstComponentOpen(false)
  index === 3 ? setIsSecondComponentOpen(true) : setIsSecondComponentOpen(false)
})

<TouchableOpacity onLongPress={onClickItem} />
</code>```

if you remove resetNavItems then your original conditions would likely work:

```<code>const onClickItem = useCallback(index => {
  if (index === 2) setIsFirstComponentOpen(!FirstComponentOpen);
  if (index === 3) setIsSecondComponentOpen(!SecondComponentOpen);
}
</code>```

Body:
Your opposite of !isMembersTrayOpen and !isMoreTrayOpen will always be true because your resetNavItems is called to always set it to false. You could try:

const [FirstComponentOpen, setIsFirstComponentOpen] = useState(false)
const [SecondComponentOpen, setIsSecondComponentOpen] = useState(false)

const onClickItem = useCallback(index => {
  index === 2 ? setIsFirstComponentOpen(true) : setIsFirstComponentOpen(false)
  index === 3 ? setIsSecondComponentOpen(true) : setIsSecondComponentOpen(false)
})

<TouchableOpacity onLongPress={onClickItem} />

if you remove resetNavItems then your original conditions would likely work:

const onClickItem = useCallback(index => {
  if (index === 2) setIsFirstComponentOpen(!FirstComponentOpen);
  if (index === 3) setIsSecondComponentOpen(!SecondComponentOpen);
}


问:
Im trying to create a a code that count numbers divisible by 9 by putting numbers into an array and count the numbers in it
Im trying to create a a code that count numbers divisible by 9 by putting numbers into  an array and count the numbers in it but it only prints 1 instead of the number of numbers divisible by 9 please help me i want to use array to count those numbers</p>
```<code>#include <iostream>
using namespace std;
int main(){
    int a,b,i;
    int numbers[]={i};
    cin >>a>>b;
    for (i=a; i<=b; i++)
        if (i%9==0){
            cout << sizeof(numbers)/sizeof(numbers[0]);
        }
}
</code>```

答:
This declaration

```<code>int numbers[]={i};
</code>```

declares an array with only one element and initializes it with an indeterminate value stored in the variable i because the variable i was not initialized.

The body of this if statement

```<code>    if (i%9==0){
        cout << sizeof(numbers)/sizeof(numbers[0]);
    }
</code>```

does not make a sense because it always outputs the number of elements in the array numbers that has only one element. But according to the description of the assignment you have to place numbers divisible by 9 into the array.

As the user can enter arbitrary values for the variables a and b then it means that you need a variable length array. However variable length arrays is not a standard C++ feature. Instead you should use the standard container std::vector.

The program can look the following way

```<code>#include <iostream>
#include <vector>
#include <utility>

int main()
{
    int a = 0, b = 0;
    std::vector<int> numbers;

    const int divisor = 9;

    std::cout << "Enter two integer numbers: ";
    std::cin >> a >> b;

    if ( b < a ) std::swap( a, b );

    for ( int i = a; not ( b < i ); ++i )
    {
        if ( i % divisor == 0 ) numbers.push_back( i );
    }

    std::cout << "There are " << numbers.size()
              << " numbers divisible by " << divisor
              << " in the range [" << a << ", " << b << "]\n";

    if ( numbers.size() != 0 )
    {
        std::cout << "They are ";

        for ( const auto &n : numbers )
        {
            std::cout << n << ' ';
        }

        std::cout << '\n';
    }
}
</code>```

Body:
Im trying to create a a code that count numbers divisible by 9 by putting numbers into  an array and count the numbers in it but it only prints 1 instead of the number of numbers divisible by 9 please help me i want to use array to count those numbers

#include <iostream>
using namespace std;
int main(){
    int a,b,i;
    int numbers[]={i};
    cin >>a>>b;
    for (i=a; i<=b; i++)
        if (i%9==0){
            cout << sizeof(numbers)/sizeof(numbers[0]);
        }
}

Body:
This declaration

int numbers[]={i};

declares an array with only one element and initializes it with an indeterminate value stored in the variable i because the variable i was not initialized.

The body of this if statement

    if (i%9==0){
        cout << sizeof(numbers)/sizeof(numbers[0]);
    }

does not make a sense because it always outputs the number of elements in the array numbers that has only one element. But according to the description of the assignment you have to place numbers divisible by 9 into the array.

As the user can enter arbitrary values for the variables a and b then it means that you need a variable length array. However variable length arrays is not a standard C++ feature. Instead you should use the standard container std::vector.

The program can look the following way

#include <iostream>
#include <vector>
#include <utility>

int main()
{
    int a = 0, b = 0;
    std::vector<int> numbers;

    const int divisor = 9;

    std::cout << "Enter two integer numbers: ";
    std::cin >> a >> b;

    if ( b < a ) std::swap( a, b );

    for ( int i = a; not ( b < i ); ++i )
    {
        if ( i % divisor == 0 ) numbers.push_back( i );
    }

    std::cout << "There are " << numbers.size()
              << " numbers divisible by " << divisor
              << " in the range [" << a << ", " << b << "]\n";

    if ( numbers.size() != 0 )
    {
        std::cout << "They are ";

        for ( const auto &n : numbers )
        {
            std::cout << n << ' ';
        }

        std::cout << '\n';
    }
}


问:
How can I make JavaScript code more "clean"
I have made this functions

```<code>
let buttonOne = true;
    let buttonTwo = false;
    let buttonThree = false;
    let buttonFour = false;
    let buttonFive = false;

    const handleButtonOne = () => {
        buttonOne = true;
        buttonTwo = false;
        buttonThree = false;
        buttonFour = false;
        buttonFive = false;
    };

    const handleButtonTwo = () => {
        buttonTwo = true;
        buttonOne = false;
        buttonThree = false;
        buttonFour = false;
        buttonFive = false;
    };

    const handleButtonThree = () => {
        buttonTwo = false;
        buttonOne = false;
        buttonThree = true;
        buttonFour = false;
        buttonFive = false;
    };

    const handleButtonFour = () => {
        buttonTwo = false;
        buttonOne = false;
        buttonThree = false;
        buttonFour = true;
        buttonFive = false;
    };

    const handleButtonFive = () => {
        buttonTwo = false;
        buttonOne = false;
        buttonThree = false;
        buttonFour = false;
        buttonFive = true;
    };

</code>```

This functions are to change the state of the different buttons and show different content to the user when the state of button is true. This works well, however, I thinks it's not the right way to do it.

My question is. How can I do the same with less code and more elegant way? Any tips?

答:
If you have only one button with true as value, you could store only the number of the button, which is set (to true).

For switching some indicators iterate the coutn of buttons and set the one which matches to the wanted style and all other to a differen unselected style.

function setButton(event) {
    const targetElement = event.target;
    button = +targetElement.value;
    for (let i = 0; i < 5; i++)
    document.getElementById(`button${i}`).style.backgroundColor = i === button
        ? '#ff7070'
        : '#dddddd'
}

let button = undefined;

for (let i = 0; i < 5; i++)
    document.getElementById(`button${i}`).addEventListener('click', setButton, false);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="button0" value="0">one</button>
<button id="button1" value="1">two</button>
<button id="button2" value="2">three</button>
<button id="button3" value="3">four</button>
<button id="button4" value="4">five</button></code>```

Body:
I have made this functions

let buttonOne = true;
    let buttonTwo = false;
    let buttonThree = false;
    let buttonFour = false;
    let buttonFive = false;

    const handleButtonOne = () => {
        buttonOne = true;
        buttonTwo = false;
        buttonThree = false;
        buttonFour = false;
        buttonFive = false;
    };

    const handleButtonTwo = () => {
        buttonTwo = true;
        buttonOne = false;
        buttonThree = false;
        buttonFour = false;
        buttonFive = false;
    };

    const handleButtonThree = () => {
        buttonTwo = false;
        buttonOne = false;
        buttonThree = true;
        buttonFour = false;
        buttonFive = false;
    };

    const handleButtonFour = () => {
        buttonTwo = false;
        buttonOne = false;
        buttonThree = false;
        buttonFour = true;
        buttonFive = false;
    };

    const handleButtonFive = () => {
        buttonTwo = false;
        buttonOne = false;
        buttonThree = false;
        buttonFour = false;
        buttonFive = true;
    };

This functions are to change the state of the different buttons and show different content to the user when the state of button is true. This works well, however, I thinks it's not the right way to do it.

My question is. How can I do the same with less code and more elegant way? Any tips?

Body:
If you have only one button with true as value, you could store only the number of the button, which is set (to true).

For switching some indicators iterate the coutn of buttons and set the one which matches to the wanted style and all other to a differen unselected style.

function setButton(event) {
    const targetElement = event.target;
    button = +targetElement.value;
    for (let i = 0; i < 5; i++)
    document.getElementById(`button${i}`).style.backgroundColor = i === button
        ? '#ff7070'
        : '#dddddd'
}

let button = undefined;

for (let i = 0; i < 5; i++)
    document.getElementById(`button${i}`).addEventListener('click', setButton, false);

<button id="button0" value="0">one</button>
<button id="button1" value="1">two</button>
<button id="button2" value="2">three</button>
<button id="button3" value="3">four</button>
<button id="button4" value="4">five</button>


问:
How to convert an integer to a list of bits?
I'm trying to represent an integer as a list of bits and left pad it to 8 bits only if the integer is < 128:

Example input: 0x15
Desired output: [0, 0, 0, 1, 0, 1, 0, 1]
```
<p>I do it in the following way:</p>
```input = 0x15
output = deque([int(i) for i in list(bin(input))[2:]])
while len(output) != 8:
    output.appendleft(0)
```
<p>I would like to convert any integer to a binary-list. Pad to 8 only if the number requires less than 8 bits to represent.</p>
<pre class="lang-none prettyprint-override"><code>Another Example input: 0x715
Desired output: [1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1]
</code>```

How can I do this both for numbers less then 8 bits and also for larger ones?

答:
I use bitmasks far less than I used to, but when I do use them I often have the need to decompose a value into its parts

```<code>def get_Bits(number):
i = 1
list_of_hex = []
while (i <= number):
    if ((number & i) > 0):
        bitRepresentation = hex(i)
        list_of_hex.append(bitRepresentation)

    i = i*2

return list_of_hex
</code>```

you can change the (hex) function to (bin) if you need the binary decomposition

Body:
I'm trying to represent an integer as a list of bits and left pad it to 8 bits only if the integer is < 128:

Example input: 0x15
Desired output: [0, 0, 0, 1, 0, 1, 0, 1]

I do it in the following way:

input = 0x15
output = deque([int(i) for i in list(bin(input))[2:]])
while len(output) != 8:
    output.appendleft(0)

I would like to convert any integer to a binary-list. Pad to 8 only if the number requires less than 8 bits to represent.

Another Example input: 0x715
Desired output: [1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1]

How can I do this both for numbers less then 8 bits and also for larger ones?

Body:
I use bitmasks far less than I used to, but when I do use them I often have the need to decompose a value into its parts

def get_Bits(number):
i = 1
list_of_hex = []
while (i <= number):
    if ((number & i) > 0):
        bitRepresentation = hex(i)
        list_of_hex.append(bitRepresentation)

    i = i*2

return list_of_hex

you can change the (hex) function to (bin) if you need the binary decomposition


问:
Postgres for loop doesn't work with cursor?
I have a simple PostgreSQL script and try to run the for loop with cursor to fetch rows as pagination:

```<code>begin;
declare curs cursor for select id from postgres.core.security_group order by id asc;
fetch 4 from curs;
commit;
</code>```

Working fine, but when I add a for loop to it, won't work:

```<code>CREATE OR REPLACE FUNCTION postgres.core.cursor_selection()
    RETURNS SETOF varchar AS
$func$
DECLARE
    curs cursor for select * from postgres.core.security_group;
    _modules varchar;  -- assuming data type integer
BEGIN
    FOR _modules IN SELECT * FROM postgres.core.security_group ORDER BY id limit 10
        LOOP
            RETURN NEXT _modules;
        END LOOP;
END
$func$  LANGUAGE plpgsql;

SELECT postgres.core.cursor_selection();
</code>```

I have the loop not working properly and not showing more data other than the first 10 records. How do I get the data as a set of 10s on each page?
Much appreciated.

答:
Functions in plpgsql don't stream.  RETURN NEXT kind of looks like it streams via co-routine or something, but it really just accumulates all the rows until the end of the function and returns them at once.

And SQL doesn't have any looping constructs.  Neither does psql (in a user-visible way) that I can find.  So there is no way to do it just in SQL or with psql.  But in psql, you can set FETCH_COUNT, which uses a cursor and FETCH behind the scenes.  (If you set log_statement=all, you can see this in action in the log file.)  If you really want do it manually for some reason, you could use \watch as an infinite loop.

```<code>begin;
declare curs cursor for select id from postgres.core.security_group order by id asc;
fetch 4 from curs \watch 0.1
commit;
</code>```

You will have to break out of the loop yourself once it finishes or you get tired of it, like with ctrl-C (on Linux)

The usual way to use a cursor in SQL would be in some other programming language with a db driver, like python or JS or Java or Perl.  But they too will usually have settings where the driver uses cursors behind the scenes without you needing to manually implement it. (like psycopg2's "named cursors" do)

Body:
I have a simple PostgreSQL script and try to run the for loop with cursor to fetch rows as pagination:

begin;
declare curs cursor for select id from postgres.core.security_group order by id asc;
fetch 4 from curs;
commit;

Working fine, but when I add a for loop to it, won't work:

CREATE OR REPLACE FUNCTION postgres.core.cursor_selection()
    RETURNS SETOF varchar AS
$func$
DECLARE
    curs cursor for select * from postgres.core.security_group;
    _modules varchar;  -- assuming data type integer
BEGIN
    FOR _modules IN SELECT * FROM postgres.core.security_group ORDER BY id limit 10
        LOOP
            RETURN NEXT _modules;
        END LOOP;
END
$func$  LANGUAGE plpgsql;

SELECT postgres.core.cursor_selection();

I have the loop not working properly and not showing more data other than the first 10 records. How do I get the data as a set of 10s on each page?
Much appreciated.

Body:
Functions in plpgsql don't stream.  RETURN NEXT kind of looks like it streams via co-routine or something, but it really just accumulates all the rows until the end of the function and returns them at once.

And SQL doesn't have any looping constructs.  Neither does psql (in a user-visible way) that I can find.  So there is no way to do it just in SQL or with psql.  But in psql, you can set FETCH_COUNT, which uses a cursor and FETCH behind the scenes.  (If you set log_statement=all, you can see this in action in the log file.)  If you really want do it manually for some reason, you could use \watch as an infinite loop.

begin;
declare curs cursor for select id from postgres.core.security_group order by id asc;
fetch 4 from curs \watch 0.1
commit;

You will have to break out of the loop yourself once it finishes or you get tired of it, like with ctrl-C (on Linux)

The usual way to use a cursor in SQL would be in some other programming language with a db driver, like python or JS or Java or Perl.  But they too will usually have settings where the driver uses cursors behind the scenes without you needing to manually implement it. (like psycopg2's "named cursors" do)


问:
Grabbing MySQL counts from loosely related tables with complex structure
MySQL here. I have the following data model in a Q&A database:

```<code>[questions]
===
question_id : PK           # ex: 12345
question_value : VARCHAR   # ex: 'What is your favorite food?'

[answers]
===
answer_id : PK              # ex: 23456
question_id : FK            # points to a questions.question_id
answer_value : VARCHAR      # ex: 'Pizza', 'French Fries', etc.

[user_answers]
===
user_answer_id : PK         # ex: 34567
question_id : FK            # points to a questions.question_id
user_answer_value : VARCHAR # ex: 'Pizza', 'French Fries', etc.
</code>```

...where [questions] is a table containing all the questions I will ask users, [answers] is a table containing all the possible answers for each question, and [user_answers] are the actual answers users give for a particular question. So the application uses [questions] and [answers] to present a user with a question & possible answers, then the user selects one of those answers, and that result gets written to the [user_answers] table.

One very important thing to note is that the application will guarantee that there are never any "orphaned" [user_answers], meaning, there will always be an [answers] record whose [answer_value] matches a [user_answers.user_answer_value]. So if there is a [user_answers.user_answer_value] in the database under a particular question_id, there will always be a matching [answers.answer_value]. Hence it is safe to match to the two "value fields" against each other in a query and not lose any data.

I realize this is not a great data model. But it is critical to point out that I simply cannot change it; its locked in and beyond my ability to make changes to, I'm simply stuck with it. And so unfortunately as much as I will want to, I cannot accept any answers that require changes to the data model.

Now then, I am trying to write a SQL query that -- for a given question_id -- returns the following columns:

the answers.answer_id as id

the answers.answer_value as answer

a count of how many user_answers existed for that particular answers.answer_id, using the value fields as a way of determining the match (i.e. "'Pizza' == 'Pizza'"), as popularity

So using the "favorite food" example from above, say that was the only question in the database, and the three possible answers were "Pizza", "French Fries" and "Cheeseburgers". Say 50 users had answered "Pizza", 65 users had answered "French Fries", and 12 users had answered "Cheeseburgers". Then the query would return results like so:

```<code>id      |     answer      |   popularity
==========================================
123     |   Pizza         |   50
456     |   French Fries  |   65
789     |   Cheeseburgers |   12
</code>```

Important to note: if an answer has never been selected by any user yet, then its count should be zero (0).

My best attempt so far at this query is:

```<code>SELECT
  a.answer_id as id,
  a.answer_value as answer,
  count(ua.answer_id) as popularity
FROM
  answers a
INNER JOIN
  user_answers ua
ON
  a.question_id = ua.question_id
WHERE
  a.question_id = ?   # provided by application
  AND
  a.answer_value = ua.answer_value
</code>```

However this doesn't look right to me. For one I don't believe an INNER JOIN is appropriate. I also believe I need to do a GROUP BY but I'm unsure of which table/column to group the count by.

Its important to note that in reality there will be hundreds of questions in this DB, each with 4 - 8 answers, and there will be hundreds (possibly thousands) of users providing answers, so its important that this query (which provides popularity counts for each question's answer) only include counts for user answers matching answers that are tied to the same "parent" question ID. Can anyone spot where I'm going awry?

答:
This will work for your requirement</p>
```<code>select a.answer_id as id,a.answer_value as answer,count(user_answer_value) as popularity from user_answers ua
join answers a on a.answer_id = ua.user_answer_value where a.question_id= 1
group by a.answer_id, a.answer_value order by count(user_answer_value) desc
</code>```

Body:
MySQL here. I have the following data model in a Q&A database:

[questions]
===
question_id : PK           # ex: 12345
question_value : VARCHAR   # ex: 'What is your favorite food?'

[answers]
===
answer_id : PK              # ex: 23456
question_id : FK            # points to a questions.question_id
answer_value : VARCHAR      # ex: 'Pizza', 'French Fries', etc.

[user_answers]
===
user_answer_id : PK         # ex: 34567
question_id : FK            # points to a questions.question_id
user_answer_value : VARCHAR # ex: 'Pizza', 'French Fries', etc.

...where [questions] is a table containing all the questions I will ask users, [answers] is a table containing all the possible answers for each question, and [user_answers] are the actual answers users give for a particular question. So the application uses [questions] and [answers] to present a user with a question & possible answers, then the user selects one of those answers, and that result gets written to the [user_answers] table.

One very important thing to note is that the application will guarantee that there are never any "orphaned" [user_answers], meaning, there will always be an [answers] record whose [answer_value] matches a [user_answers.user_answer_value]. So if there is a [user_answers.user_answer_value] in the database under a particular question_id, there will always be a matching [answers.answer_value]. Hence it is safe to match to the two "value fields" against each other in a query and not lose any data.

I realize this is not a great data model. But it is critical to point out that I simply cannot change it; its locked in and beyond my ability to make changes to, I'm simply stuck with it. And so unfortunately as much as I will want to, I cannot accept any answers that require changes to the data model.

Now then, I am trying to write a SQL query that -- for a given question_id -- returns the following columns:

the answers.answer_id as id

the answers.answer_value as answer

a count of how many user_answers existed for that particular answers.answer_id, using the value fields as a way of determining the match (i.e. "'Pizza' == 'Pizza'"), as popularity

So using the "favorite food" example from above, say that was the only question in the database, and the three possible answers were "Pizza", "French Fries" and "Cheeseburgers". Say 50 users had answered "Pizza", 65 users had answered "French Fries", and 12 users had answered "Cheeseburgers". Then the query would return results like so:

id      |     answer      |   popularity
==========================================
123     |   Pizza         |   50
456     |   French Fries  |   65
789     |   Cheeseburgers |   12

Important to note: if an answer has never been selected by any user yet, then its count should be zero (0).

My best attempt so far at this query is:

SELECT
  a.answer_id as id,
  a.answer_value as answer,
  count(ua.answer_id) as popularity
FROM
  answers a
INNER JOIN
  user_answers ua
ON
  a.question_id = ua.question_id
WHERE
  a.question_id = ?   # provided by application
  AND
  a.answer_value = ua.answer_value

However this doesn't look right to me. For one I don't believe an INNER JOIN is appropriate. I also believe I need to do a GROUP BY but I'm unsure of which table/column to group the count by.

Its important to note that in reality there will be hundreds of questions in this DB, each with 4 - 8 answers, and there will be hundreds (possibly thousands) of users providing answers, so its important that this query (which provides popularity counts for each question's answer) only include counts for user answers matching answers that are tied to the same "parent" question ID. Can anyone spot where I'm going awry?

Body:
This will work for your requirement

select a.answer_id as id,a.answer_value as answer,count(user_answer_value) as popularity from user_answers ua
join answers a on a.answer_id = ua.user_answer_value where a.question_id= 1
group by a.answer_id, a.answer_value order by count(user_answer_value) desc


问:
How to return values from C/++ functions correctly?
I have made some app and the method im using is this:

```<code>INT name(char *one,char *two,char buffer[]){
memcpy(buffer,"omg",4);//or using std::string::copy ... that's how I actually return value
...}
</code>```

and I call it like:

```<code>char returned[255];
name(first,second,returned);
printf/cout;
</code>```

Everything is fine. Now my question is, is this method terrible or a disaster? Also, what is going on with allocated memory for 255 chars, I mean is there a way to re-allocate it somehow to save memory a little?

This is so called pass-by-reference, in either case I have to return multiple values (from 2 to 10). If I would need only 1 I would use return buffer with static type I guess.

Thanks. Write your favourite methods please while I read similar questions to this one hehe.

答:
For C you should pass the size of the buffer along with the pointer to it. Passing an array as a param reduces it to a pointer, which does not contain any information about the size of the memory it points to. Something like this:

```<code>int name(char *one, char *two, char *buffer, size_t len);
</code>```

and call it like this:

```<code>char returned[255];
int result = name("one", "two", returned, sizeof returned);
</code>```

For C++ you should use std::string which takes care of it all for you, like others have said.

Body:
I have made some app and the method im using is this:

INT name(char *one,char *two,char buffer[]){
memcpy(buffer,"omg",4);//or using std::string::copy ... that's how I actually return value
...}

and I call it like:

char returned[255];
name(first,second,returned);
printf/cout;

Everything is fine. Now my question is, is this method terrible or a disaster? Also, what is going on with allocated memory for 255 chars, I mean is there a way to re-allocate it somehow to save memory a little?

This is so called pass-by-reference, in either case I have to return multiple values (from 2 to 10). If I would need only 1 I would use return buffer with static type I guess.

Thanks. Write your favourite methods please while I read similar questions to this one hehe.

Body:
For C you should pass the size of the buffer along with the pointer to it. Passing an array as a param reduces it to a pointer, which does not contain any information about the size of the memory it points to. Something like this:

int name(char *one, char *two, char *buffer, size_t len);

and call it like this:

char returned[255];
int result = name("one", "two", returned, sizeof returned);

For C++ you should use std::string which takes care of it all for you, like others have said.


问:
JMeter: Oauth 2.0 Token Generation- Getting Timed Out
I am trying to do API Testing by JMeter in two steps:

1. Generate Acess Token

Here, the authentication request is getting timed out.

Authentication Type: OAuth2.0
Grant Type- Client Credentials

I am passing the token URL and grant_type, client_id and client_secret in the Parameters section like this:

But I am getting the following error:

2. Hit the API with the fetched token
I am able to hit this with a token generated from POSTMAN.
Also in POSTMAN, I am able to authenticate properly. I tried recording the POSTMAN script but the authentication flow is not getting recorded. Just the GET API is working.

Is there any way to get the token in JMeter? or any other workaround?

答:
Given you send the same requests you should get the same responses so capture the requests originating from JMeter and Postman using an external sniffer tool like Fiddler or Wireshark and compare the them.

The requests must be exactly the same including:

URL

Request Body

HTTP Headers

Inspect the requests and amend JMeter's configuration so the request would be 100% equal to what Postman sends.

Also it's possible to record Postman request or collection execution using JMeter's HTTP(S) Test Script Recorder

And last but not the least check HTTP Proxy settings for Postman, it might be the case you need to use a proxy server for accessing the authorization endpoint and the connection to the application under test is direct, Postman has proxy configured and JMeter doesn't, if this is the case - perform JMeter Proxy configuration again to match 100% Postman settings.


问:
How do I handle multiple interactions that belong to specific users in Discord JS?
How do I make it so that if 2 users execute a command that needs to detect if I press buttons, only that user can react to their own interaction, and if you press the others one, you will get an ephemeral message saying that it’s not yours?

I’ve thought of a solution, but I don’t know if it works:

Changing the filter in a collector.
Problem is, I don’t even know if it’s possible to change a filter, and if multiple people run that code at once, will the filter update to the most recent thing?

I know its a lot of questions, so the main question is just the title.

答:
The way I handle it is like this:

create a filter to include the ID's of the person/people you want to be able to use the button

create the interaction collector with that filter
=> The collector will only trigger for people you specified, everyone else will get a message saying that the interaction failed.

Alternatively, you could simply make a filter that collects all interactions, and then check for the ID of the person that interacted in the code.
If it's not someone that should be able to use the button, return an ephemeral message.

//filters for only for interactions on a certain message and by a certain user
const filter = (interaction) => interaction.user.id == <userid> && interaction.message.id == <messageid>

//create a component collector for 5 minutes for that specific message or alternatively an entire channel (if you create it for a single message you don't need to check for the message ID in the filter)
const collector = <message/channel>.createMessageComponentCollector({filter: filter, time: 30000});

//when the filter collects something, this runs
collector.on('collect', async i => {
    //alternatively check for user IDs here
    if(interaction.user.id != <userid>) return <error message>

    //your code here
    ...
})

//this runs once the collector stops
collector.on('end', async collected => {...})
```


问:
Hadoop Job Scheduling query
I am a beginner to Hadoop.

As per my understanding, Hadoop framework runs the Jobs in FIFO order (default scheduling).

Is there any way to tell the framework to run the job at a particular time?

i.e Is there any way to configure to run the job daily at 3PM like that?

Any inputs on this greatly appreciated.

Thanks, R

答: What about calling the job from external java schedule framework, like Quartz? Then you can run the job as you want.</p>

Title: Hadoop Job Scheduling query