问:
Access variables at play level
I use localhost and set_fact to store variables and access them in different playbooks.

---
- hosts: localhost
  connection: local
  gather_facts: False
  tasks:
    - name: set_variables
      set_fact:
        cloudinit_fqdn: 'server1.example.com'
        additional_container_config_values:
          security.nesting: 'false'
          security.privileged: 'false'
        cloudinit_network_raw:
          version: 2
          renderer: networkd
          ethernets:
            eth0:
              dhcp4: False
              addresses: [192.168.178.35/24]
              gateway4: 192.168.178.1
              nameservers:
                addresses: [192.168.178.13]
```
<p>Now I want to use the <code>cloudinit_fqdn</code> at <code>import_playbook</code>:</p>
<pre class="lang-yaml prettyprint-override"><code>- name: system configuration
  import_playbook: "{{ hostvars['localhost']['cloudinit_fqdn'] }}_server_config.yml"
</code>```

I tried different ways to get that variable, but I get errors like:

'ERROR! 'hostvars' is undefined'

I am not able to get access to that variable by:

- debug:
    msg: '{{ vars }}'
```

ERROR! 'debug' is not a valid attribute for a Play

How can I use a variable at play-level?

答:
Regarding your use case I've setup a short test to come around the syntax errors of the variable, as well the debug task.

---
- hosts: localhost
  become: false
  gather_facts: false

  tasks:

  - name: Set variables
    set_fact:
      example_fqdn: 'test.example.com'

  - name: Show variables
    debug:
      msg: "{{ hostvars['localhost'].example_fqdn }}"

```
<p>While the example is working, adding</p>
<pre class="lang-yaml prettyprint-override"><code>- name: Import playbook
  import_playbook: "{{ hostvars['localhost'].example_fqdn }}.yml"
</code>```

or even a simple

- name: Import playbook
  import_playbook: "{{ example_fqdn }}.yml"
```
<p>let the playbook run fail with</p>
```ERROR! 'hostvars' is undefined
ERROR! 'example_fqdn' is undefined
```
<p>since the import is done during compile time, whereby the variable will be defined during runtime. Even not possible is</p>
<pre class="lang-yaml prettyprint-override"><code>- name: Import playbook
  import_playbook: "{{ to_import }}.yml"
  vars:
    to_import: "{{ example_fqdn }}"
</code>```

as the import is static, not dynamic. Importing playbooks and Re-using playbooks seems not working in that way.

What is actually working is

- name: Import playbook
  import_playbook: test.example.com.yml
```

Furher Questions and Answers

Ansible: import_playbook fails with variable undefined error

Ansible: Skip import_playbook with variable definition

What's the difference between include_tasks and import_tasks

Title: Access variables at play level

Body:
I use localhost and set_fact to store variables and access them in different playbooks.

---
- hosts: localhost
  connection: local
  gather_facts: False
  tasks:
    - name: set_variables
      set_fact:
        cloudinit_fqdn: 'server1.example.com'
        additional_container_config_values:
          security.nesting: 'false'
          security.privileged: 'false'
        cloudinit_network_raw:
          version: 2
          renderer: networkd
          ethernets:
            eth0:
              dhcp4: False
              addresses: [192.168.178.35/24]
              gateway4: 192.168.178.1
              nameservers:
                addresses: [192.168.178.13]

Now I want to use the cloudinit_fqdn at import_playbook:

- name: system configuration
  import_playbook: "{{ hostvars['localhost']['cloudinit_fqdn'] }}_server_config.yml"

I tried different ways to get that variable, but I get errors like:

'ERROR! 'hostvars' is undefined'

I am not able to get access to that variable by:

- debug:
    msg: '{{ vars }}'

ERROR! 'debug' is not a valid attribute for a Play

How can I use a variable at play-level?

Body:
Regarding your use case I've setup a short test to come around the syntax errors of the variable, as well the debug task.

---
- hosts: localhost
  become: false
  gather_facts: false

  tasks:

  - name: Set variables
    set_fact:
      example_fqdn: 'test.example.com'

  - name: Show variables
    debug:
      msg: "{{ hostvars['localhost'].example_fqdn }}"

While the example is working, adding

- name: Import playbook
  import_playbook: "{{ hostvars['localhost'].example_fqdn }}.yml"

or even a simple

- name: Import playbook
  import_playbook: "{{ example_fqdn }}.yml"

let the playbook run fail with

ERROR! 'hostvars' is undefined
ERROR! 'example_fqdn' is undefined

since the import is done during compile time, whereby the variable will be defined during runtime. Even not possible is

- name: Import playbook
  import_playbook: "{{ to_import }}.yml"
  vars:
    to_import: "{{ example_fqdn }}"

as the import is static, not dynamic. Importing playbooks and Re-using playbooks seems not working in that way.

What is actually working is

- name: Import playbook
  import_playbook: test.example.com.yml

Furher Questions and Answers

Ansible: import_playbook fails with variable undefined error

Ansible: Skip import_playbook with variable definition

What's the difference between include_tasks and import_tasks


来源: stackexchange

问:
Timeout Pattern - How bad is Thread.Abort really?
I've read at various websites that Thread.Abort is not very good to use. In this case, how do you implement a timeout pattern? For instance, I've read that MS uses the pattern below (which I've wrapped in an extension method) throughout the framework. Personally, I think this is a pretty cool extension, but I'm worried about the Thread.Abort. Does anyone have a better way?</p>

```<code> public static bool CallandWait(this Action action, int timeout)
    {
        Thread subThread = null;
        Action wrappedAction = () =>
        {
            subThread = Thread.CurrentThread;
            action();
        };

        IAsyncResult result = wrappedAction.BeginInvoke(null, null);

        if (((timeout != -1) && !result.IsCompleted) && (!result.AsyncWaitHandle.WaitOne(timeout, false) || !result.IsCompleted))
        {
            if (subThread != null)
            {
                subThread.Abort();
            }

            return false;
        }
        else
        {
            wrappedAction.EndInvoke(result);
            return true;
        }
    }
</code>```

答:
Basically you're talking about aborting an action which (as far as we know) has no graceful way of aborting.

That means there's going to be no safe way of aborting it. Thread.Abort is just not a nice thing to do - there are various race conditions and ugly situations you can get into (see the link in Richard's answer). I would try desperately hard to avoid wanting to cancel actions that don't know about cancellation - and if you absolutely have to do it, consider restarting the whole app afterwards, as you may no longer be in a sane state.

OwnerDisplayName: Steve

ContentLicense: CC BY-SA 2.5

Body:
I've read at various websites that Thread.Abort is not very good to use. In this case, how do you implement a timeout pattern? For instance, I've read that MS uses the pattern below (which I've wrapped in an extension method) throughout the framework. Personally, I think this is a pretty cool extension, but I'm worried about the Thread.Abort. Does anyone have a better way?

 public static bool CallandWait(this Action action, int timeout)
    {
        Thread subThread = null;
        Action wrappedAction = () =>
        {
            subThread = Thread.CurrentThread;
            action();
        };

        IAsyncResult result = wrappedAction.BeginInvoke(null, null);

        if (((timeout != -1) && !result.IsCompleted) && (!result.AsyncWaitHandle.WaitOne(timeout, false) || !result.IsCompleted))
        {
            if (subThread != null)
            {
                subThread.Abort();
            }

            return false;
        }
        else
        {
            wrappedAction.EndInvoke(result);
            return true;
        }
    }

OwnerDisplayName: Jon Skeet


问:
npm boostrap, js doesnt work on react project
I'm making a react project, where I need to put a navbar, I installed bootstrap with

```<code>npm install bootstrap
</code>```

and I imported it in my index.js like this :

```<code>import 'bootstrap/dist/css/bootstrap.css';
</code>```

I put the bootstrap's documentation navbar exemple in my component, but the button doesn't show the links.
Here's my code :

```<code><nav class="navbar navbar-expand-lg navbar-light bg-light">
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarTogglerDemo01">
                    <a class="navbar-brand" href="#">Hidden brand</a>
                    <ul class="navbar-nav mr-auto mt-2 mt-lg-0">
                        <li class="nav-item active">
                            <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#">Link</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
                        </li>
                    </ul>
                    <form class="form-inline my-2 my-lg-0">
                        <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" />
                        <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
                    </form>
                </div>
            </nav>
</code>```

I tried to add  :

```<code>import 'bootstrap/dist/js/bootstrap.js';
</code>```

in my index.js file but, it didn't work

Do you have any idea, to solve this ?

答:
First install bootstrap npm install bootstrap and than install jquery and popper.js to, npm install jquery popper.js.

Add all to index.js

import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.bundle.min';
import $ from 'jquery';
import Popper from 'popper.js';
```

ContentLicense: CC BY-SA 4.0

Body:
I'm making a react project, where I need to put a navbar, I installed bootstrap with

npm install bootstrap

and I imported it in my index.js like this :

import 'bootstrap/dist/css/bootstrap.css';

I put the bootstrap's documentation navbar exemple in my component, but the button doesn't show the links.
Here's my code :

                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation">

                </button>

                    Hidden brand

                            Home (current)

                            Link

                            Disabled

                    <form class="form-inline my-2 my-lg-0">
                        <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" />
                        <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
                    </form>

I tried to add  :

import 'bootstrap/dist/js/bootstrap.js';

in my index.js file but, it didn't work

Do you have any idea, to solve this ?


问:
How can I convert JS to TS?
I read many articles about TypeScript and couldn't find anything. What type to set for elements X and Y? or how to convert the code to TS? thanks in advance for your help</p>
```<code>const x = document.getElementById("password-input");
const y = document.getElementById("img");
function showPass() {
            if (x.type === "password") {
            x.type = "text";
            y.src = "png"

        } else {
            x.type = "password";
            y.src = "png"
        }
    }
</code>```

答:
You can't just use TS in the browser, you'll need to compile it. For your specific use case, you will need to tell TS what the HTMLElement is for x and y, otherwise it won't like x.type and y.src as src and type aren't properties on HTMLElement

```<code>const x: HTMLInputElement = document.getElementById("password-input");
const y: HTMLImageElement = document.getElementById("img");
function showPass() {
            if (x.type === "password") {
            x.type = "text";
            y.src = "png"

        } else {
            x.type = "password";
            y.src = "png"
        }
    }
</code>```

Title: How can I convert JS to TS?

Body:
I read many articles about TypeScript and couldn't find anything. What type to set for elements X and Y? or how to convert the code to TS? thanks in advance for your help

const x = document.getElementById("password-input");
const y = document.getElementById("img");
function showPass() {
            if (x.type === "password") {
            x.type = "text";
            y.src = "png"

        } else {
            x.type = "password";
            y.src = "png"
        }
    }

Body:
You can't just use TS in the browser, you'll need to compile it. For your specific use case, you will need to tell TS what the HTMLElement is for x and y, otherwise it won't like x.type and y.src as src and type aren't properties on HTMLElement

const x: HTMLInputElement = document.getElementById("password-input");
const y: HTMLImageElement = document.getElementById("img");
function showPass() {
            if (x.type === "password") {
            x.type = "text";
            y.src = "png"

        } else {
            x.type = "password";
            y.src = "png"
        }
    }


问:
Export of MySQL database with --complete-insert does not include column names in resulting txt files
I am trying to export database with multiple tables into csv / txt files including column names. However, using --complete-insert flag in the statement does export txt files but without corresponding column headers. The exported sql file does contain the column headers.

This is the command I am using:

mysqldump --password  --fields-optionally-enclosed-by='"' --fields-terminated-by=',' --tab /var/lib/mysql-files/ --complete-insert test

I am using latest docker image with MySQL 8.0.28 installed on it. I tried different ways of including --complete-insert statement with no effect.

答:
In the end, the following was easiest for me (some of the exports will be used within python based environment so keeping it all in one place was useful for me).

```<code>from sqlalchemy import create_engine
import pandas as pd
import os

# Dummy connection settings values
pwd = "helloworld"
port = "3306"
database = "testapp"
container_name = "mysql-development"

# Connect to the database
mysql_conn_str = f"mysql+pymysql://root:{pwd}@{container_name}:{port}/{database}"
engine = create_engine(mysql_conn_str)
connection = engine.connect()

def save_files(x, engine, base_path = "./", **kwargs):

    save_path = os.path.join(base_path, f"{x}.csv")
    df = pd.read_sql_query(f"SELECT * FROM {x}", engine)

    df.to_csv(save_path, **kwargs)

# Execute queries
tables = pd.read_sql_query("SHOW TABLES;", engine)
tables[f"Tables_in_{database}"].apply(save_files, args=(engine, ), base_path = "/install", index = False)
</code>```

Body:
In the end, the following was easiest for me (some of the exports will be used within python based environment so keeping it all in one place was useful for me).

from sqlalchemy import create_engine
import pandas as pd
import os

# Dummy connection settings values
pwd = "helloworld"
port = "3306"
database = "testapp"
container_name = "mysql-development"

# Connect to the database
mysql_conn_str = f"mysql+pymysql://root:{pwd}@{container_name}:{port}/{database}"
engine = create_engine(mysql_conn_str)
connection = engine.connect()

def save_files(x, engine, base_path = "./", **kwargs):

    save_path = os.path.join(base_path, f"{x}.csv")
    df = pd.read_sql_query(f"SELECT * FROM {x}", engine)

    df.to_csv(save_path, **kwargs)

# Execute queries
tables = pd.read_sql_query("SHOW TABLES;", engine)
tables[f"Tables_in_{database}"].apply(save_files, args=(engine, ), base_path = "/install", index = False)


问:
Discord.js isnt sending the embed due to non-empty string error
```<code>const { SlashCommandBuilder } = require('@discordjs/builders')
const discord = require('discord.js')
const open = require('openweather-api-node');
module.exports = {
    data: new SlashCommandBuilder()
        .setName('weather')
        .setDescription('Shows the Weather condition of a place')
        .addStringOption(option =>
            option.setName('city')
                .setDescription('Name of the city')
                .setRequired(true)),

    async execute(Discord, client, interaction) {

        let city = interaction.options.getString('city');

        let weather = new open({
            key: process.env.WEATHER,

            units: 'metric'
        })

        weather.setLanguage('en')
     let info = await   weather.getCurrent({ locationName: city })

      if(!info) return interaction.reply({content:"Oops "})
            //location
            var lon = info.lon.toString()
            var lat = info.lat.toString()
            let Timezone = info.timezone

            //Temperature
            var temp =  info.weather.temp.cur.toString()
            let feel_like = info.weather.feels_like.cur
            let min = info.weather.temp.min
            let max =info.weather.temp.max

            //air condition
            let pressure = info.weather.pressure
            let humidity = info.weather.humidity + '%'
            let wind = info.weather.wind.speed + 'km/h'

            //description

            let sky = info.weather.description
            let status = info.weather.main

        console.log(temp)
        console.log(lon)
        console.log(lat)

            let new1 = new discord.MessageEmbed()
            new1.setTitle(city + `'s Weather`)
            new1.setDescription('bruh pls work')
            new1.setColor('#0099ff')
            new1.addFields('**Location**', `Latitude:`+ lat,true)
            new1.addFields('**Temperature**', `${temp}℃`,true)
            new1.setTimestamp()
            new1.setFooter({ text: 'Information by Open-Weather' })

            interaction.reply({embeds:[new1]})

    }
}
</code>```

So this is my code
the temp,lan,lat variables were number but i changed them into string
and even checked with the typeof method
It gave me a string

But still i'm facing out this error called RangeError [EMBED_FIELD_NAME]: MessageEmbed field names must be non-empty string

Please help me if you know whats the solution

答:
Try this format:

.addFields(
    { name: 'string', value: 'string', inline: true }
)
```
<p>For multiple:</p>
<pre class="lang-js prettyprint-override"><code>.addFields(
    { name: 'string', value: 'string' }
    { name: 'string', value: 'string' }
)
</code>```

Or refer to the other answer.

Body:
const { SlashCommandBuilder } = require('@discordjs/builders')
const discord = require('discord.js')
const open = require('openweather-api-node');
module.exports = {
    data: new SlashCommandBuilder()
        .setName('weather')
        .setDescription('Shows the Weather condition of a place')
        .addStringOption(option =>
            option.setName('city')
                .setDescription('Name of the city')
                .setRequired(true)),

    async execute(Discord, client, interaction) {

        let city = interaction.options.getString('city');

        let weather = new open({
            key: process.env.WEATHER,

            units: 'metric'
        })

        weather.setLanguage('en')
     let info = await   weather.getCurrent({ locationName: city })

      if(!info) return interaction.reply({content:"Oops "})
            //location
            var lon = info.lon.toString()
            var lat = info.lat.toString()
            let Timezone = info.timezone

            //Temperature
            var temp =  info.weather.temp.cur.toString()
            let feel_like = info.weather.feels_like.cur
            let min = info.weather.temp.min
            let max =info.weather.temp.max

            //air condition
            let pressure = info.weather.pressure
            let humidity = info.weather.humidity + '%'
            let wind = info.weather.wind.speed + 'km/h'

            //description

            let sky = info.weather.description
            let status = info.weather.main

        console.log(temp)
        console.log(lon)
        console.log(lat)

            let new1 = new discord.MessageEmbed()
            new1.setTitle(city + `'s Weather`)
            new1.setDescription('bruh pls work')
            new1.setColor('#0099ff')
            new1.addFields('**Location**', `Latitude:`+ lat,true)
            new1.addFields('**Temperature**', `${temp}℃`,true)
            new1.setTimestamp()
            new1.setFooter({ text: 'Information by Open-Weather' })

            interaction.reply({embeds:[new1]})

    }
}

So this is my code
the temp,lan,lat variables were number but i changed them into string
and even checked with the typeof method
It gave me a string

But still i'm facing out this error called RangeError [EMBED_FIELD_NAME]: MessageEmbed field names must be non-empty string

Please help me if you know whats the solution

Body:
Try this format:

.addFields(
    { name: 'string', value: 'string', inline: true }
)

For multiple:

.addFields(
    { name: 'string', value: 'string' }
    { name: 'string', value: 'string' }
)

Or refer to the other answer.


问:
Xcode 4: Fetch Request Template Variables?
In Xcode 3.X, you were supposed to right-click the whitespace in the fetch request template's predicate editor to specify a variable input rather than a hard-coded predicate.

Where is this in XCode 4? I've held option, right-clicked, option-clicked, etc and cannot figure it out....

答:
I don't think X4 has the variable anymore.

Instead, I think you have to choose an expression and then provide a variable of the form $VARNAME.

For example, given and entity Alpha with an attribute aString, I created a fetch request template bobFetch with an expression of aString == $TESTVAR.

```<code>Alpha *a=[NSEntityDescription insertNewObjectForEntityForName:@"Alpha" inManagedObjectContext:self.moc];
a.aString=@"steve";
[self saveContext];
NSDictionary *subVars=[NSDictionary dictionaryWithObject:@"steve" forKey:@"TESTVAR"];
NSFetchRequest *fetchRequest =   [self.managedObjectModel fetchRequestFromTemplateWithName:@"bobRequest" substitutionVariables:subVars];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Alpha" inManagedObjectContext:self.moc];
[fetchRequest setEntity:entity];
</code>```

If logged fetchRequest reports:

```<code><NSFetchRequest: 0x4d17480> (entity: Alpha; predicate: (aString == "steve"); sortDescriptors: ((null)); type: NSManagedObjectResultType; )
</code>```

... and can then be used normally.

```<code>NSError *error = nil;
NSArray *fetchedObjects = [self.moc executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {
    NSLog(@"fetch error = %@",error);
}
NSLog(@"fetchObjects = %@",fetchedObjects);
</code>```

Kind of clumsy for a graphical environment but it works.

ContentLicense: CC BY-SA 3.0

Body:
I don't think X4 has the variable anymore.

Instead, I think you have to choose an expression and then provide a variable of the form $VARNAME.

For example, given and entity Alpha with an attribute aString, I created a fetch request template bobFetch with an expression of aString == $TESTVAR.

Alpha *a=[NSEntityDescription insertNewObjectForEntityForName:@"Alpha" inManagedObjectContext:self.moc];
a.aString=@"steve";
[self saveContext];
NSDictionary *subVars=[NSDictionary dictionaryWithObject:@"steve" forKey:@"TESTVAR"];
NSFetchRequest *fetchRequest =   [self.managedObjectModel fetchRequestFromTemplateWithName:@"bobRequest" substitutionVariables:subVars];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Alpha" inManagedObjectContext:self.moc];
[fetchRequest setEntity:entity];

If logged fetchRequest reports:

<NSFetchRequest: 0x4d17480> (entity: Alpha; predicate: (aString == "steve"); sortDescriptors: ((null)); type: NSManagedObjectResultType; )

... and can then be used normally.

NSError *error = nil;
NSArray *fetchedObjects = [self.moc executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {
    NSLog(@"fetch error = %@",error);
}
NSLog(@"fetchObjects = %@",fetchedObjects);

Kind of clumsy for a graphical environment but it works.


问:
New Entry Not reflacting in table after inserting New record in CRUD angular app
In Angular 13, I created basic CRUD app of employee. When i insert new data and hit submit it run the createEmployee() service and print data on console. Then it redirect to home page that shows all entry in table which call getEmployeeList(). But sometimes it shows newly created entry and sometimes it not shows. In database it perfectly entered. When i goto some other page and come back to home page it shows.

create-employee.components.ts

```<code>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Employee } from 'src/app/employee';
import { EmployeeService } from 'src/app/Services/employee.service';

@Component({
 selector: 'app-create-employee',
 templateUrl: './create-employee.component.html',
 styleUrls: ['./create-employee.component.css']
})
export class CreateEmployeeComponent implements OnInit {

 employee: Employee = new Employee();

 constructor(private employservice: EmployeeService,private router: Router) { }

 ngOnInit(): void {

 }

 saveEmployee() {
   this.employservice.createEmployee(this.employee).subscribe(data => {
     console.log(data);
   })
   console.error();
 }

 gotoemployeelist() {
   this.router.navigate(['employees']);
 }

 onSubmit() {
   this.saveEmployee();
   this.gotoemployeelist();
 }

}

</code>```

employee-service.ts

```<code>import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { map, Observable } from 'rxjs';
import { Employee } from '../employee';

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {

  public baseURL="http://localhost:8080/api/v1/employees";

  constructor(private httpClient: HttpClient) {}

  getEmployeeList(): Observable<Employee[]> {
    return this.httpClient.get<Employee[]>(this.baseURL).pipe(
      map(employees => {
        for(let employee of employees) {
          employee.bdate = new Date(employee.bdate);
          employee.jdate = new Date(employee.jdate);
        }
        console.log("Employees Service: GetEmployee() called");
        return employees;
      }));
  }

  createEmployee(employee: Employee): Observable<Object> {
    console.log("Employees Service: CreateEmployee() called");
    return this.httpClient.post(this.baseURL,employee);
  }

  getEmployeebyId(id: Number): Observable<Employee> {
    console.log("Employees Service: GetEmployeeById() called");
    return this.httpClient.get<Employee>(this.baseURL+"/"+id);
  }

  updateEmployee(employee: Employee,id: number): Observable<Object> {
    console.log("Employees Service: UpdateEmployee() called");
    console.log(employee);
    return this.httpClient.put(this.baseURL+"/"+id,employee);
  }

  deleteEmployee(id: number): Observable<Object> {
    console.log("Employees Service: DeleteEmployee() called");
    return this.httpClient.delete(this.baseURL+"/"+id);
  }

}

</code>```

Home-component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Employee } from 'src/app/employee';
import { EmployeeService } from 'src/app/Services/employee.service';

@Component({
  selector: 'app-employee-list',
  templateUrl: './employee-list.component.html',
  styleUrls: ['./employee-list.component.css',]
})
export class EmployeeListComponent implements OnInit {

  employees: Employee[];

  constructor(private employeeservice: EmployeeService,private router: Router) {

  }

  ngOnInit(): void {
    this.getEmployees();
  }

  private getEmployees() {
    this.employeeservice.getEmployeeList().subscribe(data => {
      console.log(data);
      this.employees=data;
    });
  }

  updateEmployee(id: Number) {
    this.router.navigate(['update-employee',id]);
  }

  deleteEmployee(id: number) {
    this.employeeservice.deleteEmployee(id).subscribe(data => {
      console.log(id+"employeed Deleted.");
      this.getEmployees();
    });
  }

  employeeDetails(id: number) {
    this.router.navigate(['emloyee-details',id]);
  }

}
</code>```

In console you can see that createEmployee() called then GetEmployee() called and then it print console.log(newEntry) after navigation.

答:
What is happening program is not waiting to complete createEmployee API before navigating to the home page. You need to call gotoemployeelist() only after the you get response from createEmployee API. You can do this by calling the method inside the subscribe</p>
```<code> saveEmployee() {
   this.employservice.createEmployee(this.employee).subscribe(data => {
     console.log(data);
     this.gotoemployeelist();
   })
   console.error();
 }

 gotoemployeelist() {
   this.router.navigate(['employees']);
 }

 onSubmit() {
   this.saveEmployee();
 }
</code>```

Body:
In Angular 13, I created basic CRUD app of employee. When i insert new data and hit submit it run the createEmployee() service and print data on console. Then it redirect to home page that shows all entry in table which call getEmployeeList(). But sometimes it shows newly created entry and sometimes it not shows. In database it perfectly entered. When i goto some other page and come back to home page it shows.

create-employee.components.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Employee } from 'src/app/employee';
import { EmployeeService } from 'src/app/Services/employee.service';

@Component({
 selector: 'app-create-employee',
 templateUrl: './create-employee.component.html',
 styleUrls: ['./create-employee.component.css']
})
export class CreateEmployeeComponent implements OnInit {

 employee: Employee = new Employee();

 constructor(private employservice: EmployeeService,private router: Router) { }

 ngOnInit(): void {

 }

 saveEmployee() {
   this.employservice.createEmployee(this.employee).subscribe(data => {
     console.log(data);
   })
   console.error();
 }

 gotoemployeelist() {
   this.router.navigate(['employees']);
 }

 onSubmit() {
   this.saveEmployee();
   this.gotoemployeelist();
 }

}

employee-service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { map, Observable } from 'rxjs';
import { Employee } from '../employee';

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {

  public baseURL="http://localhost:8080/api/v1/employees";

  constructor(private httpClient: HttpClient) {}

  getEmployeeList(): Observable<Employee[]> {
    return this.httpClient.get<Employee[]>(this.baseURL).pipe(
      map(employees => {
        for(let employee of employees) {
          employee.bdate = new Date(employee.bdate);
          employee.jdate = new Date(employee.jdate);
        }
        console.log("Employees Service: GetEmployee() called");
        return employees;
      }));
  }

  createEmployee(employee: Employee): Observable<Object> {
    console.log("Employees Service: CreateEmployee() called");
    return this.httpClient.post(this.baseURL,employee);
  }

  getEmployeebyId(id: Number): Observable<Employee> {
    console.log("Employees Service: GetEmployeeById() called");
    return this.httpClient.get<Employee>(this.baseURL+"/"+id);
  }

  updateEmployee(employee: Employee,id: number): Observable<Object> {
    console.log("Employees Service: UpdateEmployee() called");
    console.log(employee);
    return this.httpClient.put(this.baseURL+"/"+id,employee);
  }

  deleteEmployee(id: number): Observable<Object> {
    console.log("Employees Service: DeleteEmployee() called");
    return this.httpClient.delete(this.baseURL+"/"+id);
  }

}

Home-component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Employee } from 'src/app/employee';
import { EmployeeService } from 'src/app/Services/employee.service';

@Component({
  selector: 'app-employee-list',
  templateUrl: './employee-list.component.html',
  styleUrls: ['./employee-list.component.css',]
})
export class EmployeeListComponent implements OnInit {

  employees: Employee[];

  constructor(private employeeservice: EmployeeService,private router: Router) {

  }

  ngOnInit(): void {
    this.getEmployees();
  }

  private getEmployees() {
    this.employeeservice.getEmployeeList().subscribe(data => {
      console.log(data);
      this.employees=data;
    });
  }

  updateEmployee(id: Number) {
    this.router.navigate(['update-employee',id]);
  }

  deleteEmployee(id: number) {
    this.employeeservice.deleteEmployee(id).subscribe(data => {
      console.log(id+"employeed Deleted.");
      this.getEmployees();
    });
  }

  employeeDetails(id: number) {
    this.router.navigate(['emloyee-details',id]);
  }

}

In console you can see that createEmployee() called then GetEmployee() called and then it print console.log(newEntry) after navigation.

Body:
What is happening program is not waiting to complete createEmployee API before navigating to the home page. You need to call gotoemployeelist() only after the you get response from createEmployee API. You can do this by calling the method inside the subscribe

 saveEmployee() {
   this.employservice.createEmployee(this.employee).subscribe(data => {
     console.log(data);
     this.gotoemployeelist();
   })
   console.error();
 }

 gotoemployeelist() {
   this.router.navigate(['employees']);
 }

 onSubmit() {
   this.saveEmployee();
 }


问:
How do implement panel feature in Xamarin.forms
Like in Windows Forms we can add multiple panels in the same Form and based on some condition show and hide particular panel. Is there any control in Xamarin.Forms which can be used like this?

The main reason behind this is, I have 3 tabs on a page. I am using buttons for tabs and not tabbed pages as design of tabbed bar is not what my client wants. So I have 3 pages say Page A, Page B, Page C and each of the page has 3 tabs to go to respective page. If user is on Page A and fills some sort of data(which is not yet saved) and wants to go to Page B and then on Page B he fills in some more details and then without saving data on Page B when he comes back to Page A all the details filled by user on Page A and Page B has to be available.

Hence If I use multiple pages for this then the data will be lost when I redirect to new page. So Is there any way by which I have multiple panels and hide 1st panel when 2nd panel is visible which will not clear any data and hence I can achieve what I want.

答:
Just use a Frame:</p>
```<code><StackLayout>
    <Frame x:Name="MyPanelABC">
        <Label Text="My Stuff" />
    </Frame>
</StackLayout>

private void setupPanelABC(bool isVisiblePanelABC){
    MyPanelABC.IsVisible = isVisiblePanelABC;
}
</code>```

Body:
Just use a Frame:

<StackLayout>
    <Frame x:Name="MyPanelABC">
        <Label Text="My Stuff" />
    </Frame>
</StackLayout>

private void setupPanelABC(bool isVisiblePanelABC){
    MyPanelABC.IsVisible = isVisiblePanelABC;
}


问:
JavaScript Sorting Multidimensional JSON
I have this JSON string:

```<code>{
"widgets":[
    {"column1":[
        {"weight":1, "bID":1, "hideMe":false, "collapse":false, "titleOf":"Test 1", "colorOf":"color-blue", "theFunction":"functionName"},
        {"weight":2, "bID":2, "hideMe":false, "collapse":false, "titleOf":"Test 2", "colorOf":"color-red", "theFunction":"functionName"},
        {"weight":3, "bID":3, "hideMe":false, "collapse":true, "titleOf":"Test 3", "colorOf":"color-yellow", "theFunction":"functionName"}
    ]},
    {"column2":[
        {"weight":1, "bID":4, "hideMe":false, "collapse":false, "titleOf":"Test 4", "colorOf":"color-white", "theFunction":"functionName"},
        {"weight":3, "bID":5, "hideMe":false, "collapse":false, "titleOf":"Test 5", "colorOf":"color-green", "theFunction":"functionName"},
        {"weight":2, "bID":6, "hideMe":false, "collapse":true, "titleOf":"Test 6", "colorOf":"color-green", "theFunction":"functionName"}
    ]},
    {"column3":[
        {"weight":3, "bID":7, "hideMe":false, "collapse":false, "titleOf":"Test 7", "colorOf":"color-green", "theFunction":"functionName"},
        {"weight":2, "bID":8, "hideMe":false, "collapse":true, "titleOf":"Test 8", "colorOf":"color-yellow", "theFunction":"functionName"},
        {"weight":1, "bID":9, "hideMe":false, "collapse":false, "titleOf":"Test 9", "colorOf":"color-white", "theFunction":"functionName"},
    ]}
]}
</code>```

if I do

```<code>alert(testJSON.widgets.length);
</code>```

I get 3, however if I do

```<code>alert(testJSON.widgets.column1.length);
</code>```

I get "testJSON.widgets.column3 is undefined" as an error.

What I am ultimately attempting to do is take each column1-3 and sort them by weight. Through something like

```<code>testJSON.widgets.column1.sort(function(a,b) { return parseFloat(a.weight) - parseFloat(b.weight) });
</code>```

So I can then do a $.each() via jquery

答:
You have arrays not objects.
Instead of alert(testJSON.widgets.column1.length); you should write  alert(testJSON.widgets[0].length);

Body:
I have this JSON string:

{
"widgets":[
    {"column1":[
        {"weight":1, "bID":1, "hideMe":false, "collapse":false, "titleOf":"Test 1", "colorOf":"color-blue", "theFunction":"functionName"},
        {"weight":2, "bID":2, "hideMe":false, "collapse":false, "titleOf":"Test 2", "colorOf":"color-red", "theFunction":"functionName"},
        {"weight":3, "bID":3, "hideMe":false, "collapse":true, "titleOf":"Test 3", "colorOf":"color-yellow", "theFunction":"functionName"}
    ]},
    {"column2":[
        {"weight":1, "bID":4, "hideMe":false, "collapse":false, "titleOf":"Test 4", "colorOf":"color-white", "theFunction":"functionName"},
        {"weight":3, "bID":5, "hideMe":false, "collapse":false, "titleOf":"Test 5", "colorOf":"color-green", "theFunction":"functionName"},
        {"weight":2, "bID":6, "hideMe":false, "collapse":true, "titleOf":"Test 6", "colorOf":"color-green", "theFunction":"functionName"}
    ]},
    {"column3":[
        {"weight":3, "bID":7, "hideMe":false, "collapse":false, "titleOf":"Test 7", "colorOf":"color-green", "theFunction":"functionName"},
        {"weight":2, "bID":8, "hideMe":false, "collapse":true, "titleOf":"Test 8", "colorOf":"color-yellow", "theFunction":"functionName"},
        {"weight":1, "bID":9, "hideMe":false, "collapse":false, "titleOf":"Test 9", "colorOf":"color-white", "theFunction":"functionName"},
    ]}
]}

if I do

alert(testJSON.widgets.length);

I get 3, however if I do

alert(testJSON.widgets.column1.length);

I get "testJSON.widgets.column3 is undefined" as an error.

What I am ultimately attempting to do is take each column1-3 and sort them by weight. Through something like

testJSON.widgets.column1.sort(function(a,b) { return parseFloat(a.weight) - parseFloat(b.weight) });

So I can then do a $.each() via jquery


问:
Why is my store procedure throwing a syntax error
I have a MySql database (statements) that contains a table (trans). I have written a stored procedure but I am getting a syntax error that I don't understand.   The stored procedure is supposed to go through the trans table and assign a category (WorkSheetCatCodeTest) based upon several conditions that are contained in a case statement.

The error that I'm receiving is:

```<code>**"CASE" is not valid in this position, expecting "SET"**
</code>```

Here is the the stored procedure:

```<code>CREATE DEFINER=`statements`@`%` procedure `SetWorksheetCat` ()
BEGIN
UPDATE statements.trans t
CASE t
WHEN t.OurBank = BOAUSD1234 & t.BankTranCode In(171, 491,481) THEN SET t.WorkSheetCatCodeTest = 'CAT 1'
WHEN t.OurBank = BOAUSD1234 & t.BankTranCode In(699) & t.Comments like %ISI OPERATING% THEN SET t.WorkSheetCatCodeTest = 'CAT 2'
WHEN t.OurBank = BOAUSD1234 & t.BankTranCode In(495) & t.Comments like %ISI OPERATING% THEN SET t.WorkSheetCatCodeTest = 'CAT 3'
WHEN t.OurBank = BOAUSD1234 & t.BankTranCode In(481) & t.Comments like %INT-DEBT% THEN SET t.WorkSheetCatCodeTest = 'CAT 4'
ELSE SET t.WorkSheetCatCodeTest = 'NO MAPPING RULE'
END
</code>```

答:
Thanks to JEFF HOLT, I see my errors.

Need to replace case t with set t.WorkSheetCatCodeTest = case

Need to replace each one of these BOAUSD1234 with BOAUSD1234

Neet to replace END with END;

Need to Add final END to the Proc

Body:
I have a MySql database (statements) that contains a table (trans). I have written a stored procedure but I am getting a syntax error that I don't understand.   The stored procedure is supposed to go through the trans table and assign a category (WorkSheetCatCodeTest) based upon several conditions that are contained in a case statement.

The error that I'm receiving is:

**"CASE" is not valid in this position, expecting "SET"**

Here is the the stored procedure:

CREATE DEFINER=`statements`@`%` procedure `SetWorksheetCat` ()
BEGIN
UPDATE statements.trans t
CASE t
WHEN t.OurBank = BOAUSD1234 & t.BankTranCode In(171, 491,481) THEN SET t.WorkSheetCatCodeTest = 'CAT 1'
WHEN t.OurBank = BOAUSD1234 & t.BankTranCode In(699) & t.Comments like %ISI OPERATING% THEN SET t.WorkSheetCatCodeTest = 'CAT 2'
WHEN t.OurBank = BOAUSD1234 & t.BankTranCode In(495) & t.Comments like %ISI OPERATING% THEN SET t.WorkSheetCatCodeTest = 'CAT 3'
WHEN t.OurBank = BOAUSD1234 & t.BankTranCode In(481) & t.Comments like %INT-DEBT% THEN SET t.WorkSheetCatCodeTest = 'CAT 4'
ELSE SET t.WorkSheetCatCodeTest = 'NO MAPPING RULE'
END


问:
column delimiter in pandas
I am trying to import this table in pandas:

When I import it this is what I got:

What should I write in the delimiter parameter so that it keeps the column separated as they are on excel? I have read that by default pandas use commas as separators and that explains why I got these results, but I don't understand what command should I use so that it simply uses the same column separation that excel uses.

答:
You simply specify ; as separator:

```<code>pd.read_csv('data.csv', sep=';')
</code>```

Title: column delimiter in pandas

Body:
You simply specify ; as separator:

pd.read_csv('data.csv', sep=';')


问:
What is the proper way to format a multi-line dict in Python?
In Python, I want to write a multi-line dict in my code. There are a couple of ways one could format it. Here are a few that I could think of:

```<code>mydict = { "key1": 1,
           "key2": 2,
           "key3": 3, }
</code>```

```<code>mydict = { "key1": 1,
           "key2": 2,
           "key3": 3,
         }
</code>```

```<code>mydict = {
    "key1": 1,
    "key2": 2,
    "key3": 3,
}
</code>```

I know that any of the above is syntactically correct, but I assume that there is one preferred indentation and line-break style for Python dicts. What is it?

Note: This is not an issue of syntax. All of the above are (as far as I know) valid Python statements and are equivalent to each other.

答:
flake8 – a utility for enforcing style consistency in python code, which checks your code syntax and provide instructions to improve it – recommends this format (see https://www.flake8rules.com/rules/E133.html):</p>
```<code>mydict = {
    "key1": 1,
    "key2": 2,
    "key3": 3,
    }
</code>```

Body:
In Python, I want to write a multi-line dict in my code. There are a couple of ways one could format it. Here are a few that I could think of:

mydict = { "key1": 1,
           "key2": 2,
           "key3": 3, }

mydict = { "key1": 1,
           "key2": 2,
           "key3": 3,
         }

mydict = {
    "key1": 1,
    "key2": 2,
    "key3": 3,
}

I know that any of the above is syntactically correct, but I assume that there is one preferred indentation and line-break style for Python dicts. What is it?

Note: This is not an issue of syntax. All of the above are (as far as I know) valid Python statements and are equivalent to each other.

Body:
flake8 – a utility for enforcing style consistency in python code, which checks your code syntax and provide instructions to improve it – recommends this format (see https://www.flake8rules.com/rules/E133.html):

mydict = {
    "key1": 1,
    "key2": 2,
    "key3": 3,
    }


问:
Best way to run different versions of a project on GIT?
I have to add an additional version of my project for a new customer.

The goals are:

One main version of the project that keeps common code and a
group of customer-oriented versions with specific additions for
every customer.

Be able to upload changes from common version.

The best way would be to break project into independent modules, but I am limited in time and can't stick to that option atm. I am considering 2 options

Fork

Multiple branches withing the same repo

Are there better way to do it? What are the cons and pros?
Thanks.

答:
If you don't have to absolutely keep the code for customers in different repositories for specific reasons, the solution with branches is the easiest (especially to exchange code, cherry-pick, sync,...) and lot less a burden (not having to create a lot of repositories).

And also the easier to start with. You could still create different repositories after if you change your mind.

But, if you don't know, have a look à the 'git worktree' feature to create a worktree for each customer, that could make your life a little easier...


答:
It looks like your CSV file is using semicolons (;) instead of commas (,) to delineate cells. In that case, simply add delimiter=';' to your read_csv call:

```<code>df = pd.read_csv(`cost10.csv`, header=None, names=column_names, delimiter=';')
</code>```

Title: column delimiter in pandas

Body:
I am trying to import this table in pandas:

When I import it this is what I got:

What should I write in the delimiter parameter so that it keeps the column separated as they are on excel? I have read that by default pandas use commas as separators and that explains why I got these results, but I don't understand what command should I use so that it simply uses the same column separation that excel uses.

Body:
It looks like your CSV file is using semicolons (;) instead of commas (,) to delineate cells. In that case, simply add delimiter=';' to your read_csv call:

df = pd.read_csv(`cost10.csv`, header=None, names=column_names, delimiter=';')


问:
PHP - Use cURL to send information to another page
I am trying to make a validation for a form and if everything goes right it should go to the 2nd page, where it should take the information from the $_POST.

I was told that given the way I am doing it, $_POST would not work and I should try cURL. I tried to make it work, but somehow it does not work. It redirects correctly to the install2.php but its not passing any variables to it. What i am doing wrong?

My code is as follows:

```<code><?php
//If the person pressed summit check for the information submited. If everything is correct move to the next page.
if (isset($_POST['submit']))
{
    // declare Variables
    $username = $_POST['username'];
    $password = $_POST['password'];
    $server = $_POST['server'];
    $message = "The following fields are empty: ";

    //Step 1 : Check if username & server are empty and if they are return the correct error
    if (empty($username) || empty($server) )
    {
        if (empty($username)) {
            $message .= "Username";
        }
        if (empty($password)) {
            $message .= " Password";
        }
        if (empty($server)) {
            $message .= " Server";
        }
    }
    else
    {
        //Step 2: Attempt to connect to the DB with the information provided. if not sucessful return to correct error to the user.
        @$connection = mysql_connect($server,$username,$password);
        if (!$connection)
        {
            $message = "Please check your details. the script was unable to connect to the db.";
        }
        else
        {
            //Step 3: Since the connection was stablished successfuly with the information provided then send the login details tot he next page
            // NOTE: For porpuses of this script I am only passing 1 variable... to make my life easier
            $ch = curl_init ();
            curl_setopt ($ch, CURLOPT_URL, 'http://localhost/install2.php');
            curl_setopt ($ch, CURLOPT_POST, TRUE);
            curl_setopt ($ch, CURLOPT_POSTFIELDS, $username);
            curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);

            $response = curl_exec ($ch);

            curl_close ($responde);
            header ('location: install2.php');
        }
    }
}
?>
</code>```

答:
I remarked that your variable name is not the same.</p>
```<code>$reponse and $responde
$response = curl_exec ($ch);

curl_close ($responde);
header ('location: install2.php');
</code>```

Body:
I am trying to make a validation for a form and if everything goes right it should go to the 2nd page, where it should take the information from the $_POST.

I was told that given the way I am doing it, $_POST would not work and I should try cURL. I tried to make it work, but somehow it does not work. It redirects correctly to the install2.php but its not passing any variables to it. What i am doing wrong?

My code is as follows:

<?php
//If the person pressed summit check for the information submited. If everything is correct move to the next page.
if (isset($_POST['submit']))
{
    // declare Variables
    $username = $_POST['username'];
    $password = $_POST['password'];
    $server = $_POST['server'];
    $message = "The following fields are empty: ";

    //Step 1 : Check if username & server are empty and if they are return the correct error
    if (empty($username) || empty($server) )
    {
        if (empty($username)) {
            $message .= "Username";
        }
        if (empty($password)) {
            $message .= " Password";
        }
        if (empty($server)) {
            $message .= " Server";
        }
    }
    else
    {
        //Step 2: Attempt to connect to the DB with the information provided. if not sucessful return to correct error to the user.
        @$connection = mysql_connect($server,$username,$password);
        if (!$connection)
        {
            $message = "Please check your details. the script was unable to connect to the db.";
        }
        else
        {
            //Step 3: Since the connection was stablished successfuly with the information provided then send the login details tot he next page
            // NOTE: For porpuses of this script I am only passing 1 variable... to make my life easier
            $ch = curl_init ();
            curl_setopt ($ch, CURLOPT_URL, 'http://localhost/install2.php');
            curl_setopt ($ch, CURLOPT_POST, TRUE);
            curl_setopt ($ch, CURLOPT_POSTFIELDS, $username);
            curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);

            $response = curl_exec ($ch);

            curl_close ($responde);
            header ('location: install2.php');
        }
    }
}
?>

Body:
I remarked that your variable name is not the same.

$reponse and $responde
$response = curl_exec ($ch);

curl_close ($responde);
header ('location: install2.php');


Title: I have a time series dataframe with monthly stock returns, and i want to extract and create a vector for each months returns

Body:
I have a time series dataframe with monthly stock returns, and I want to extract and create a vector for each months returns.

This is how the dataframe looks. (the MKT vector contains the monthly returns)

This is what I would like to accomplish (In the end) :

By running the dput:

structure(c(0.0286195, 0.03618317, -0.01363269, 0.02977401, 0.04461314,
0.0015209, -0.03207303, -0.0079275, 0.01882991, 0.00584478, 0.02372219,
0.03299206, -0.017908, 0.02540426, 0.04163062, -0.00317315, -0.03732322,
-0.0109474, 0.0147047, 0.00087712, 0.00608527826274047, 0.00495046849033236,
0.00503506482970477, 0.00481634688889247, 0.00424210936461577,
0.00358500724272255, 0.00424210936461577, 0.00480928182207086,
0.00485872460615713, 0.00487990531586144, 1, 1, 1, 1, 0, 0, 0,
0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0,
0, 0), .Dim = c(10L, 6L), .Dimnames = list(NULL, c("MKT", "CAP",
"RF", "dummy", "dummyJAN", "adjdummy")), index = structure(c(-36494,
-36466, -36435, -36405, -36374, -36344, -36313, -36282, -36252,
-36221), class = "Date"), class = "zoo")

Body:
Please try this:

df=structure(c(0.0286195, 0.03618317, -0.01363269, 0.02977401, 0.04461314, 0.0015209, -0.03207303, -0.0079275, 0.01882991, 0.00584478, 0.02372219, 0.03299206, -0.017908, 0.02540426, 0.04163062, -0.00317315, -0.03732322, -0.0109474, 0.0147047, 0.00087712, 0.00608527826274047, 0.00495046849033236, 0.00503506482970477, 0.00481634688889247, 0.00424210936461577, 0.00358500724272255, 0.00424210936461577, 0.00480928182207086, 0.00485872460615713, 0.00487990531586144, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0), .Dim = c(10L, 6L), .Dimnames = list(NULL, c("MKT", "CAP", "RF", "dummy", "dummyJAN", "adjdummy")), index = structure(c(-36494, -36466, -36435, -36405, -36374, -36344, -36313, -36282, -36252, -36221), class = "Date"), class = "zoo")

library(zoo)
library(foqat)
df2=fortify.zoo(df)
df3=svri(df2, bkip = "1 day", mode = "recipes", value = "year")
df3
#   month of year         MKT         CAP          RF dummy dummyJAN adjdummy
#1              1  0.02861950  0.02372219 0.006085278     1        1        0
#2              2  0.03618317  0.03299206 0.004950468     1        0        1
#3              3 -0.01363269 -0.01790800 0.005035065     1        0        1
#4              4  0.02977401  0.02540426 0.004816347     1        0        1
#5              5  0.04461314  0.04163062 0.004242109     0        0        0
#6              6  0.00152090 -0.00317315 0.003585007     0        0        0
#7              7 -0.03207303 -0.03732322 0.004242109     0        0        0
#8              8 -0.00792750 -0.01094740 0.004809282     0        0        0
#9              9  0.01882991  0.01470470 0.004858725     0        0        0
#10            10  0.00584478  0.00087712 0.004879905     0        0        0


问:
Learning Curve in Q-learning
My question is I wrote the Q-learning algorithm in c++ with epsilon greedy policy now I have to plot the learning curve for the Q-values. What exactly I should have to plot because I have an 11x5 Q matrix, so should I take one Q value and plot its learning or should I have to take the whole matrix for a learning curve, could you guide me with it.
Thank you</p>

答: Learning curves in RL are typically plots of returns over time, not Q-losses or anything like this. So you should run your environment, compute the total reward (aka return) and plot it at a corresponding time.

Title: Learning Curve in Q-learning


答:
The reason why testJSON.widgets.column1 is undefined is because widgets is an Array, and you're not accessing an array index.  You can access testJSON.widgets[0].column1 instead, or restructure your JSON to look like this:

```<code>{
"widgets":{
    "column1":[
        {"weight":1, "bID":1, "hideMe":false, "collapse":false, "titleOf":"Test 1", "colorOf":"color-blue", "theFunction":"functionName"},
        {"weight":2, "bID":2, "hideMe":false, "collapse":false, "titleOf":"Test 2", "colorOf":"color-red", "theFunction":"functionName"},
        {"weight":3, "bID":3, "hideMe":false, "collapse":true, "titleOf":"Test 3", "colorOf":"color-yellow", "theFunction":"functionName"}
    ],
    "column2":[
        {"weight":1, "bID":4, "hideMe":false, "collapse":false, "titleOf":"Test 4", "colorOf":"color-white", "theFunction":"functionName"},
        {"weight":3, "bID":5, "hideMe":false, "collapse":false, "titleOf":"Test 5", "colorOf":"color-green", "theFunction":"functionName"},
        {"weight":2, "bID":6, "hideMe":false, "collapse":true, "titleOf":"Test 6", "colorOf":"color-green", "theFunction":"functionName"}
    ],
    "column3":[
        {"weight":3, "bID":7, "hideMe":false, "collapse":false, "titleOf":"Test 7", "colorOf":"color-green", "theFunction":"functionName"},
        {"weight":2, "bID":8, "hideMe":false, "collapse":true, "titleOf":"Test 8", "colorOf":"color-yellow", "theFunction":"functionName"},
        {"weight":1, "bID":9, "hideMe":false, "collapse":false, "titleOf":"Test 9", "colorOf":"color-white", "theFunction":"functionName"},
    ]
}
</code>```

Update:

Actually, I think what you really want is to have a "two-dimensional" array (actually an array of arrays); named columns cannot be conveniently accessed in a loop.  This would be a better structure for your needs:

```<code>{
    "widgets": [
        [
            {"weight":1, "bID":1, "hideMe":false, "collapse":false, "titleOf":"Test 1", "colorOf":"color-blue", "theFunction":"functionName"},
            {"weight":2, "bID":2, "hideMe":false, "collapse":false, "titleOf":"Test 2", "colorOf":"color-red", "theFunction":"functionName"},
            {"weight":3, "bID":3, "hideMe":false, "collapse":true, "titleOf":"Test 3", "colorOf":"color-yellow", "theFunction":"functionName"}
        ],
        [
            {"weight":1, "bID":4, "hideMe":false, "collapse":false, "titleOf":"Test 4", "colorOf":"color-white", "theFunction":"functionName"},
            {"weight":3, "bID":5, "hideMe":false, "collapse":false, "titleOf":"Test 5", "colorOf":"color-green", "theFunction":"functionName"},
            {"weight":2, "bID":6, "hideMe":false, "collapse":true, "titleOf":"Test 6", "colorOf":"color-green", "theFunction":"functionName"}
        ],
        [
            {"weight":3, "bID":7, "hideMe":false, "collapse":false, "titleOf":"Test 7", "colorOf":"color-green", "theFunction":"functionName"},
            {"weight":2, "bID":8, "hideMe":false, "collapse":true, "titleOf":"Test 8", "colorOf":"color-yellow", "theFunction":"functionName"},
            {"weight":1, "bID":9, "hideMe":false, "collapse":false, "titleOf":"Test 9", "colorOf":"color-white", "theFunction":"functionName"}
        ]
    ]
}
</code>```

Title: JavaScript Sorting Multidimensional JSON

Body:
The reason why testJSON.widgets.column1 is undefined is because widgets is an Array, and you're not accessing an array index.  You can access testJSON.widgets[0].column1 instead, or restructure your JSON to look like this:

{
"widgets":{
    "column1":[
        {"weight":1, "bID":1, "hideMe":false, "collapse":false, "titleOf":"Test 1", "colorOf":"color-blue", "theFunction":"functionName"},
        {"weight":2, "bID":2, "hideMe":false, "collapse":false, "titleOf":"Test 2", "colorOf":"color-red", "theFunction":"functionName"},
        {"weight":3, "bID":3, "hideMe":false, "collapse":true, "titleOf":"Test 3", "colorOf":"color-yellow", "theFunction":"functionName"}
    ],
    "column2":[
        {"weight":1, "bID":4, "hideMe":false, "collapse":false, "titleOf":"Test 4", "colorOf":"color-white", "theFunction":"functionName"},
        {"weight":3, "bID":5, "hideMe":false, "collapse":false, "titleOf":"Test 5", "colorOf":"color-green", "theFunction":"functionName"},
        {"weight":2, "bID":6, "hideMe":false, "collapse":true, "titleOf":"Test 6", "colorOf":"color-green", "theFunction":"functionName"}
    ],
    "column3":[
        {"weight":3, "bID":7, "hideMe":false, "collapse":false, "titleOf":"Test 7", "colorOf":"color-green", "theFunction":"functionName"},
        {"weight":2, "bID":8, "hideMe":false, "collapse":true, "titleOf":"Test 8", "colorOf":"color-yellow", "theFunction":"functionName"},
        {"weight":1, "bID":9, "hideMe":false, "collapse":false, "titleOf":"Test 9", "colorOf":"color-white", "theFunction":"functionName"},
    ]
}

Update:

Actually, I think what you really want is to have a "two-dimensional" array (actually an array of arrays); named columns cannot be conveniently accessed in a loop.  This would be a better structure for your needs:

{
    "widgets": [
        [
            {"weight":1, "bID":1, "hideMe":false, "collapse":false, "titleOf":"Test 1", "colorOf":"color-blue", "theFunction":"functionName"},
            {"weight":2, "bID":2, "hideMe":false, "collapse":false, "titleOf":"Test 2", "colorOf":"color-red", "theFunction":"functionName"},
            {"weight":3, "bID":3, "hideMe":false, "collapse":true, "titleOf":"Test 3", "colorOf":"color-yellow", "theFunction":"functionName"}
        ],
        [
            {"weight":1, "bID":4, "hideMe":false, "collapse":false, "titleOf":"Test 4", "colorOf":"color-white", "theFunction":"functionName"},
            {"weight":3, "bID":5, "hideMe":false, "collapse":false, "titleOf":"Test 5", "colorOf":"color-green", "theFunction":"functionName"},
            {"weight":2, "bID":6, "hideMe":false, "collapse":true, "titleOf":"Test 6", "colorOf":"color-green", "theFunction":"functionName"}
        ],
        [
            {"weight":3, "bID":7, "hideMe":false, "collapse":false, "titleOf":"Test 7", "colorOf":"color-green", "theFunction":"functionName"},
            {"weight":2, "bID":8, "hideMe":false, "collapse":true, "titleOf":"Test 8", "colorOf":"color-yellow", "theFunction":"functionName"},
            {"weight":1, "bID":9, "hideMe":false, "collapse":false, "titleOf":"Test 9", "colorOf":"color-white", "theFunction":"functionName"}
        ]
    ]
}


问:
Collection view cell with horizontal inset does not remain centred when scrolled
Hey I have a collection view with the following scrolling behaviour:

The cells need to have a spacing of 16 pts between them and remain centered when scrolled. You can see in the demo only the first and last cell remain centred. My collection view width is the same width as the screen. Setup in viewDidLoad like so:

```<code>func setupCollectionView() {
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        collectionView.register(UINib(nibName: "SubtopicCollectionCell", bundle: nil), forCellWithReuseIdentifier: "SubtopicCollectionCell")
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.scrollDirection = .horizontal
        flowLayout.minimumLineSpacing = 16
        collectionView.isPagingEnabled = true
        collectionView.setCollectionViewLayout(flowLayout, animated: false)
    }
</code>```

The various delegate methods as follows:

```<code>func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 5
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: SubtopicCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: "SubtopicCollectionCell", for: indexPath) as! SubtopicCollectionCell
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: collectionView.frame.size.width * 0.78, height: collectionView.frame.size.height)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 40, bottom: 0, right: 40)
    }
</code>```

It's important that part of the next cell is displayed on the screen with the current cell centred (like the first and last cell in the demo). How do I achieve this behaviour?

答: flowLayout.minimumLineSpacing = 0</p>

Body:
Hey I have a collection view with the following scrolling behaviour:

The cells need to have a spacing of 16 pts between them and remain centered when scrolled. You can see in the demo only the first and last cell remain centred. My collection view width is the same width as the screen. Setup in viewDidLoad like so:

func setupCollectionView() {
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        collectionView.register(UINib(nibName: "SubtopicCollectionCell", bundle: nil), forCellWithReuseIdentifier: "SubtopicCollectionCell")
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.scrollDirection = .horizontal
        flowLayout.minimumLineSpacing = 16
        collectionView.isPagingEnabled = true
        collectionView.setCollectionViewLayout(flowLayout, animated: false)
    }

The various delegate methods as follows:

func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 5
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: SubtopicCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: "SubtopicCollectionCell", for: indexPath) as! SubtopicCollectionCell
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: collectionView.frame.size.width * 0.78, height: collectionView.frame.size.height)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 40, bottom: 0, right: 40)
    }

It's important that part of the next cell is displayed on the screen with the current cell centred (like the first and last cell in the demo). How do I achieve this behaviour?

Body: flowLayout.minimumLineSpacing = 0


问:
how to check the current Firebase data under uid?
I am trying to check uid from firebase Realtime database, but its only returns the current uid and when I try to check uid with previous uid then also it only returns the current uid. I had tried many ways and searched but I can't get the exact solution, please if any one could help.

here what I am using to check the uid

```<code>FirebaseAuth.getInstance().getCurrentUser().getUid();
</code>```

here is my code how I am trying to check

```<code> String userEnteredUserName = binding.textLoginUserName.getEditText().getText().toString().trim();
 String userEnteredPassword = binding.textPassword.getEditText().getText().toString().trim();
 DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
    Query checkUser = reference.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).orderByChild("userName").equalTo(userEnteredUserName);
    Log.d("uids", "uid: " + uid);
    checkUser.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            binding.textLoginUserName.setError(null);
            binding.textLoginUserName.setErrorEnabled(false);
            Log.d("users", "Username: " + snapshot.toString());

            if (snapshot.exists()) {
                String passwordFromDB = snapshot.child(userEnteredUserName).child("password").getValue(String.class);
                if (passwordFromDB.equals(userEnteredPassword)) {
      //next activity
}else{
Toast.makeText(Login.this, "Error", Toast.LENGTH_SHORT).show();
}
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

            Toast.makeText(Login.this, "Error", Toast.LENGTH_SHORT).show();

        }
    });
</code>```

In log what I get,

```<code>2022-02-06 13:13:06.173 18093-18093/abc C/uids: uid: OFtpR6bfISP3Odd9K1oGWCQmeEf2
</code>```

Here is my firebase data, "aisha12" is working which is under the current uid but when I try to check "vgbb" it returns only the current uid

答:
If I understand correctly, you are trying to allow a user to register a username and ensuring that the username is unique. Your current data structure doesn't allow you to do that query though.

Firebase Realtime Database can only order/filter on a value that is at a fixed path under each child node of the location you query. So in your current code:

```<code>reference.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).orderByChild("userName").equalTo(userEnteredUserName);
</code>```

You are querying the direct child nodes of /Users/$uid looking for the username under there. Since you're specifying the UID in that path, you're only searching under that specific user.

There is no way with your current data structure to search across all /Users, since the property you are looking for is under /Users/$uid/$username/userName, so with two dynamic keys in there, and the database can only handle one dynamic key.

To allow the query, you will need to change the data structure and remove the $userName level from it, so that you get:

```<code>Users: {
  "3l6Rm....": {
    "userName": "vgbb",
    ...
  },
  "OftpR...": {
    "userName": "aisha12",
    ...
  }
}
</code>```

Now you can search for the username with:

```<code>DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");

Query checkUser = reference.orderByChild("userName").equalTo(userEnteredUserName);
</code>```

I also recommend checking out these previous questions on allowing a user to register a unique username:

How do you prevent duplicate user properties in Firebase?

Firebase security rules to check unique value of a child #AskFirebase

How to check if usernames are unique in Firebase

unique property in Firebase

How to give unique usernames from a list of usernames to the users in the firebase

Check value already exists or not in Firebase?

Body:
I am trying to check uid from firebase Realtime database, but its only returns the current uid and when I try to check uid with previous uid then also it only returns the current uid. I had tried many ways and searched but I can't get the exact solution, please if any one could help.

here what I am using to check the uid

FirebaseAuth.getInstance().getCurrentUser().getUid();

here is my code how I am trying to check

 String userEnteredUserName = binding.textLoginUserName.getEditText().getText().toString().trim();
 String userEnteredPassword = binding.textPassword.getEditText().getText().toString().trim();
 DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
    Query checkUser = reference.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).orderByChild("userName").equalTo(userEnteredUserName);
    Log.d("uids", "uid: " + uid);
    checkUser.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            binding.textLoginUserName.setError(null);
            binding.textLoginUserName.setErrorEnabled(false);
            Log.d("users", "Username: " + snapshot.toString());

            if (snapshot.exists()) {
                String passwordFromDB = snapshot.child(userEnteredUserName).child("password").getValue(String.class);
                if (passwordFromDB.equals(userEnteredPassword)) {
      //next activity
}else{
Toast.makeText(Login.this, "Error", Toast.LENGTH_SHORT).show();
}
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

            Toast.makeText(Login.this, "Error", Toast.LENGTH_SHORT).show();

        }
    });

In log what I get,

2022-02-06 13:13:06.173 18093-18093/abc C/uids: uid: OFtpR6bfISP3Odd9K1oGWCQmeEf2

Here is my firebase data, "aisha12" is working which is under the current uid but when I try to check "vgbb" it returns only the current uid

Body:
If I understand correctly, you are trying to allow a user to register a username and ensuring that the username is unique. Your current data structure doesn't allow you to do that query though.

Firebase Realtime Database can only order/filter on a value that is at a fixed path under each child node of the location you query. So in your current code:

reference.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).orderByChild("userName").equalTo(userEnteredUserName);

You are querying the direct child nodes of /Users/$uid looking for the username under there. Since you're specifying the UID in that path, you're only searching under that specific user.

There is no way with your current data structure to search across all /Users, since the property you are looking for is under /Users/$uid/$username/userName, so with two dynamic keys in there, and the database can only handle one dynamic key.

To allow the query, you will need to change the data structure and remove the $userName level from it, so that you get:

Users: {
  "3l6Rm....": {
    "userName": "vgbb",
    ...
  },
  "OftpR...": {
    "userName": "aisha12",
    ...
  }
}

Now you can search for the username with:

DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");

Query checkUser = reference.orderByChild("userName").equalTo(userEnteredUserName);

I also recommend checking out these previous questions on allowing a user to register a unique username:

How do you prevent duplicate user properties in Firebase?

Firebase security rules to check unique value of a child #AskFirebase

How to check if usernames are unique in Firebase

unique property in Firebase

How to give unique usernames from a list of usernames to the users in the firebase

Check value already exists or not in Firebase?


问:
PHP is not recognized as an internal or external command in command prompt
I got the following error when I run a command with php

```<code>C:\xampp\htdocs>php
'php' is not recognized as an internal or external command,
operable program or batch file.
</code>```

I don't get any error when I run the command with php in following path:

```<code>C:\xampp\php>php  //do not got error here
</code>```

Why I get this error?

'php' is not recognized as an internal or external command, operable program or batch file.

答:
In latest Xampp 8.1.2
PHP path is changed to this below: Set it in your PATH variable.

```<code>C:\xampp\php\windowsXamppPhp
</code>```

Don't forget to restart the PowerShell and run as Administrator.

Body:
I got the following error when I run a command with php

C:\xampp\htdocs>php
'php' is not recognized as an internal or external command,
operable program or batch file.

I don't get any error when I run the command with php in following path:

C:\xampp\php>php  //do not got error here

Why I get this error?

'php' is not recognized as an internal or external command, operable program or batch file.

Body:
In latest Xampp 8.1.2
PHP path is changed to this below: Set it in your PATH variable.

C:\xampp\php\windowsXamppPhp

Don't forget to restart the PowerShell and run as Administrator.


问:
How to access full email source code in thunderbird message_display_action extension?
I am building an extension in Thunderbird with UI element message_display_action for my school project. I am wondering if I can access full email source code from java script file that I am using for building up my html page when pressing on button my extension. I found a funciton named getFull(messageId) in documentation at https://webextension-api.thunderbird.net/ but I don't understand how to use that function and I don't even know what messageId is. I know it is a integer but I don't know how to get that integer for a specific email. I entered permission (messagesRead) in my manifest file of extension for reading emails but i still don't know how to use that function. I didn't find any examples or tutorials on the internet so if anyone can help me or atleast point me to the right direction.</p>

答:
Getting the id of the currently displayed message

You should take a look at https://github.com/thundernest/sample-extensions/tree/master/messageDisplay, which is an example how to get the id of the currently displayed message from the messageDisplayAction using messageDisplay.getDisplayedMessage().

See also https://webextension-api.thunderbird.net/en/latest/messageDisplay.html.

messages.getFull()

Didn't find a small example using that API. As a hint you should note that this function works on the different MIME parts a mail consists of.

You will not get the complete source of the email that way. To get the raw source you would need to use messages.getRaw(). But you should probably not use getRaw() unless you really need it, because you would need to handle the complete parsing of the message yourself.


问:
batchwise values consumption using python list and dictionary
Hello all i need a little help in finding solution for a datastructure problem using python .
I have two datastructures, batches dictionary which contain batch qty for a certain batch and second datastucture so_data is list of orders. Now task is to loop over so_data and consume batchwise quantities in batches on FIFO basis.

```<code>batches = {'batch1': 200, 'batch2': 300, 'batch3': 200, 'batch4': 200,
         'batch5': 400, 'batch6': 100, 'batch7': 200, 'batch8': 300}

so_data = [50, 50, 50, 10, 340, 10, 40, 20, 150, 330, 50, 150, 20, 50, 30, 100, 60]

def batchwise_consumption(so_data, batches):
    print(batches)
    for so_qty in so_data:

        for bch,bch_qty in batches.items():
            if bch_qty > 0:
                print('order qty: ', so_qty, ', curr batch qty: ', bch_qty, ', curr batch: ', bch)
                if bch_qty >= so_qty:
                    # order fullfilled by one batch
                    batches[bch] = bch_qty - so_qty
                    print('\trem qty: ', batches[bch])
                    break # break on full filling order
                else:
                    # order fullfilled by partial batches
                    partial_qty = batches[bch]
                    batches[bch] = batches[bch] - batches[bch]
                    rem_so_qty = so_qty-partial_qty
                    print('\tpartial qty', partial_qty, ', rem so qty', rem_so_qty)
                    while partial_qty != so_qty:
                        # make so_qty from multiple batches
                        break # break on full filling order

    print(batches)
batchwise_consumption(so_data, batches)
</code>```

This problem is part of dataset, following is simulation of batchwise consumption

Any help or some better solution is appreciated.
Thanks in advance for helping .

答:
Finally resolved:
Well the task was to consume batchwise stock for Sales order list. So after looping sales order I checked:

If so_qty is less than batch qty and fit within given index of batch qty then decreased so_qty from batch qty, then appended current batch into consumed batch list of dictionary which is maintaining batchwise consumption for each order and finally set current so_qty to 0 as order is fullfilled

Else if so_qty is greater than batch qty than reduce batch qty from current so_qty, append remaining batch qty to consumed batch list, set current batch to 0 and continue with same so_qty unless it became 0 and break the loop for current so_qty when 0.

```<code>batches = {'batch1': 200, 'batch2': 300, 'batch3': 200, 'batch4': 200,
         'batch5': 400, 'batch6': 100, 'batch7': 200, 'batch8': 300, 'batch9': 50}

so_data = [50, 50, 50, 10, 340, 10, 40, 20, 150, 330, 50, 150, 20, 50, 30, 100, 60, 400]

def batchwise_consumption(so_data, batches):
    order_no=0
    for so_qty in so_data:
        order_no +=1
        print(order_no, '\tso qty ', so_qty)
        baches_consumed = []
        for bch,bch_qty in batches.items():
            if bch_qty > 0:
                if so_qty <= bch_qty:
                    batches[bch] = bch_qty - so_qty
                    baches_consumed.append({bch: so_qty})
                    so_qty = 0

                elif so_qty > bch_qty:
                    so_qty = so_qty - bch_qty
                    batches[bch] = 0
                    baches_consumed.append({bch: bch_qty})
                    continue

                if so_qty == 0:
                    break
        print('\t', baches_consumed)

batchwise_consumption(so_data, batches)
</code>```

Body:
Hello all i need a little help in finding solution for a datastructure problem using python .
I have two datastructures, batches dictionary which contain batch qty for a certain batch and second datastucture so_data is list of orders. Now task is to loop over so_data and consume batchwise quantities in batches on FIFO basis.

batches = {'batch1': 200, 'batch2': 300, 'batch3': 200, 'batch4': 200,
         'batch5': 400, 'batch6': 100, 'batch7': 200, 'batch8': 300}

so_data = [50, 50, 50, 10, 340, 10, 40, 20, 150, 330, 50, 150, 20, 50, 30, 100, 60]

def batchwise_consumption(so_data, batches):
    print(batches)
    for so_qty in so_data:

        for bch,bch_qty in batches.items():
            if bch_qty > 0:
                print('order qty: ', so_qty, ', curr batch qty: ', bch_qty, ', curr batch: ', bch)
                if bch_qty >= so_qty:
                    # order fullfilled by one batch
                    batches[bch] = bch_qty - so_qty
                    print('\trem qty: ', batches[bch])
                    break # break on full filling order
                else:
                    # order fullfilled by partial batches
                    partial_qty = batches[bch]
                    batches[bch] = batches[bch] - batches[bch]
                    rem_so_qty = so_qty-partial_qty
                    print('\tpartial qty', partial_qty, ', rem so qty', rem_so_qty)
                    while partial_qty != so_qty:
                        # make so_qty from multiple batches
                        break # break on full filling order

    print(batches)
batchwise_consumption(so_data, batches)

This problem is part of dataset, following is simulation of batchwise consumption

Any help or some better solution is appreciated.
Thanks in advance for helping .

Body:
Finally resolved:
Well the task was to consume batchwise stock for Sales order list. So after looping sales order I checked:

If so_qty is less than batch qty and fit within given index of batch qty then decreased so_qty from batch qty, then appended current batch into consumed batch list of dictionary which is maintaining batchwise consumption for each order and finally set current so_qty to 0 as order is fullfilled

Else if so_qty is greater than batch qty than reduce batch qty from current so_qty, append remaining batch qty to consumed batch list, set current batch to 0 and continue with same so_qty unless it became 0 and break the loop for current so_qty when 0.

batches = {'batch1': 200, 'batch2': 300, 'batch3': 200, 'batch4': 200,
         'batch5': 400, 'batch6': 100, 'batch7': 200, 'batch8': 300, 'batch9': 50}

so_data = [50, 50, 50, 10, 340, 10, 40, 20, 150, 330, 50, 150, 20, 50, 30, 100, 60, 400]

def batchwise_consumption(so_data, batches):
    order_no=0
    for so_qty in so_data:
        order_no +=1
        print(order_no, '\tso qty ', so_qty)
        baches_consumed = []
        for bch,bch_qty in batches.items():
            if bch_qty > 0:
                if so_qty <= bch_qty:
                    batches[bch] = bch_qty - so_qty
                    baches_consumed.append({bch: so_qty})
                    so_qty = 0

                elif so_qty > bch_qty:
                    so_qty = so_qty - bch_qty
                    batches[bch] = 0
                    baches_consumed.append({bch: bch_qty})
                    continue

                if so_qty == 0:
                    break
        print('\t', baches_consumed)

batchwise_consumption(so_data, batches)


问:
How to create couchdb indexes in hyperledger-fabric with maven build
I'm trying to create couchdb indexes in hyperledger-fabric. I'm using maven as build tool. I added my index json files under META-INF/statedb/couchdb/indexes dir structure. I tried

By adding this MATA-INF dir into the directory where the chaincode resides

By adding this MATA-INF dir into the resources folder (src\main\resources)

But indexes were not created in both cases. I used following command to verify that indexes are created.

docker logs <peer container name>  2>&1 | grep "CouchDB index"

How do I create indexes?

答:
First of all your first attempt is the correct one. To make sure the chaincode was properly packed you can check out the chaincode.tar.gz file. If you open the file there should be one directory with the name of your chaincode and one file called metadata.json

If it's not the case than you need to include the META-INF directory in the build/install/NAME_OF_YOUR_CHAINCODE directory. I use gradle so I can't provide the proper commands in Maven to copy the META-INF.

Edit: I just tested the command you provide docker logs <peer container name>  2>&1 | grep "CouchDB index". It didn't work for me as well. I had to use the docker container id: docker logs <peer container id>  2>&1 | grep "CouchDB index"


问:
CORS problem,using axios,how can this be possible?
I'm using gin to be my backend,and this is my cors middleware code.

func Cors() gin.HandlerFunc {
    return func(ctx *gin.Context) {
        method := ctx.Request.Method
        if method == "OPTIONS" {
            ctx.Header("Access-Control-Max-Age", "1728000")
            ctx.Header("Access-Control-Allow-Credentials", "true")
            ctx.Header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,PATCH,OPTIONS")
            ctx.Header("Access-Control-Allow-Headers", "Content-Type,Cookie,Authorization,Access-Control-Request-Headers,Access-Control-Request-Method,Origin,Referer,Sec-Fetch-Dest,Accept-Language,Accept-Encoding,Sec-Fetch-Mode,Sec-Fetch-Site,User-Agent,Pragma,Host,Connection,Cache-Control,Accept-Language,Accept-Encoding,X-Requested-With,X-Forwarded-For,X-Forwarded-Host,X-Forwarded-Proto,X-Forwarded-Port,X-Forwarded-Prefix,X-Real-IP,Accept")
            ctx.Header("Access-Control-Allow-Origin", ctx.Request.Header.Get("origin"))
            ctx.AbortWithStatus(http.StatusNoContent)
            return
        }
        ctx.Next()
    }
}
```
<p>In the frontend,I'm using the axios to request,and I'm using React to develop my app.<br />
Below is my setting about axios.</p>
<pre class="lang-js prettyprint-override"><code>const BASE_URL = "http://localhost:8000";

axios.defaults.baseURL = BASE_URL;
axios.defaults.withCredentials = true;
</code>```

and I abstracted a function to do a POST request

async function post<T = any, D = any>(
    url: string,
    data?: T,
    headers?: AxiosRequestHeaders
): Promise<D> {
    const res = await axios.post(url, data, {
        headers: headers,
    });
    if (res.status === 200) return Promise.resolve(res.data);
    else return Promise.reject(res.statusText);
}
```

it's interesting when I requesting on Chrome.

picture

I truly got a Access-Control-Allow-Origin header but it just said I didn't get this header in respond.

It's really weired and I don't know how to do.

答:
When different origin,we need always to put Access-Control-Allow-Origin header in responses' headers.And if we Access-Control-Allow-Credentials,this should be put in responses' headers too.

middleware should be changed like below:

func Cors() gin.HandlerFunc {
    return func(ctx *gin.Context) {
        method := ctx.Request.Method
        if method == "OPTIONS" {
            ctx.Header("Access-Control-Max-Age", "1728000")
            ctx.Header("Access-Control-Allow-Credentials", "true")
            ctx.Header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,PATCH,OPTIONS")
            ctx.Header("Access-Control-Allow-Origin", ctx.Request.Header.Get("origin"))
            ctx.Header("Access-Control-Allow-Headers", "Content-Type,Cookie,Authorization,Access-Control-Request-Headers,Access-Control-Request-Method,Origin,Referer,Sec-Fetch-Dest,Accept-Language,Accept-Encoding,Sec-Fetch-Mode,Sec-Fetch-Site,User-Agent,Pragma,Host,Connection,Cache-Control,Accept-Language,Accept-Encoding,X-Requested-With,X-Forwarded-For,X-Forwarded-Host,X-Forwarded-Proto,X-Forwarded-Port,X-Forwarded-Prefix,X-Real-IP,Accept")
            ctx.AbortWithStatus(http.StatusNoContent)
            return
        }
        ctx.Header("Access-Control-Allow-Origin", ctx.Request.Header.Get("origin"))
        ctx.Header("Access-Control-Allow-Credentials", "true")
        ctx.Next()
    }
}
```

Body:
I'm using gin to be my backend,and this is my cors middleware code.

func Cors() gin.HandlerFunc {
    return func(ctx *gin.Context) {
        method := ctx.Request.Method
        if method == "OPTIONS" {
            ctx.Header("Access-Control-Max-Age", "1728000")
            ctx.Header("Access-Control-Allow-Credentials", "true")
            ctx.Header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,PATCH,OPTIONS")
            ctx.Header("Access-Control-Allow-Headers", "Content-Type,Cookie,Authorization,Access-Control-Request-Headers,Access-Control-Request-Method,Origin,Referer,Sec-Fetch-Dest,Accept-Language,Accept-Encoding,Sec-Fetch-Mode,Sec-Fetch-Site,User-Agent,Pragma,Host,Connection,Cache-Control,Accept-Language,Accept-Encoding,X-Requested-With,X-Forwarded-For,X-Forwarded-Host,X-Forwarded-Proto,X-Forwarded-Port,X-Forwarded-Prefix,X-Real-IP,Accept")
            ctx.Header("Access-Control-Allow-Origin", ctx.Request.Header.Get("origin"))
            ctx.AbortWithStatus(http.StatusNoContent)
            return
        }
        ctx.Next()
    }
}

In the frontend,I'm using the axios to request,and I'm using React to develop my app.

Below is my setting about axios.

const BASE_URL = "http://localhost:8000";

axios.defaults.baseURL = BASE_URL;
axios.defaults.withCredentials = true;

and I abstracted a function to do a POST request

async function post<T = any, D = any>(
    url: string,
    data?: T,
    headers?: AxiosRequestHeaders
): Promise<D> {
    const res = await axios.post(url, data, {
        headers: headers,
    });
    if (res.status === 200) return Promise.resolve(res.data);
    else return Promise.reject(res.statusText);
}

it's interesting when I requesting on Chrome.

picture

I truly got a Access-Control-Allow-Origin header but it just said I didn't get this header in respond.

It's really weired and I don't know how to do.


问:
How to convert String to Array and put it in github actions matrix?
I have GitHub actions two jobs. One is running a python script to get a list [[file1, 1.0], [file2, 3.0]] and the other is to put this list in the GitHub actions matrix. But I got from python script is a string and it cannot be put into matrix. How to solve this?</p>
```<code>on:
  pull_request:
    branches: [ master, develop ]
    types: [ closed ]

jobs:
  compute-version:
    runs-on: ubuntu-latest

    outputs:
      list: ${{ steps.semver.outputs.list }}

    steps:
      - name: Run Computer Version Script
        id: semver
        run: |
          python ./.github/bump-version.py $GITHUB_REF
          res=$?
          echo "::set-output name=list::$res"

  update-yaml:
    needs: compute-version

    runs-on: ubuntu-latest

    strategy:
          matrix:
            node: ${{needs.compute-version.outputs.bump_list}}

    steps:
      - name: Checkout
        uses: actions/checkout@v2

      - name: Update Version on Yaml File
        uses: fjogeleit/yaml-update-action@master
        with:
          valueFile: ${{ matrix.node['file'] }}
          propertyPath: info.version
          value: ${{ matrix.node['version'] }}
          commitChange: true
          updateFile: true
          targetBranch: ${{needs.compute-version.outputs.target_branch}}
          masterBranchName: master
          createPR: false
          branch:  ${{needs.compute-version.outputs.target_branch}}
          message: Bump version to ${{ matrix.node['version'] }} in ${{ matrix.node['file'] }}
</code>```

答:
Using toJson and fromJSON is the only way to pass variables like Array in GitHub actions.

If you case, here is a good example on how to build what you are looking for.

More details explained on GitHub Blog post here

```<code>name: build
on: push
jobs:
  job1:
    runs-on: ubuntu-latest
    outputs:
      matrix: ${{ steps.set-matrix.outputs.matrix }}
    steps:
    - id: set-matrix
      run: echo "::set-output name=matrix::{\"include\":[{\"project\":\"foo\",\"config\":\"Debug\"},{\"project\":\"bar\",\"config\":\"Release\"}]}"
  job2:
    needs: job1
    runs-on: ubuntu-latest
    strategy:
      matrix: ${{fromJson(needs.job1.outputs.matrix)}}
    steps:
    - run: build
</code>```

Body:
I have GitHub actions two jobs. One is running a python script to get a list [[file1, 1.0], [file2, 3.0]] and the other is to put this list in the GitHub actions matrix. But I got from python script is a string and it cannot be put into matrix. How to solve this?

on:
  pull_request:
    branches: [ master, develop ]
    types: [ closed ]

jobs:
  compute-version:
    runs-on: ubuntu-latest

    outputs:
      list: ${{ steps.semver.outputs.list }}

    steps:
      - name: Run Computer Version Script
        id: semver
        run: |
          python ./.github/bump-version.py $GITHUB_REF
          res=$?
          echo "::set-output name=list::$res"

  update-yaml:
    needs: compute-version

    runs-on: ubuntu-latest

    strategy:
          matrix:
            node: ${{needs.compute-version.outputs.bump_list}}

    steps:
      - name: Checkout
        uses: actions/checkout@v2

      - name: Update Version on Yaml File
        uses: fjogeleit/yaml-update-action@master
        with:
          valueFile: ${{ matrix.node['file'] }}
          propertyPath: info.version
          value: ${{ matrix.node['version'] }}
          commitChange: true
          updateFile: true
          targetBranch: ${{needs.compute-version.outputs.target_branch}}
          masterBranchName: master
          createPR: false
          branch:  ${{needs.compute-version.outputs.target_branch}}
          message: Bump version to ${{ matrix.node['version'] }} in ${{ matrix.node['file'] }}

Body:
Using toJson and fromJSON is the only way to pass variables like Array in GitHub actions.

If you case, here is a good example on how to build what you are looking for.

More details explained on GitHub Blog post here

name: build
on: push
jobs:
  job1:
    runs-on: ubuntu-latest
    outputs:
      matrix: ${{ steps.set-matrix.outputs.matrix }}
    steps:
    - id: set-matrix
      run: echo "::set-output name=matrix::{\"include\":[{\"project\":\"foo\",\"config\":\"Debug\"},{\"project\":\"bar\",\"config\":\"Release\"}]}"
  job2:
    needs: job1
    runs-on: ubuntu-latest
    strategy:
      matrix: ${{fromJson(needs.job1.outputs.matrix)}}
    steps:
    - run: build