问:
Why, when adding two or more identical objects to state in a row, they always generate the same key?
I'm learning React and i'm stuck on this problem. I've looked for answers but couldn't find why this exact thing was happening.

When i fill in a form and submit it, a new object gets added to the state. No matter how i generate random key (for example in code below i do it with date object and getTime method), when i add two or more identical objects to the state in a row (one exactly after the other), they always generate the same key, same with math.random and all other methods i've tried.

If i add one object and then change any data even a little bit and add another and then add the same as the first one, everything works perfectly. The only problem is when i try to add the same ones in a row.

By identical objects i mean that all their {key: value} pairs contain the same data and they have the same keys.

This is how my state objects like like:

```<code>state = {
    dmd: [
      {name: 'dmd', age: 69, rich: 'yes', id: 1},
      {name: 'lk', age: 19, rich: 'true', id: 2},
      {name: 'tm', age: 83, rich: 'aye', id: 3}
    ]
  }
</code>```

Note that when i have this initial state already hard coded, when i add a new object that's the same as the 3rd one, the error doesn't occur. It's just when creating new ones.

newDmd object that is passed to addDmd method would not have id at first and would look like this:

```<code>{name: 'john', age: 22, rich: 'yes'}
</code>```

Method used to change state:

```<code>  addDmd = (newDmd) => {
    newDmd.id = new Date().getTime();
    let newArray = [...this.state.dmd, newDmd];
    this.setState({
      dmd: newArray
    });
  }
</code>```

The image below is to show you when the keys become the same (my key is 'id'). You can see that on the last 3 additions, the key is the same, starting to repeat after the second one:

I don't have enough reputation points to post an image, so here's a link: https://i.imgur.com/WQrVHlp.png

I would like to know:

Why this happens

How to fix this

Best practices regarding changing state and generating unique keys

Edit:
Adding code from where addDmd method is called.

```<code>class AddDmd extends Component {
    state = {
        name: null,
        age: null,
        rich: null
    };

    handleChange = (e) => {
        this.setState({
            [e.target.id]: e.target.value
        });
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.addDmd(this.state);
    }

    render() {
        return (
            <div>
                <form onSubmit={this.handleSubmit}>
                    <label htmlFor="name">Name:</label>
                    <input type="text" id="name" onChange={this.handleChange}></input>
                    <label htmlFor="age">Age:</label>
                    <input type="text" id="age" onChange={this.handleChange}></input>
                    <label htmlFor="rich">rich?:</label>
                    <input type="text" id="rich" onChange={this.handleChange}></input>
                    <button>Submit</button>
                </form>
            </div>
        )
    }
}
</code>```

Edit 2: added full code of class where addDmd method resides.

```<code>class App extends Component {
  state = {
    dmd: [
      {name: 'dmd', age: 69, rich: 'yes', id: 1},
      {name: 'lk', age: 19, rich: 'true', id: 2},
      {name: 'tm', age: 83, rich: 'aye', id: 3}
    ]
  }

  addDmd = (newDmd) => {
    newDmd.id = new Date().getTime();
    let newArray = [...this.state.dmd, newDmd];
    this.setState({
      dmd: newArray
    });
  }

  render() {
    return (
      <div className="App" >
        <AddDmd addDmd={this.addDmd} />
      </div>
    );
  }
}
</code>```

答:
Why this happens ?
I totally agree with the reason @Brian Thompsan mentioned.

Also, I have create a example code for your use-case where I am adding a same item with different ids (created using date/time) on the button click. Its working fine and here is the code.

```<code>import React from "react";
import Listbox from "./listBox";

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      dmd: [
        { name: "dmd", age: 69, rich: "yes", id: 1 },
        { name: "lk", age: 19, rich: "true", id: 2 },
        { name: "tm", age: 83, rich: "aye", id: 3 }
      ]
    };
  }
  addDmd = () => {
    const newId = new Date().getTime();
    console.log(newId);
    let newArray = [
      ...this.state.dmd,
      { id: newId, name: "new name", age: "new age" }
    ];
    this.setState({
      dmd: newArray
    });
  };
  render() {
    return (
      <>
        <input type="button" onClick={this.addDmd} />
        {this.state.dmd.map(item => (
          <div>
            id: {item.id} name:: {item.name}
          </div>
        ))}
      </>
    );
  }
}
export default App;
</code>```

Body:
I'm learning React and i'm stuck on this problem. I've looked for answers but couldn't find why this exact thing was happening.

When i fill in a form and submit it, a new object gets added to the state. No matter how i generate random key (for example in code below i do it with date object and getTime method), when i add two or more identical objects to the state in a row (one exactly after the other), they always generate the same key, same with math.random and all other methods i've tried.

If i add one object and then change any data even a little bit and add another and then add the same as the first one, everything works perfectly. The only problem is when i try to add the same ones in a row.

By identical objects i mean that all their {key: value} pairs contain the same data and they have the same keys.

This is how my state objects like like:

state = {
    dmd: [
      {name: 'dmd', age: 69, rich: 'yes', id: 1},
      {name: 'lk', age: 19, rich: 'true', id: 2},
      {name: 'tm', age: 83, rich: 'aye', id: 3}
    ]
  }

Note that when i have this initial state already hard coded, when i add a new object that's the same as the 3rd one, the error doesn't occur. It's just when creating new ones.

newDmd object that is passed to addDmd method would not have id at first and would look like this:

{name: 'john', age: 22, rich: 'yes'}

Method used to change state:

  addDmd = (newDmd) => {
    newDmd.id = new Date().getTime();
    let newArray = [...this.state.dmd, newDmd];
    this.setState({
      dmd: newArray
    });
  }

The image below is to show you when the keys become the same (my key is 'id'). You can see that on the last 3 additions, the key is the same, starting to repeat after the second one:

I don't have enough reputation points to post an image, so here's a link: https://i.imgur.com/WQrVHlp.png

I would like to know:

Why this happens

How to fix this

Best practices regarding changing state and generating unique keys

Edit:
Adding code from where addDmd method is called.

class AddDmd extends Component {
    state = {
        name: null,
        age: null,
        rich: null
    };

    handleChange = (e) => {
        this.setState({
            [e.target.id]: e.target.value
        });
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.addDmd(this.state);
    }

    render() {
        return (

                <form onSubmit={this.handleSubmit}>
                    Name:
                    <input type="text" id="name" onChange={this.handleChange}></input>
                    Age:
                    <input type="text" id="age" onChange={this.handleChange}></input>
                    rich?:
                    <input type="text" id="rich" onChange={this.handleChange}></input>
                    <button>Submit</button>
                </form>

        )
    }
}

Edit 2: added full code of class where addDmd method resides.

class App extends Component {
  state = {
    dmd: [
      {name: 'dmd', age: 69, rich: 'yes', id: 1},
      {name: 'lk', age: 19, rich: 'true', id: 2},
      {name: 'tm', age: 83, rich: 'aye', id: 3}
    ]
  }

  addDmd = (newDmd) => {
    newDmd.id = new Date().getTime();
    let newArray = [...this.state.dmd, newDmd];
    this.setState({
      dmd: newArray
    });
  }

  render() {
    return (

        <AddDmd addDmd={this.addDmd} />

    );
  }
}

Body:
Why this happens ?
I totally agree with the reason @Brian Thompsan mentioned.

Also, I have create a example code for your use-case where I am adding a same item with different ids (created using date/time) on the button click. Its working fine and here is the code.

import React from "react";
import Listbox from "./listBox";

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      dmd: [
        { name: "dmd", age: 69, rich: "yes", id: 1 },
        { name: "lk", age: 19, rich: "true", id: 2 },
        { name: "tm", age: 83, rich: "aye", id: 3 }
      ]
    };
  }
  addDmd = () => {
    const newId = new Date().getTime();
    console.log(newId);
    let newArray = [
      ...this.state.dmd,
      { id: newId, name: "new name", age: "new age" }
    ];
    this.setState({
      dmd: newArray
    });
  };
  render() {
    return (
      <>
        <input type="button" onClick={this.addDmd} />
        {this.state.dmd.map(item => (
          <div>
            id: {item.id} name:: {item.name}
          </div>
        ))}
      </>
    );
  }
}
export default App;


来源: stackexchange

问:
Get Index Minimum Value in Column When String - Pandas Dataframe
I have done some research on this, but couldn't find a concise method when the index is of type 'string'.

Given the following Pandas dataframe:

```<code>Platform | Action |    RPG    | Fighting
----------------------------------------
PC       |   4    |      6    |     9
Playstat |   6    |      7    |     5
Xbox     |   9    |      4    |     6
Wii      |   8    |      8    |     7
</code>```

I was trying to get the index (Platform) of the smallest value in the 'RPG' column, which would return 'Xbox'. I managed to make it work but it's not efficient, and looking for a better/quicker/condensed approach. Here is what I got:

```<code># Return the minimum value of a series of all columns values for RPG
series1 = min(ign_data.loc['RPG'])

# Find the lowest value in the series
minim = min(ign_data.loc['RPG'])

# Get the index of that value using boolean indexing
result = series1[series1 == minim].index

# Format that index to a list, and return the first (and only) element
str_result = result.format()[0]
</code>```

答:
Use Series.idxmin:

```<code>df.set_index('Platform')['RPG'].idxmin()
#'Xbox'
</code>```

or what @Quang Hoang suggests on the comments

```<code>df.loc[df['RPG'].idxmin(), 'Platform']
</code>```

if Platform already the index:

```<code>df['RPG'].idxmin()
</code>```

EDIT

```<code>df.set_index('Platform').loc['Playstat'].idxmin()
#'Fighting'

df.set_index('Platform').idxmin(axis=1)['Playstat']
#'Fighting'
</code>```

if already the index:

```<code>df.loc['Playstat'].idxmin()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have done some research on this, but couldn't find a concise method when the index is of type 'string'.

Given the following Pandas dataframe:

Platform | Action |    RPG    | Fighting
----------------------------------------
PC       |   4    |      6    |     9
Playstat |   6    |      7    |     5
Xbox     |   9    |      4    |     6
Wii      |   8    |      8    |     7

I was trying to get the index (Platform) of the smallest value in the 'RPG' column, which would return 'Xbox'. I managed to make it work but it's not efficient, and looking for a better/quicker/condensed approach. Here is what I got:

# Return the minimum value of a series of all columns values for RPG
series1 = min(ign_data.loc['RPG'])

# Find the lowest value in the series
minim = min(ign_data.loc['RPG'])

# Get the index of that value using boolean indexing
result = series1[series1 == minim].index

# Format that index to a list, and return the first (and only) element
str_result = result.format()[0]

Body:
Use Series.idxmin:

df.set_index('Platform')['RPG'].idxmin()
#'Xbox'

or what @Quang Hoang suggests on the comments

df.loc[df['RPG'].idxmin(), 'Platform']

if Platform already the index:

df['RPG'].idxmin()

EDIT

df.set_index('Platform').loc['Playstat'].idxmin()
#'Fighting'

df.set_index('Platform').idxmin(axis=1)['Playstat']
#'Fighting'

if already the index:

df.loc['Playstat'].idxmin()


问:
Python: errno13: Permission denied when trying to copy folders
Been through the numerous other 'errno13' posts, but found nothing that helps here.

The file directory is as follows:

```<code>C:\\Users\\My HP\\Desktop\\Python\\Automate_the_boring_stuff\\Misc\\Eating\\Pie\\carrot.txt
</code>```

And here's my code for copying folders:

```<code>for folderTitle, childFolders, fileNames in os.walk('C:\\Users\\My HP\\Desktop\\Python\\Automate_the_boring_stuff\\Misc\\Eating'):

     for folder in childFolders:
         shutil.copy(folder, folder + '_backup')
</code>```

Running this causes the 'errno13: Permission denied' error.
Are the folders somehow in 'in use' or otherwise not copyable? They are not open in Windows as far as I can tell. Task manager shows Windows Explorer to be inactive.

This issue exists on every editor I've tried (Geany, IDLE and jupyter are the ones I have access to).

(As an aside, opening the Python script in IDLE causes an error if you try to import shell utility; the error states that shutil can't be found. Not had this issue with Geany/Jupyter).

Can anyone help?

答:
```<code>import os
path = r"D:\test"
file_path = r"D:\tmp.txt"
while(True):
    print(len(path))
    os.mkdir(path)
    new_file_path = os.path.join(path,file_path)
    os.rename(file_path,new_file_path)
    file_path = new_file_path
    path = os.path.join(path,"test")
</code>```

the above make a longer path with inner folders, end with [WinError 206] The filename or extension is too long, at length 252

```<code>while(True):
    print(len(file_path))
    new_file_path = file_path+".txt"
    os.rename(file_path,new_file_path)
    file_path = new_file_path
</code>```

the above causes [WinError 3] The system cannot find the path specified: at length 256
using shutil.move instead of os.rename causes [Errno 2] No such file or directory
not sure that this is the problem, but try using less folder in folder

Body:
Been through the numerous other 'errno13' posts, but found nothing that helps here.

The file directory is as follows:

C:\\Users\\My HP\\Desktop\\Python\\Automate_the_boring_stuff\\Misc\\Eating\\Pie\\carrot.txt

And here's my code for copying folders:

for folderTitle, childFolders, fileNames in os.walk('C:\\Users\\My HP\\Desktop\\Python\\Automate_the_boring_stuff\\Misc\\Eating'):

     for folder in childFolders:
         shutil.copy(folder, folder + '_backup')

Running this causes the 'errno13: Permission denied' error.
Are the folders somehow in 'in use' or otherwise not copyable? They are not open in Windows as far as I can tell. Task manager shows Windows Explorer to be inactive.

This issue exists on every editor I've tried (Geany, IDLE and jupyter are the ones I have access to).

(As an aside, opening the Python script in IDLE causes an error if you try to import shell utility; the error states that shutil can't be found. Not had this issue with Geany/Jupyter).

Can anyone help?

Body:
import os
path = r"D:\test"
file_path = r"D:\tmp.txt"
while(True):
    print(len(path))
    os.mkdir(path)
    new_file_path = os.path.join(path,file_path)
    os.rename(file_path,new_file_path)
    file_path = new_file_path
    path = os.path.join(path,"test")

the above make a longer path with inner folders, end with [WinError 206] The filename or extension is too long, at length 252

while(True):
    print(len(file_path))
    new_file_path = file_path+".txt"
    os.rename(file_path,new_file_path)
    file_path = new_file_path

the above causes [WinError 3] The system cannot find the path specified: at length 256
using shutil.move instead of os.rename causes [Errno 2] No such file or directory
not sure that this is the problem, but try using less folder in folder


问:
How is C++ array recognized?
When you pass an array in C++, they get passed as a pointer. So we have to pass the size of that array explicitly.

```<code>// This will not work.
int GetSize(int* arr){
  return sizeof(arr)/size(int);
}
</code>```

But if we don't use a function to get its size and use "sizeof" in the same function where the array was initialized, now we get the correct result.

```<code>int main(){
  int arr[5];
  int size = sizeof(arr)/sizeof(int);
  cout << size << endl;
}
</code>```

So is it adequate for me to look at the array as a class with a pointer, its size and type of elements in it?

Now that I think about it, I'm not sure how C++ knows array's size in the latter code if it's just handled the same as a pointer.

答:
So is it adequate for me to look at the array as a class with a pointer, its size and type of elements in it?

No, because it is not.  A C-style array is just a chunk of contiguous memory holding elements of a given type, nothing more, nothing less.

Now that I think about it, I'm not sure how C++ knows array's size in the latter code if it's just handled the same as a pointer.

That is not how arrays are handled.

In your first example, the function only accepts a pointer, it doesn't care where that pointer comes from.  Passing in an array will decay the array into a pointer to the 1st element.  All size information is lost, and the size of the array can't be determined from the pointer alone.  That is why sizeof(arr) doesn't work in that context.  It only knows the size of the pointer itself, not the size of the array that the pointer came from.

In your second example, the actual array is in scope where sizeof() is being used.  The compiler knows the declaration of the array, so sizeof(arr) can know the actual byte size of the array.

If you really want to know the size of a passed array in a function, and don't want to pass the size explicitly as a parameter, then pass the array by reference instead of by pointer so the array's size is not lost:

template<size_t N>
int GetSize(int (&arr)[N]){
  return N;
}
```

Title: How is C++ array recognized?

Body:
When you pass an array in C++, they get passed as a pointer. So we have to pass the size of that array explicitly.

// This will not work.
int GetSize(int* arr){
  return sizeof(arr)/size(int);
}

But if we don't use a function to get its size and use "sizeof" in the same function where the array was initialized, now we get the correct result.

int main(){
  int arr[5];
  int size = sizeof(arr)/sizeof(int);
  cout << size << endl;
}

So is it adequate for me to look at the array as a class with a pointer, its size and type of elements in it?

Now that I think about it, I'm not sure how C++ knows array's size in the latter code if it's just handled the same as a pointer.


问:
WPF UniformGrid rows and column same width height
i need help with UniformGrid, or Grid, table, whatever.

Simple Version:
I have a MainWindow with only 6 Rectangle, and they should fill my entire MainWindow. When i resize the window, those 6 Rectangle need to able to resize and keep the same width and height like all the other rectangles.

I eventually need to replace my rectangles with actual content, such as 6 videos playing, or 6 web browsers, or 6 images, etc, all with same width/height, as the window resizes by the user.

Here are the rectangles.

Here is my XAML code so far. It doesn't quite work, as even if i resize the MainWindow, the rectangles all stay as "squares", they always have length = width. But i need rectangles, with sometimes the length could be greater than width, since he window is resized by user however he wants.

```<code>        <UniformGrid Rows="2" Columns="3">
            <Rectangle Stretch="UniformToFill" Fill="Black" />
            <Rectangle Stretch="UniformToFill" Fill="Blue" />
            <Rectangle Stretch="UniformToFill" Fill="Red" />
            <Rectangle Stretch="UniformToFill" Fill="Green" />
            <Rectangle Stretch="UniformToFill" Fill="Yellow" />
            <Rectangle Stretch="UniformToFill" Fill="Orange" />
        </UniformGrid>
</code>```

Complex Version:
I eventually need to allow user to display 1, 2, 4, or 6 displays, so they need to take up the entire window with width/height.

Here's how it would look if it should display 2 display. (when the user resize the window so that length > width)

答:
The Grid give's you that resizing behavior already if you define your columns and rows with star-size, which is the default. Instead of writing for example <RowDefinition Height="*"/> you can just write <RowDefinition/>.

So, this should work:

```<code><Grid>
  <Grid.RowDefinitions>
    <RowDefinition/>
    <RowDefinition/>
  </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
    <ColumnDefinition/>
    <ColumnDefinition/>
    <ColumnDefinition/>
  </Grid.ColumnDefinitions>
  <Rectangle Grid.Row="0" Fill="Black" />
  <Rectangle Grid.Column="1" Fill="Blue" />
  <Rectangle Grid.Column="2" Fill="Red" />
  <Rectangle Grid.Row="1" Fill="Green" />
  <Rectangle Grid.Row="1" Grid.Column="1" Fill="Yellow" />
  <Rectangle Grid.Row="1" Grid.Column="2" Fill="Orange" />
</Grid>
</code>```

For the complex case you need to adjust the Grid's RowDefinitions and ColumnDefinitions based on the elements that you put into that Grid and based on Window size, if you want to create columns or rows. You can set everything from Codebehind on the Grid.

Give it a name in Xaml and use in Codebehind for example grid.RowDefinitions.Add(...);

Add or remove elements in Codebehind via grid.Children.Add(...);

Set Grid.Row and Grid.Column in Codebehind via static methods Grid.SetRow and Grid.SetColumn

Body:
i need help with UniformGrid, or Grid, table, whatever.

Simple Version:
I have a MainWindow with only 6 Rectangle, and they should fill my entire MainWindow. When i resize the window, those 6 Rectangle need to able to resize and keep the same width and height like all the other rectangles.

I eventually need to replace my rectangles with actual content, such as 6 videos playing, or 6 web browsers, or 6 images, etc, all with same width/height, as the window resizes by the user.

Here are the rectangles.

Here is my XAML code so far. It doesn't quite work, as even if i resize the MainWindow, the rectangles all stay as "squares", they always have length = width. But i need rectangles, with sometimes the length could be greater than width, since he window is resized by user however he wants.

        <UniformGrid Rows="2" Columns="3">
            <Rectangle Stretch="UniformToFill" Fill="Black" />
            <Rectangle Stretch="UniformToFill" Fill="Blue" />
            <Rectangle Stretch="UniformToFill" Fill="Red" />
            <Rectangle Stretch="UniformToFill" Fill="Green" />
            <Rectangle Stretch="UniformToFill" Fill="Yellow" />
            <Rectangle Stretch="UniformToFill" Fill="Orange" />
        </UniformGrid>

Complex Version:
I eventually need to allow user to display 1, 2, 4, or 6 displays, so they need to take up the entire window with width/height.

Here's how it would look if it should display 2 display. (when the user resize the window so that length > width)

Body:
The Grid give's you that resizing behavior already if you define your columns and rows with star-size, which is the default. Instead of writing for example <RowDefinition Height="*"/> you can just write <RowDefinition/>.

So, this should work:

<Grid>
  <Grid.RowDefinitions>
    <RowDefinition/>
    <RowDefinition/>
  </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
    <ColumnDefinition/>
    <ColumnDefinition/>
    <ColumnDefinition/>
  </Grid.ColumnDefinitions>
  <Rectangle Grid.Row="0" Fill="Black" />
  <Rectangle Grid.Column="1" Fill="Blue" />
  <Rectangle Grid.Column="2" Fill="Red" />
  <Rectangle Grid.Row="1" Fill="Green" />
  <Rectangle Grid.Row="1" Grid.Column="1" Fill="Yellow" />
  <Rectangle Grid.Row="1" Grid.Column="2" Fill="Orange" />
</Grid>

For the complex case you need to adjust the Grid's RowDefinitions and ColumnDefinitions based on the elements that you put into that Grid and based on Window size, if you want to create columns or rows. You can set everything from Codebehind on the Grid.

Give it a name in Xaml and use in Codebehind for example grid.RowDefinitions.Add(...);

Add or remove elements in Codebehind via grid.Children.Add(...);

Set Grid.Row and Grid.Column in Codebehind via static methods Grid.SetRow and Grid.SetColumn


问:
Creating a custom component wrapping an input control on Angular for reactive forms
I'm trying to create a custom component with an input form control inside but I have no idea how to connect the directive formControl and formControlName to the inner input, this is my code:

```<code><div class="input-group">
    <input class="form-control form-control-sm"
        #code />
    <div class="input-group-append">
        <button type="button" class="btn btn-sm btn-success"
            (click)="search()">
            <i class="fa fa-search"></i>
        </button>
    </div>
</div>
</code>```

this is the .ts file

```<code>import { Input, Component, forwardRef, OnInit, ViewChild } from '@angular/core';
import { DefaultValueAccessor, ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
    selector: 'search-input',
    templateUrl: './search-input.component.html',
    styleUrls: ['./search-input.component.scss'],
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => SearchInputComponent),
            multi: true
        }
    ]
})
export class SearchInputComponent implements OnInit, ControlValueAccessor {
    writeValue(obj: any) {
    }

    registerOnChange(fn: any) {
    //this.valueAccesor.registerOnChange(fn);
    }

   registerOnTouched(fn: any) {
    //this.valueAccesor.registerOnTouched(fn);
   }

    setDisabledState(isDisabled: boolean) {
    //this.valueAccesor.setDisabledState(isDisabled);
    }
}
</code>```

It should

```<code><search-input formControlName="code">
</code>```

Or

```<code><search-input formControl="code">
</code>```

Please, help me with this, I don't have much experience with Angular

答:
In order to have a child component work with the same parent form, you should pass in the Parent Form instance as an input to the child component. The parent form will use the form builder to create the child form control. The child will define the template for the control.

Here is a parent form (Sandbox) with a child component (AppTestInputForm):

import { Component, OnInit } from '@angular/core';
import { FormBuilder, Form, FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-sandbox',
  templateUrl: './sandbox.component.html',
  styleUrls: ['./sandbox.component.css']
})
export class SandboxComponent implements OnInit {
  form: FormGroup;

  constructor(private formBuilder: FormBuilder) {
    this.form = formBuilder.group({
      searchValue: new FormControl('')
    });
  }
  ngOnInit() {

  }

  submit() {
    if(this.form.valid) {
      console.log(this.form.get('searchValue').value, 'submitting search value');
    }
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form [formGroup]="form" (ngSubmit)="submit()">
    <app-test-input-form [parentForm]="form"></app-test-input-form>
    <button type="submit" class="btn btn-primary">Submit</button>
 </form></code>```

Here is the child component which contains the search input:

import { Component, OnInit, Input } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-test-input-form',
  templateUrl: './test-input-form.component.html',
  styleUrls: ['./test-input-form.component.css']
})
export class TestInputFormComponent implements OnInit {
  @Input() parentForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {

  }

  ngOnInit() {

  }

  search() {
    console.log('searching with value', this.parentForm.get('searchValue').value);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="input-group" [formGroup]="parentForm">
  <input class="form-control form-control-sm" formControlName="searchValue" />
  <div class="input-group-append">
    <button type="button" class="btn btn-sm btn-success" (click)="search()">
            <i class="fa fa-search"></i>
        </button>
  </div>
</div></code>```

Body:
I'm trying to create a custom component with an input form control inside but I have no idea how to connect the directive formControl and formControlName to the inner input, this is my code:

    <input class="form-control form-control-sm"
        #code />

        <button type="button" class="btn btn-sm btn-success"
            (click)="search()">

        </button>

this is the .ts file

import { Input, Component, forwardRef, OnInit, ViewChild } from '@angular/core';
import { DefaultValueAccessor, ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
    selector: 'search-input',
    templateUrl: './search-input.component.html',
    styleUrls: ['./search-input.component.scss'],
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => SearchInputComponent),
            multi: true
        }
    ]
})
export class SearchInputComponent implements OnInit, ControlValueAccessor {
    writeValue(obj: any) {
    }

    registerOnChange(fn: any) {
    //this.valueAccesor.registerOnChange(fn);
    }

   registerOnTouched(fn: any) {
    //this.valueAccesor.registerOnTouched(fn);
   }

    setDisabledState(isDisabled: boolean) {
    //this.valueAccesor.setDisabledState(isDisabled);
    }
}

It should

<search-input formControlName="code">

Or

<search-input formControl="code">

Please, help me with this, I don't have much experience with Angular

Body:
In order to have a child component work with the same parent form, you should pass in the Parent Form instance as an input to the child component. The parent form will use the form builder to create the child form control. The child will define the template for the control.

Here is a parent form (Sandbox) with a child component (AppTestInputForm):

import { Component, OnInit } from '@angular/core';
import { FormBuilder, Form, FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-sandbox',
  templateUrl: './sandbox.component.html',
  styleUrls: ['./sandbox.component.css']
})
export class SandboxComponent implements OnInit {
  form: FormGroup;

  constructor(private formBuilder: FormBuilder) {
    this.form = formBuilder.group({
      searchValue: new FormControl('')
    });
  }
  ngOnInit() {

  }

  submit() {
    if(this.form.valid) {
      console.log(this.form.get('searchValue').value, 'submitting search value');
    }
  }

}

<form [formGroup]="form" (ngSubmit)="submit()">
    <app-test-input-form [parentForm]="form"></app-test-input-form>
    <button type="submit" class="btn btn-primary">Submit</button>
 </form>

Here is the child component which contains the search input:

import { Component, OnInit, Input } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-test-input-form',
  templateUrl: './test-input-form.component.html',
  styleUrls: ['./test-input-form.component.css']
})
export class TestInputFormComponent implements OnInit {
  @Input() parentForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {

  }

  ngOnInit() {

  }

  search() {
    console.log('searching with value', this.parentForm.get('searchValue').value);
  }
}

<div class="input-group" [formGroup]="parentForm">
  <input class="form-control form-control-sm" formControlName="searchValue" />
  <div class="input-group-append">
    <button type="button" class="btn btn-sm btn-success" (click)="search()">
            <i class="fa fa-search"></i>
        </button>
  </div>
</div>


问:
How to join multiple Kafka topics in StreamSets Data Collector?
I have a use case where I have to "join" multiple Kafka topics based on some criteria in StreamSets Data Collector. I wonder if there is some commonly adopted idiom that could solve such a problem?</p>

答: How about using the Kafka Multitopic Consumer 1 then the Stream Selector Processor 2 to route to trash or processing based on you criteria?</p>


问:
Can I write my simple Python code in a better way?
I should rewrite my own function in a better way. The function takes an iterator and a sequence of boolean functions and returns an iterator of the elements in the input iterator which returns a truthy value.

```<code>def allTrue (iterator, funz):
for i in iterator:
    count = 0
    for f in funz:
        if f(i):
            count = count+1
        if count==len(funz):
            yield i
</code>```

I tried to write this:

```<code>def allTrue2 (iterator, funz):
    return (filter (f , iterator) for f in funz)
</code>```

But it's wrong. How could I improve the code?

Output:

```<code>print(list(allTrue(range(50),
               (lambda x: x % 3 == 0,
                lambda x: x > 10,
                lambda x: x < 44)
               )))

>>> [12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42]
</code>```

答:
You can yield from a generator expression like this:</p>

```<code>def allTrue(iterator, funz):
    yield from (i for i in iterator if all(f(i) for f in funz))
</code>```

Body:
I should rewrite my own function in a better way. The function takes an iterator and a sequence of boolean functions and returns an iterator of the elements in the input iterator which returns a truthy value.

def allTrue (iterator, funz):
for i in iterator:
    count = 0
    for f in funz:
        if f(i):
            count = count+1
        if count==len(funz):
            yield i

I tried to write this:

def allTrue2 (iterator, funz):
    return (filter (f , iterator) for f in funz)

But it's wrong. How could I improve the code?

Output:

print(list(allTrue(range(50),
               (lambda x: x % 3 == 0,
                lambda x: x > 10,
                lambda x: x < 44)
               )))

>>> [12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42]

Body:
You can yield from a generator expression like this:

def allTrue(iterator, funz):
    yield from (i for i in iterator if all(f(i) for f in funz))


问:
change mysql file format and collation
I need to apply this setting to MariaDB 5.5.
Is it safe to do it on running DB? Will it affect only new databases
or old DB in Latin1/nonUTF8 might be crashed?
Of cource I will run full backup, but just want to know about others experience.</p>

```<code>[client]
default-character-set = utf8mb4

[mysqld]
innodb_file_format = Barracuda
innodb_file_per_table = 1
innodb_large_prefix

character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci
skip-character-set-client-handshake

[mysql]
default-character-set = utf8mb4
</code>```

答:
Note the "default-" -- This implies that nothing already in existence will be affected by it.

There is more than what you did to make Emojis possible.  See "best practice" in Trouble with UTF-8 characters; what I see is not what I stored

As Mech implied, existing tables will need to be ALTERed if the columns are not already CHARACTER SET utf8mb4.

Also, for Barracuda, file_per_table and large_prefix to take effect on a table, you must do an ALTER.  When finished, use SHOW CREATE TABLE as a partial variation that changes have taken effect.  ALTER TABLE t CONVERT TO utf8mb4; is probably the simplest.

Since you are using 5.5 or 5.6, there are more things that need fixing to handle indexing VARCHAR(255); see http://mysql.rjweb.org/doc.php/limits#767_limit_in_innodb_indexes

Title: change mysql file format and collation

Body:
I need to apply this setting to MariaDB 5.5.
Is it safe to do it on running DB? Will it affect only new databases
or old DB in Latin1/nonUTF8 might be crashed?
Of cource I will run full backup, but just want to know about others experience.

[client]
default-character-set = utf8mb4

[mysqld]
innodb_file_format = Barracuda
innodb_file_per_table = 1
innodb_large_prefix

character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci
skip-character-set-client-handshake

[mysql]
default-character-set = utf8mb4


问:
Keep labels at fixed distance when shrinking graph in ggplot2
I am visualizing survey data and comparing responses from black vs. white students. I created a function to create dumbbell plots.

```<code>dumbbell = function(df) {
  ggplot(df, aes(pct_responses, Domain)) +
    geom_line(aes(group=Domain)) +
    geom_point(aes(color=race), size=5) +
    vertical_theme + #custom theme that I made
    scale_color_manual(labels = c("Black Students", "White Students"),
                       values=c("#073b47", "#e59918")) +
    scale_x_continuous(expand = c(0, 0),
                       limits=c(0,100),
                       breaks = seq(0, 100, by=20),
                       labels = function(x) paste0(x,"%")) +
    labs(x = "% of Affirmative Responses") +
    scale_y_discrete(labels = wrap_format(40)) +
    geom_text_repel(aes(label=paste0(round(pct_responses),"%")), size=3.52778, family="Georgia", nudge_y=0.3, nudge_x=1.6, segment.color=NA)
}
</code>```

Even though I put in nudge_y to keep the labels at a fixed distance from the colored circles, when I save graphs as different sizes, the space between the label and the circle changes. See for example below:

```<code>dumbbell(df)
ggsave("test1.png", w=6.5, h=3, unit="in")
ggsave("test2.png", w=6.5, h=3.6, unit="in")
</code>```

How do I keep the distance fixed?

答:
nudge_y=0.3 will move the labels by 0.3 units (where the implicit distance between each y label is 1 unit). But 0.3 units along an axis will be a greater physical distance when the plot is rendered with a larger physical size. You could try to calculate the nudge amount as some fraction of the rendered height of the plot, but it's probably easier to just use vjust, which will keep the labels near the dumbbells. Here's an example (data adapted from here):

```<code>library(tidyverse)

health <- read.csv("https://raw.githubusercontent.com/selva86/datasets/master/health.csv")
health$Area <- factor(health$Area, levels=as.character(health$Area))

dat = health %>%
  slice(1:3) %>%
  gather(key, value, -Area)

ggplot(dat, aes(value, Area)) +
  geom_line(aes(group=Area)) +
  geom_point(aes(color=key), size=5) +
  geom_text(aes(label=paste0(round(value*100),"%")), size=3.52778,
            family="Georgia", vjust=-1.5) +
  scale_y_discrete(expand=c(0.2,0)) +
  theme_classic()

ggsave("test1.png", w=6.5, h=3, unit="in")
ggsave("test2.png", w=6.5, h=4, unit="in")
</code>```

Another, possibly cleaner, option is to plot the numbers right on the dumbells:

```<code>ggplot(dat, aes(value, Area)) +
  geom_line(aes(group=Area)) +
  geom_point(aes(color=key), size=9) +
  geom_text(aes(label=paste0(round(value*100, 1),"%")), size=3.5,
            family="Georgia", colour="white") +
  theme_classic()
</code>```

Body:
I am visualizing survey data and comparing responses from black vs. white students. I created a function to create dumbbell plots.

dumbbell = function(df) {
  ggplot(df, aes(pct_responses, Domain)) +
    geom_line(aes(group=Domain)) +
    geom_point(aes(color=race), size=5) +
    vertical_theme + #custom theme that I made
    scale_color_manual(labels = c("Black Students", "White Students"),
                       values=c("#073b47", "#e59918")) +
    scale_x_continuous(expand = c(0, 0),
                       limits=c(0,100),
                       breaks = seq(0, 100, by=20),
                       labels = function(x) paste0(x,"%")) +
    labs(x = "% of Affirmative Responses") +
    scale_y_discrete(labels = wrap_format(40)) +
    geom_text_repel(aes(label=paste0(round(pct_responses),"%")), size=3.52778, family="Georgia", nudge_y=0.3, nudge_x=1.6, segment.color=NA)
}

Even though I put in nudge_y to keep the labels at a fixed distance from the colored circles, when I save graphs as different sizes, the space between the label and the circle changes. See for example below:

dumbbell(df)
ggsave("test1.png", w=6.5, h=3, unit="in")
ggsave("test2.png", w=6.5, h=3.6, unit="in")

How do I keep the distance fixed?

Body:
nudge_y=0.3 will move the labels by 0.3 units (where the implicit distance between each y label is 1 unit). But 0.3 units along an axis will be a greater physical distance when the plot is rendered with a larger physical size. You could try to calculate the nudge amount as some fraction of the rendered height of the plot, but it's probably easier to just use vjust, which will keep the labels near the dumbbells. Here's an example (data adapted from here):

library(tidyverse)

health <- read.csv("https://raw.githubusercontent.com/selva86/datasets/master/health.csv")
health$Area <- factor(health$Area, levels=as.character(health$Area))

dat = health %>%
  slice(1:3) %>%
  gather(key, value, -Area)

ggplot(dat, aes(value, Area)) +
  geom_line(aes(group=Area)) +
  geom_point(aes(color=key), size=5) +
  geom_text(aes(label=paste0(round(value*100),"%")), size=3.52778,
            family="Georgia", vjust=-1.5) +
  scale_y_discrete(expand=c(0.2,0)) +
  theme_classic()

ggsave("test1.png", w=6.5, h=3, unit="in")
ggsave("test2.png", w=6.5, h=4, unit="in")

Another, possibly cleaner, option is to plot the numbers right on the dumbells:

ggplot(dat, aes(value, Area)) +
  geom_line(aes(group=Area)) +
  geom_point(aes(color=key), size=9) +
  geom_text(aes(label=paste0(round(value*100, 1),"%")), size=3.5,
            family="Georgia", colour="white") +
  theme_classic()


问:
Computing recursively defined string

A series of strings are defined recursively as follows:

Level 1: S1 = 'OuQ'

Level k: Sk = 'O' + Sk-1 + 'u' + Sk-1 + 'Q'

For example, S2 = 'O' + S1 + 'u' + S1 + 'Q' = 'OOuQuOuQQ'.

Given 3 integers k, l, and r, find all the characters of Sk[l], Sk[l+1], ..., Sk[r−1], Sk[r] (where 0<k<50, and l<r)

I tried solving this problem with pointers and recursion, but it did not work because the strings are too long for reasonable computation. My code is:

#include <stdio.h>
int main(){
    int k,l,r;
    char icon[2000],*p;
    p=icon;

    scanf("%d %d %d",&k,&l,&r);
    OuQ(&icon,k);

    int i;
    for(i=l;i<r+1;i++){
        printf("%c",*(p+i));
    }
    return 0;
}

void OuQ(char *icon,int k){
    if(k==1){
        *(icon)='O';
        *(icon+1)='u';
        *(icon+2)='Q';
        return;
    }else{
        *icon='O';
        OuQ(icon+1,k-1);
        *(icon+4)='u';
        OuQ(icon+5,k-1);
        *(icon+8)='Q';
        return;
    }
}

```

答:
Here is a non-recursive solution. Since l and r may be large, I changed them to uint64_t.

#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>

//  OuQ(k, p) returns the character at position p in S[k].
static char OuQ(int k, uint64_t p)
{
    //  Find the length of S[k-1], treating S[0] as the empty string.
    uint64_t l = 0;
    for (int i = 1; i < k; ++i)
        l = 2*l + 3;

    /*  Identify where p is in O S[k-1] u S[k-1] Q.  If it is one of the
        terminal letters, return that.  Otherwise, adjust p to the position
        within S[k-1], then reduce the problem to that (by adjusting l), and
        repeat.
    */
    while (1)
    {
        if (p < 1)
            return 'O';
        else if (p < 1+l)
            p -= 1;
        else if (p < 1+l+1)
            return 'u';
        else if (p < 1+l+1+l)
            p -= 1+l+1;
        else
            return 'Q';
        l = (l-3)/2;
    }
}

int main()
{
    /*  uint64_t is used for l and r, since they may be large.  SCNu64 is
        defined in <inttypes.h> and provides a conversion specifier for
        uint64_t.
    */
    int k;
    uint64_t l, r;
    scanf("%d%" SCNu64 "%" SCNu64, &k, &l, &r);

    for (uint64_t i = l; i <= r; ++i)
        putchar(OuQ(k, i));
    putchar('\n');
}

```

Title: Computing recursively defined string


问:
Unable to Access Local Host From Docker Container

Problem

I have two Docker containers:

a server ran with fastapi;uvicorn

a client sending a GET request to http://0.0.0.0

The server seems to work just fine as bashing curl -X GET http://0.0.0.0 works as expected. However, my docker client seems unable to get access.

After building the client container (files below), when running docker run -it --name app_client_container app_client:latest I receive the following error:

requests.exceptions.ConnectionError: HTTPConnectionPool(host='0.0.0.0', port=80): Max retries exceeded with url: / (Caused by NewConnectionError(': Failed to establish a new connection: Errno 111 Connection refused'))

Setup

My project looks like this

|- client.Dockerfile
|- client.py
|- client_req.txt
|- server.Dockerfile
|- server.py
|- server_req.txt
```

<p><strong>Client</strong></p>

<pre class="lang-py prettyprint-override"><code># client.Dockerfile
FROM python:3.8

WORKDIR /srv
WORKDIR /srv
ADD client_req.txt /srv/client_req.txt
RUN pip install -r client_req.txt

ADD . /srv
CMD python /srv/client.py

# client.py
import json
import requests
import traceback

try:
    response = requests.get('http://0.0.0.0', timeout=5)
    print(json.dumps(response.json(), indent=4))
except Exception as e:
    print('Connection could not be established :(')
    print('Here is more information:')
    traceback.print_exc()

# client_req.txt
requests
</code>```

Server

# server.Dockerfile
FROM python:3.8

WORKDIR /srv
ADD server_req.txt /srv/server_req.txt
RUN pip install -r server_req.txt

EXPOSE 80

ADD . /srv
CMD uvicorn server:app --host 0.0.0.0 --port 80 --reload

# server.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

# server_req.txt
fastapi
uvicorn
```

答:
Try running the client with docker run ... --net=host ...

Although the server exposes :80 to the host, the host's network is not, by default, available to other containers; i.e. the host's :80 is not available inside other (including the client) containers.

Alternatively, you may:

reference the host via its DNS within the container;

create a docker network and bind both containers to it (thereby also using container names to reference)

or -- somewhat equally to the previous -- use Docker Compose.

Body:
Problem

I have two Docker containers:

a server ran with fastapi;uvicorn

a client sending a GET request to http://0.0.0.0

The server seems to work just fine as bashing curl -X GET http://0.0.0.0 works as expected. However, my docker client seems unable to get access.

After building the client container (files below), when running docker run -it --name app_client_container app_client:latest I receive the following error:

requests.exceptions.ConnectionError: HTTPConnectionPool(host='0.0.0.0', port=80): Max retries exceeded with url: / (Caused by NewConnectionError(': Failed to establish a new connection: Errno 111 Connection refused'))

Setup

My project looks like this

|- client.Dockerfile
|- client.py
|- client_req.txt
|- server.Dockerfile
|- server.py
|- server_req.txt

Client

# client.Dockerfile
FROM python:3.8

WORKDIR /srv
WORKDIR /srv
ADD client_req.txt /srv/client_req.txt
RUN pip install -r client_req.txt

ADD . /srv
CMD python /srv/client.py

# client.py
import json
import requests
import traceback

try:
    response = requests.get('http://0.0.0.0', timeout=5)
    print(json.dumps(response.json(), indent=4))
except Exception as e:
    print('Connection could not be established :(')
    print('Here is more information:')
    traceback.print_exc()

# client_req.txt
requests

Server

# server.Dockerfile
FROM python:3.8

WORKDIR /srv
ADD server_req.txt /srv/server_req.txt
RUN pip install -r server_req.txt

EXPOSE 80

ADD . /srv
CMD uvicorn server:app --host 0.0.0.0 --port 80 --reload

# server.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

# server_req.txt
fastapi
uvicorn


问:
Spring cloud data flow shell : Stuck on "The stream is being deployed"
I successfully registered three apps named appSink, appSource and appProcessor as follows

```<code>dataflow:>app register --name appSource --type source --uri maven://com.example:source:jar:0.0.1-SNAPSHOT --force
Successfully registered application 'source:appSource'
dataflow:>app register --name appProcessor --type processor --uri maven://com.example:processor:jar:0.0.1-SNAPSHOT --force
Successfully registered application 'processor:appProcessor'
dataflow:>app register --name appSink --type sink --uri maven://com.example:sink:jar:0.0.1-SNAPSHOT --force
Successfully registered application 'sink:appSink'
dataflow:>app list
╔══════════╤═════════════╤════════╤════╗
║  source  │  processor  │  sink  │task║
╠══════════╪═════════════╪════════╪════╣
║appSource│appProcessor│appSink│    ║
╚══════════╧═════════════╧════════╧════╝
</code>```

I then created and deployed a stream as follows:

```<code>dataflow:>stream create --name myStream --definition 'appSource | appProcessor | appSink’
Created new stream 'myStream'
dataflow:>stream deploy --name myStream
</code>```

I get the message

```<code>Deployment request has been sent for stream 'myStream'
</code>```

In the streams list I see

```<code>║myStream1  │source-app | processor-app | sink-app│The stream is being deployed.                                         ║
</code>```

The deployment never finishes it seems. The data flow server logs are just stuck on this

```<code>o.s.c.d.spi.local.LocalAppDeployer       : Deploying app with deploymentId myStream1.source-app instance 0.
</code>```

Why is my stream not deploying successfully?

答: Add spring boot actuator dependency in your project, dataflow calls /health and /info to see if the app is deployed or not.</p>

ContentLicense: CC BY-SA 3.0

Body:
I successfully registered three apps named appSink, appSource and appProcessor as follows

dataflow:>app register --name appSource --type source --uri maven://com.example:source:jar:0.0.1-SNAPSHOT --force
Successfully registered application 'source:appSource'
dataflow:>app register --name appProcessor --type processor --uri maven://com.example:processor:jar:0.0.1-SNAPSHOT --force
Successfully registered application 'processor:appProcessor'
dataflow:>app register --name appSink --type sink --uri maven://com.example:sink:jar:0.0.1-SNAPSHOT --force
Successfully registered application 'sink:appSink'
dataflow:>app list
╔══════════╤═════════════╤════════╤════╗
║  source  │  processor  │  sink  │task║
╠══════════╪═════════════╪════════╪════╣
║appSource│appProcessor│appSink│    ║
╚══════════╧═════════════╧════════╧════╝

I then created and deployed a stream as follows:

dataflow:>stream create --name myStream --definition 'appSource | appProcessor | appSink’
Created new stream 'myStream'
dataflow:>stream deploy --name myStream

I get the message

Deployment request has been sent for stream 'myStream'

In the streams list I see

║myStream1  │source-app | processor-app | sink-app│The stream is being deployed.                                         ║

The deployment never finishes it seems. The data flow server logs are just stuck on this

o.s.c.d.spi.local.LocalAppDeployer       : Deploying app with deploymentId myStream1.source-app instance 0.

Why is my stream not deploying successfully?


问:
Obtains the name and ID of the dropped element
I am using the cdk drag and drop library to drag and drop objects.

My problem is that I am not able to obtain the data (object information: name and ID) of the dropped object.

I've tried using console.log (event.item.data) but it gives undefined.

Does anyone know how I can get the information about the dropped element?

Thanks

Stackblitz - Demo

.ts

```<code> drop(event: CdkDragDrop<string[]>) {
    console.log(event.item.data)
    if (event.previousContainer === event.container) {
      moveItemInArray(
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    } else {
      transferArrayItem(
        event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    }
  }
</code>```

html

```<code><div class="six" style=" height: 75%;">
  <div class="card-deck cardsZone">
    <div class="card myCards">
      <div class="card-body" style="overflow-y: auto;"  #activeList="cdkDropList"
      class="box-list" style="height:100%"
      cdkDropList
      cdkDropListOrientation="vertical"
      [cdkDropListData]="A"
      [cdkDropListConnectedTo]="[inactiveList]"
      (cdkDropListDropped)="drop($event)">
        <div *ngFor="let nw of A" cdkDrag>
        <div class="card mysmallCcards">
          <div class="card-body">
                   <span>{{nw.name}}</span>
          </div>
        </div>
        </div>
      </div>
    </div>
    <div class="card myCards">
      <div class="card-body" style="overflow-y: auto;" #inactiveList="cdkDropList"
      class="box-list" style="height:100%"
      cdkDropList
      cdkDropListOrientation="vertical"
      [cdkDropListData]="B"
      [cdkDropListConnectedTo]="[activeList]"
      (cdkDropListDropped)="drop($event)">
        <div *ngFor="let pr of B" cdkDrag>
        <div class="card mysmallCcards">
          <div class="card-body">
           <span>{{pr.name}}</span>
          </div>
        </div>
        </div>
      </div>
    </div>
  </div>
</div>
</code>```

Body:
I am using the cdk drag and drop library to drag and drop objects.

My problem is that I am not able to obtain the data (object information: name and ID) of the dropped object.

I've tried using console.log (event.item.data) but it gives undefined.

Does anyone know how I can get the information about the dropped element?

Thanks

Stackblitz - Demo

.ts

 drop(event: CdkDragDrop<string[]>) {
    console.log(event.item.data)
    if (event.previousContainer === event.container) {
      moveItemInArray(
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    } else {
      transferArrayItem(
        event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    }
  }

html

                   {{nw.name}}

           {{pr.name}}

Body:
The data of the item is just an input. The documentation for it is:

@Input('cdkDragData') data: T

Arbitrary data to attach to this drag instance.

So, to add the data to the event, you have to set it for each draggable element. Like this:

<div *ngFor="let nw of A" cdkDrag [cdkDragData]="nw">


答:
Why sizeof() when in the same scope? - It's because the compiler sees that you have declared int arr[5], it gets that the size is 5 at the compile time. sizeof() is computed at compile time.

Why it doesn't work when array is passed as a pointer? - It's because an array decays into a pointer here. Hence, it loses the information of size. Infact, sizeof(arr) here will give you the size of a pointer on your system - 8 bytes for 64-bit machine, 4-byte for 32-bit machine.

Title: How is C++ array recognized?


问:
How do you stop a thead background color from leaking when there are rounded corners?
I have a table with rounded corners. I've specified a different background colour only for the thead.

On all browsers other than Firefox, the background colour leaks through the rounded corner. I've set overflow to hidden but that doesn't seem to help.

How can I stop the background colour from leaking through the rounded corner of the table?

Here's the code:
https://codepen.io/ayushn21/pen/OJVRMgG

Thanks!

答:
Try this:

```<code>table {
  tr:first-child th:first-child {
    border-top-left-radius: 16px;
  }
  tr:first-child th:last-child {
    border-top-right-radius: 16px;
  }
}
</code>```

You can do the same for last row:

```<code>table {
  tr:last-child td:first-child {
    border-bottom-left-radius: 16px;
  }
  tr:last-child td:last-child {
    border-bottom-right-radius: 16px;
  }
}
</code>```

Body:
Try this:

table {
  tr:first-child th:first-child {
    border-top-left-radius: 16px;
  }
  tr:first-child th:last-child {
    border-top-right-radius: 16px;
  }
}

You can do the same for last row:

table {
  tr:last-child td:first-child {
    border-bottom-left-radius: 16px;
  }
  tr:last-child td:last-child {
    border-bottom-right-radius: 16px;
  }
}


问:
Flutter Firebase Crashlytics reports stack trace as Java class files and not as Dart files
I have integrated Flutter Crashlytics in our app, but it is reporting crashes stack trace in Java class files and not in Dart files. So it is difficult to infer what is the file and line number where this issue occurred in the flutter codebase.

Here is an example of one such crash report from Firebase Crashltytics of an Uncaught exception:

```<code>Non-fatal Exception: java.lang.Exception: NoSuchMethodError: The method 'markNeedsBuild' was called on null.
Receiver: null
Tried calling: markNeedsBuild()
       at State.setState(State.java:1168)
       at _ArgonButtonState.initState.<fn>(initState.java:107)
       at AnimationLocalStatusListenersMixin.notifyStatusListeners(AnimationLocalStatusListenersMixin.java:193)
       at AnimationController._checkStatusChanged(AnimationController.java:773)
       at AnimationController._tick(AnimationController.java:789)
       at Ticker._tick(Ticker.java:237)
       at SchedulerBinding._invokeFrameCallback(SchedulerBinding.java:1102)
       at SchedulerBinding.handleBeginFrame.<fn>(handleBeginFrame.java:1017)
       at SchedulerBinding.handleBeginFrame(SchedulerBinding.java:1015)
       at SchedulerBinding._handleBeginFrame(SchedulerBinding.java:949)
</code>```

Here is how Crashlytics is initialized:

```<code>// Pass all uncaught errors from the framework to Crashlytics.
FlutterError.onError = Crashlytics.instance.recordFlutterError;

runZoned(() {
    runApp(AppMain(homeWidget));
  }, onError: Crashlytics.instance.recordError);
</code>```

I am reporting caught exceptions as such:

```<code>Crashlytics.instance.recordError(error, stack);
</code>```

How can I configure Crashlytics to report stack trace in dart? Does Crashlytics show erroneous file names and line numbers for Dart source code?

答: Todd from Crashlytics. This is a known behavior and we are looking into possible options moving forward. Kotlin users will see a similar behavior.</p>

Body:
I have integrated Flutter Crashlytics in our app, but it is reporting crashes stack trace in Java class files and not in Dart files. So it is difficult to infer what is the file and line number where this issue occurred in the flutter codebase.

Here is an example of one such crash report from Firebase Crashltytics of an Uncaught exception:

Non-fatal Exception: java.lang.Exception: NoSuchMethodError: The method 'markNeedsBuild' was called on null.
Receiver: null
Tried calling: markNeedsBuild()
       at State.setState(State.java:1168)
       at _ArgonButtonState.initState.<fn>(initState.java:107)
       at AnimationLocalStatusListenersMixin.notifyStatusListeners(AnimationLocalStatusListenersMixin.java:193)
       at AnimationController._checkStatusChanged(AnimationController.java:773)
       at AnimationController._tick(AnimationController.java:789)
       at Ticker._tick(Ticker.java:237)
       at SchedulerBinding._invokeFrameCallback(SchedulerBinding.java:1102)
       at SchedulerBinding.handleBeginFrame.<fn>(handleBeginFrame.java:1017)
       at SchedulerBinding.handleBeginFrame(SchedulerBinding.java:1015)
       at SchedulerBinding._handleBeginFrame(SchedulerBinding.java:949)

Here is how Crashlytics is initialized:

// Pass all uncaught errors from the framework to Crashlytics.
FlutterError.onError = Crashlytics.instance.recordFlutterError;

runZoned(() {
    runApp(AppMain(homeWidget));
  }, onError: Crashlytics.instance.recordError);

I am reporting caught exceptions as such:

Crashlytics.instance.recordError(error, stack);

How can I configure Crashlytics to report stack trace in dart? Does Crashlytics show erroneous file names and line numbers for Dart source code?


问:
Navigation Component in RecyclerView Adapter
I wrote the following piece of code in the adapter.

```<code>holder.itemView.setOnClickListener {
    val action = SearchFragmentDirections.actionSearchFragmentToArtistFragment(artist.id)
    Navigation.createNavigateOnClickListener(action)
}
</code>```

And this is may navigation xml:

```<code> ...
    <fragment android:id="@+id/searchFragment"
          android:name="com.salmanseifian.spotiny.ui.search.SearchFragment"
          android:label="SearchFragment">

    <action android:id="@+id/action_searchFragment_to_artistFragment"
            app:destination="@id/artistFragment"
            app:popUpTo="@+id/searchFragment"/>
</fragment>
</code>```

but it won't work. Can anybody help?

答:
Example in kotlin

sorry about my English

Try to make a click interface and use inside the Adadapter, with it you can take the position of the item

example ==> interface

```<code>interface MyInterface {
    fun OnClickListener( string : String , position: Int, view: View)
}
</code>```

How to use inside the adapter

```<code>class ProductAdadapter(
    val context: Context,
    private var myInterface : MyInterface
    ) : RecyclerView.Adapter<ProductAdadapter.ProductViewModel>() {

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): ProductViewModel {
        val view = LayoutInflater.from(context).inflate(R.layout.item_product_adapter, parent, false)
        return ProductViewModel(view)
    }

    override fun getItemCount() =  product.size

    override fun getItemViewType(position: Int): Int {
        return super.getItemViewType(position)
    }

    override fun onBindViewHolder(holder: ProductViewModel, position: Int) {
        holder.bindView(product[position])

        holder.mcvProductsAd.setOnClickListener{
            myInterface .OnClickListener(product[position],position, it)
        }
    }

    class ProductViewModel(item: View) : RecyclerView.ViewHolder(item) {
        val mcvProductsAd = item.mcv_products_ad

        fun bindView(product: Product) {
            Glide.with(itemView.context).load(product.image).into(imageProduct)
        }
    }
}
</code>```

afterwards and just make an implement inside the Fragment

```<code>class ProductFragment : Fragment(), MyInterface {

    lateinit var productAdadapter: ProductAdadapter

    companion object {
        fun newInstance() = ProductFragment()
    }

    private lateinit var viewModel: ProductViewModel

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.product_fragment, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel = ViewModelProviders.of(this).get(ProductViewModel::class.java)

        viewModel.loadMessages().observe(viewLifecycleOwner, androidx.lifecycle.Observer {
            it?.let {
                grid.layoutManager = GridLayoutManager(context!!, 2)
                grid.adapter = ProductAdadapter(context!!, it, this)
            }
        })

        mt_product_new.setOnClickListener { activity!!.onBackPressed() }
    }

    override fun OnClickListener(string: String, position: Int, view: View) {
        Navigation.findNavController(it)
           .navigate(R.id.action_my_orders_fragment_to_offers_fragment, null)
         }

    }

}
</code>```

Body:
I wrote the following piece of code in the adapter.

holder.itemView.setOnClickListener {
    val action = SearchFragmentDirections.actionSearchFragmentToArtistFragment(artist.id)
    Navigation.createNavigateOnClickListener(action)
}

And this is may navigation xml:

 ...
    <fragment android:id="@+id/searchFragment"
          android:name="com.salmanseifian.spotiny.ui.search.SearchFragment"
          android:label="SearchFragment">

    <action android:id="@+id/action_searchFragment_to_artistFragment"
            app:destination="@id/artistFragment"
            app:popUpTo="@+id/searchFragment"/>
</fragment>

but it won't work. Can anybody help?

Body:
Example in kotlin

sorry about my English

Try to make a click interface and use inside the Adadapter, with it you can take the position of the item

example ==> interface

interface MyInterface {
    fun OnClickListener( string : String , position: Int, view: View)
}

How to use inside the adapter

class ProductAdadapter(
    val context: Context,
    private var myInterface : MyInterface
    ) : RecyclerView.Adapter<ProductAdadapter.ProductViewModel>() {

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): ProductViewModel {
        val view = LayoutInflater.from(context).inflate(R.layout.item_product_adapter, parent, false)
        return ProductViewModel(view)
    }

    override fun getItemCount() =  product.size

    override fun getItemViewType(position: Int): Int {
        return super.getItemViewType(position)
    }

    override fun onBindViewHolder(holder: ProductViewModel, position: Int) {
        holder.bindView(product[position])

        holder.mcvProductsAd.setOnClickListener{
            myInterface .OnClickListener(product[position],position, it)
        }
    }

    class ProductViewModel(item: View) : RecyclerView.ViewHolder(item) {
        val mcvProductsAd = item.mcv_products_ad

        fun bindView(product: Product) {
            Glide.with(itemView.context).load(product.image).into(imageProduct)
        }
    }
}

afterwards and just make an implement inside the Fragment

class ProductFragment : Fragment(), MyInterface {

    lateinit var productAdadapter: ProductAdadapter

    companion object {
        fun newInstance() = ProductFragment()
    }

    private lateinit var viewModel: ProductViewModel

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.product_fragment, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel = ViewModelProviders.of(this).get(ProductViewModel::class.java)

        viewModel.loadMessages().observe(viewLifecycleOwner, androidx.lifecycle.Observer {
            it?.let {
                grid.layoutManager = GridLayoutManager(context!!, 2)
                grid.adapter = ProductAdadapter(context!!, it, this)
            }
        })

        mt_product_new.setOnClickListener { activity!!.onBackPressed() }
    }

    override fun OnClickListener(string: String, position: Int, view: View) {
        Navigation.findNavController(it)
           .navigate(R.id.action_my_orders_fragment_to_offers_fragment, null)
         }

    }

}


问:
A calculator with no if's
So i wanted to ask if its possible to make a calculator but without if statements like normally i do it like:

```<code>Scanner userInput1 = new Scanner(System.in);
System.out.print("Number: ");
double number1 = userInput1.nextDouble();
System.out.print("Operator: ");
String operator = userInput1.next();
System.out.print("Another Number: ");
double number2 = userInput1.nextDouble();
if(operator.equals(+))
{
   double result = number1 + number2;
   System.out.println("The result is " + result);
}
</code>```

And i need to make a if statement and "ask" if the operator equals plus. is it possible to make it that you dont need to to that with the if statements and do it like that:

```<code>Scanner userInput1 = new Scanner(System.in);
System.out.print("Number: ");
double number1 = userInput1.nextDouble();
System.out.print("Operator: ");
String operator = userInput1.next();
System.out.print("Another Number: ");
double number2 = userInput1.nextDouble();
System.out.println("The result is " number1 + operator + number2);
</code>```

Now it would just say as example: The result is 15+17 and i wanted to ask if its possible to make it  that it gives me the result without the if statements.
Thanks

答:
It's possible to do this using no if, no switch, and no other branching language constructs*. The basic idea is to use a map of functions to do the operations, and then use the operator (as a string) to look up the function in the map.

import java.util.Map;
import java.util.HashMap;
import java.util.function.BinaryOperator;

public class Calculator {
    private static final Map<String, BinaryOperator<Integer>> operators;
    static {
        operators = new HashMap<>();
        operators.put("+", (a, b) -> a + b);
        operators.put("-", (a, b) -> a - b);
        operators.put("*", (a, b) -> a * b);
        operators.put("/", (a, b) -> a / b);
    }

    public static int doOperation(int a, int b, String op) {
        return operators.get(op).apply(a, b);
    }
}
```

This is just to demonstrate the concept, so I haven't done any console input/output or parsing, and there is no error-handling. If the string op isn't in the map, it will throw a NullPointerException; if you like, you can use getOrDefault to handle that case.

*Yes, of course there is branching going on under the hood in order to make get and getByDefault work. What I mean is that this code itself doesn't use any language constructs that are compiled to conditional jumps.

Title: A calculator with no if's

Body:
So i wanted to ask if its possible to make a calculator but without if statements like normally i do it like:

Scanner userInput1 = new Scanner(System.in);
System.out.print("Number: ");
double number1 = userInput1.nextDouble();
System.out.print("Operator: ");
String operator = userInput1.next();
System.out.print("Another Number: ");
double number2 = userInput1.nextDouble();
if(operator.equals(+))
{
   double result = number1 + number2;
   System.out.println("The result is " + result);
}

And i need to make a if statement and "ask" if the operator equals plus. is it possible to make it that you dont need to to that with the if statements and do it like that:

Scanner userInput1 = new Scanner(System.in);
System.out.print("Number: ");
double number1 = userInput1.nextDouble();
System.out.print("Operator: ");
String operator = userInput1.next();
System.out.print("Another Number: ");
double number2 = userInput1.nextDouble();
System.out.println("The result is " number1 + operator + number2);

Now it would just say as example: The result is 15+17 and i wanted to ask if its possible to make it  that it gives me the result without the if statements.
Thanks

Body:
It's possible to do this using no if, no switch, and no other branching language constructs*. The basic idea is to use a map of functions to do the operations, and then use the operator (as a string) to look up the function in the map.

import java.util.Map;
import java.util.HashMap;
import java.util.function.BinaryOperator;

public class Calculator {
    private static final Map<String, BinaryOperator<Integer>> operators;
    static {
        operators = new HashMap<>();
        operators.put("+", (a, b) -> a + b);
        operators.put("-", (a, b) -> a - b);
        operators.put("*", (a, b) -> a * b);
        operators.put("/", (a, b) -> a / b);
    }

    public static int doOperation(int a, int b, String op) {
        return operators.get(op).apply(a, b);
    }
}

This is just to demonstrate the concept, so I haven't done any console input/output or parsing, and there is no error-handling. If the string op isn't in the map, it will throw a NullPointerException; if you like, you can use getOrDefault to handle that case.

*Yes, of course there is branching going on under the hood in order to make get and getByDefault work. What I mean is that this code itself doesn't use any language constructs that are compiled to conditional jumps.


问:
System.NullReferenceException Xamarin Android arrayAdapter
initialize ArrayAdapter by class MainActivity, set it in OnCreate and still in method UpdateAdapter(BluetoothDevice device) I get error: System.NullReferenceException Object Reference not set to an instance of object

https://imgur.com/a/RFTK4NA

```<code>public class MainActivity : AppCompatActivity
    {
        ListView mainlist;
        List<string> lista = new List<string>();
        public ArrayAdapter<string> arrayAdapter; ...

        protected override void OnCreate(Bundle savedInstanceState)
        {
            mainlist = (ListView)FindViewById<ListView>(Resource.Id.listView1);
            arrayAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, lista);
            mainlist.Adapter = arrayAdapter;
</code>```

...

```<code>        skanujbtn.Click += (sender, e) =>
        {
            var receiver_ = new BluetoothDeviceReceiver();
            IntentFilter filter = new IntentFilter(BluetoothDevice.ActionFound);
            RegisterReceiver(receiver_, filter);
            if (!bluetoothAdapter.IsDiscovering) bluetoothAdapter.StartDiscovery();}

        public void UpdateAdapter(BluetoothDevice device)
        {
            lista.Add(device.Name);
            arrayAdapter.NotifyDataSetChanged();
        }
    }
</code>```

Other class

```<code>public class BluetoothDeviceReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        var action = intent.Action;
        if (action != BluetoothDevice.ActionFound)
        {
            return;
        }
    // Get the device
    var device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);

    if (device.BondState != Bond.Bonded)
    {
        MainActivity obj = new MainActivity();
        obj.UpdateAdapter(device);

    }
}
</code>```

答:
The code it is not telling much, you have to share where you use that method?

Here are my guesses:

Guess1:

Question: What is the device object initialised on?

Probably device object you are receiving in the method is null from what I can see:
If you have class something like this

```<code>public class BluetoothDevice
{
    public string Name { get; set; }
}
</code>```

You need to initalize it at least to one object before it is propagated to the method

```<code> BluetoothDevice device = new BluetoothDevice()
 {
      Name = "SomeBluetoothDevice"
 };
</code>```

Guess2:

You are invoking the UpdateAdapter() method before the initialization of the Adapter

EDIT:

Here is the issue you are creating new instance from MainActivity

```<code>if (device.BondState != Bond.Bonded)
    {
        **MainActivity obj = new MainActivity();**
        obj.UpdateAdapter(device);

    }
</code>```

that way it will create a new instance of the activity but it won't invoke the OnCreate method because that is not how Activities are created you can create by intent of type of

Anyway here is how can you fix the isssue:
Use the already existing instance from the Activity in the BluetoothDeviceReceiver add this code:

```<code>public class BluetoothDeviceReceiver : BroadcastReceiver
    {
        MainActivity mainActivity;
        public BluetoothDeviceReceiver(MainActivity mainActivity)
        {
            this.mainActivity = mainActivity;
        }

        public override void OnReceive(Context context, Intent intent)
        {
            mainActivity.UpdateAdapter(device);
        }
    }
</code>```

In the MainActivity:

```<code> skanujbtn.Click += (sender, e) =>
 {
            var receiver_ = new BluetoothDeviceReceiver(this);
...
 }
</code>```

Body:
initialize ArrayAdapter by class MainActivity, set it in OnCreate and still in method UpdateAdapter(BluetoothDevice device) I get error: System.NullReferenceException Object Reference not set to an instance of object

https://imgur.com/a/RFTK4NA

public class MainActivity : AppCompatActivity
    {
        ListView mainlist;
        List<string> lista = new List<string>();
        public ArrayAdapter<string> arrayAdapter; ...

        protected override void OnCreate(Bundle savedInstanceState)
        {
            mainlist = (ListView)FindViewById<ListView>(Resource.Id.listView1);
            arrayAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, lista);
            mainlist.Adapter = arrayAdapter;

...

        skanujbtn.Click += (sender, e) =>
        {
            var receiver_ = new BluetoothDeviceReceiver();
            IntentFilter filter = new IntentFilter(BluetoothDevice.ActionFound);
            RegisterReceiver(receiver_, filter);
            if (!bluetoothAdapter.IsDiscovering) bluetoothAdapter.StartDiscovery();}

        public void UpdateAdapter(BluetoothDevice device)
        {
            lista.Add(device.Name);
            arrayAdapter.NotifyDataSetChanged();
        }
    }

Other class

public class BluetoothDeviceReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        var action = intent.Action;
        if (action != BluetoothDevice.ActionFound)
        {
            return;
        }
    // Get the device
    var device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);

    if (device.BondState != Bond.Bonded)
    {
        MainActivity obj = new MainActivity();
        obj.UpdateAdapter(device);

    }
}

Body:
The code it is not telling much, you have to share where you use that method?

Here are my guesses:

Guess1:

Question: What is the device object initialised on?

Probably device object you are receiving in the method is null from what I can see:
If you have class something like this

public class BluetoothDevice
{
    public string Name { get; set; }
}

You need to initalize it at least to one object before it is propagated to the method

 BluetoothDevice device = new BluetoothDevice()
 {
      Name = "SomeBluetoothDevice"
 };

Guess2:

You are invoking the UpdateAdapter() method before the initialization of the Adapter

EDIT:

Here is the issue you are creating new instance from MainActivity

if (device.BondState != Bond.Bonded)
    {
        **MainActivity obj = new MainActivity();**
        obj.UpdateAdapter(device);

    }

that way it will create a new instance of the activity but it won't invoke the OnCreate method because that is not how Activities are created you can create by intent of type of

Anyway here is how can you fix the isssue:
Use the already existing instance from the Activity in the BluetoothDeviceReceiver add this code:

public class BluetoothDeviceReceiver : BroadcastReceiver
    {
        MainActivity mainActivity;
        public BluetoothDeviceReceiver(MainActivity mainActivity)
        {
            this.mainActivity = mainActivity;
        }

        public override void OnReceive(Context context, Intent intent)
        {
            mainActivity.UpdateAdapter(device);
        }
    }

In the MainActivity:

 skanujbtn.Click += (sender, e) =>
 {
            var receiver_ = new BluetoothDeviceReceiver(this);
...
 }


问:
Is there standard way of making multiple API calls combined into one HTTP request?
While designing rest API's I time to time have challenge to deal with batch operations (e.g. delete or update many entities at once) to reduce overhead of many tcp client connections. And in particular situation problem usually solves by adding custom api method for specific operation (e.g. POST /files/batchDelete which accepts ids at request body) which doesn't look pretty from point of view of rest api design principles but do the job.

But for me general solution for the problem still desirable. Recently I found Google Cloud Storage JSON API batching documentation which for me looks like pretty general solution. I mean similar format may be used for any http api, not just google cloud storage. So my question is - does anybody know kind of general standard (standard or it's draft, guideline, community effort or so) of making multiple API calls combined into one HTTP request?

I'm aware of capabilities of http/2 which include usage of single tcp connection for http requests but my question is addressed to application level. Which in my opinion still make sense because despite of ability to use http/2 taking that on application level seems like the only way to guarantee that for any client including http/1 which is currently the most used version of http.

答:
reduce overhead of many tcp client connections

If this is the crux of the issue, the easiest way to solve this is to switch to HTTP/2

In a way, HTTP/2 does exactly what you want. You open 1 connection, and using that collection you can send many HTTP requests in parallel. Unlike batching in a single HTTP request, it's mostly transparent for clients and response and requests can be processed out of order.

Ultimately batching multiple operations in a single HTTP request is always a network hack.

HTTP/2 is widely available. If HTTP/1.1 is still the most used version (this might be true, but gap is closing), this has more to do with servers not yet being set up for it, not clients.


问:
XML validation against XSD with javax.xml.validation.Validator: cannot resolve types come from 2nd XSD
I am trying to write a method that validates XML against XSD.
In my case, I have multiple XSD files.

When I use tools like IntelliJ IDEA to generate a sample XML from my main XSD everything looks fine:  the sample XML is generated and looks as I expect. So I think that my XSD files are okay.

This is my simplified main XSD:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns:ds="http://www.w3.org/2000/09/xmldsig#">

    <xsd:import schemaLocation="xmldsig-core-schema.xsd" namespace="http://www.w3.org/2000/09/xmldsig#" />

    <xsd:element name="Message">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="messageId" type="xsd:string" />
                <xsd:element ref="ds:Signature" minOccurs="0" />
            </xsd:sequence>
            <xsd:attribute name="Id" type="xsd:string" use="optional"/>
        </xsd:complexType>
    </xsd:element>
</xsd:schema>
</code>```

I downloaded and put the xmldsig-core-schema.xsd in the same directory with my XSD files.

The error I get:

```<code>org.xml.sax.SAXParseException: src-resolve: Cannot resolve the name 'ds:Signature' to a(n) 'element declaration' component.
</code>```

Java code:

```<code>InputStream xsdStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("schema/my.xsd");
// 1. InputStream xsdSignatureStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("schema/xmldsig-core-schema.xsd");

Source[] sources = new StreamSource[1];
sources[0] = new StreamSource(xsdStream);
// 2. sources[1] = new StreamSource(xsdSignatureStream);

SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
// 3. schemaFactory.setResourceResolver(new ClasspathResourceResolver());
Schema schema = schemaFactory.newSchema(sources);

Validator validator = schema.newValidator();

String xmlString = "...";
StringReader xmlStringReader = new StringReader(xmlString)
Source source = new StreamSource(xmlStringReader);
validator.validate(source);
</code>```

So it seems that the javax.xml.validation.Validator does not see my 2nd XSD file. So  I tried to add it when I initialize the javax.xml.validation.Schema but it does not help (see commented lines 1. and 2.).

I also tried to create and add an external ResourceResolver (see commented line 3.), but it does not help.

Comment:
The streams I use are initialized properly, the file paths are good, I can read the content from streams and log it as strings.

What I miss here?

答: I suspect that when the schema document is loaded using getResourceAsStream("schema/my.xsd"); it doesn't have a known base URI and therefore the relative URI xmldsig-core-schema.xsd doesn't resolve properly. Try setting a base URI (systemId property) on your StreamSource object.

Body:
I am trying to write a method that validates XML against XSD.
In my case, I have multiple XSD files.

When I use tools like IntelliJ IDEA to generate a sample XML from my main XSD everything looks fine:  the sample XML is generated and looks as I expect. So I think that my XSD files are okay.

This is my simplified main XSD:

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns:ds="http://www.w3.org/2000/09/xmldsig#">

    <xsd:import schemaLocation="xmldsig-core-schema.xsd" namespace="http://www.w3.org/2000/09/xmldsig#" />

    <xsd:element name="Message">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="messageId" type="xsd:string" />
                <xsd:element ref="ds:Signature" minOccurs="0" />
            </xsd:sequence>
            <xsd:attribute name="Id" type="xsd:string" use="optional"/>
        </xsd:complexType>
    </xsd:element>
</xsd:schema>

I downloaded and put the xmldsig-core-schema.xsd in the same directory with my XSD files.

The error I get:

org.xml.sax.SAXParseException: src-resolve: Cannot resolve the name 'ds:Signature' to a(n) 'element declaration' component.

Java code:

InputStream xsdStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("schema/my.xsd");
// 1. InputStream xsdSignatureStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("schema/xmldsig-core-schema.xsd");

Source[] sources = new StreamSource[1];
sources[0] = new StreamSource(xsdStream);
// 2. sources[1] = new StreamSource(xsdSignatureStream);

SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
// 3. schemaFactory.setResourceResolver(new ClasspathResourceResolver());
Schema schema = schemaFactory.newSchema(sources);

Validator validator = schema.newValidator();

String xmlString = "...";
StringReader xmlStringReader = new StringReader(xmlString)
Source source = new StreamSource(xmlStringReader);
validator.validate(source);

So it seems that the javax.xml.validation.Validator does not see my 2nd XSD file. So  I tried to add it when I initialize the javax.xml.validation.Schema but it does not help (see commented lines 1. and 2.).

I also tried to create and add an external ResourceResolver (see commented line 3.), but it does not help.

Comment:
The streams I use are initialized properly, the file paths are good, I can read the content from streams and log it as strings.

What I miss here?


问:
WAMP Curl installation
I have uncomment the following from the php.ini file

```<code>;extension=php_bz2.dll
extension=php_curl.dll
;extension=php_dba.dll
</code>```

Also ,I have copied the php_curl.dll to windows\system32 and restart the apache server.

I am testing the follwoing script

```<code><?php

$curl_handle=curl_init();
curl_setopt($curl_handle,CURLOPT_URL,'http://example.com');
curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
$buffer = curl_exec($curl_handle);
curl_close($curl_handle);

if (empty($buffer))
{
    print "Sorry, example.com are a bunch of poopy-heads.<p>";
}
else
{
    print $buffer;
}
?>
</code>```

and getting the following error

```<code>Fatal error: Call to undefined function curl_init() in C:\wamp\www\t.php on line 3
</code>```

any help will be appreciated ?

答:
Or even simpler, click the wamp icon in the notification area (bottom right of your screen),
go through PHP > PHP extensions and click the second item 'php_curl'.
Wamp will restart automatically.</p>

ContentLicense: CC BY-SA 2.5

Title: WAMP Curl installation

Body:
I have uncomment the following from the php.ini file

;extension=php_bz2.dll
extension=php_curl.dll
;extension=php_dba.dll

Also ,I have copied the php_curl.dll to windows\system32 and restart the apache server.

I am testing the follwoing script

<?php

$curl_handle=curl_init();
curl_setopt($curl_handle,CURLOPT_URL,'http://example.com');
curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
$buffer = curl_exec($curl_handle);
curl_close($curl_handle);

if (empty($buffer))
{
    print "Sorry, example.com are a bunch of poopy-heads.
";
}
else
{
    print $buffer;
}
?>

and getting the following error

Fatal error: Call to undefined function curl_init() in C:\wamp\www\t.php on line 3

any help will be appreciated ?


问:
Keep receiving Sorry, it is not possible to delete all non-frozen rows
I have a script on Google Apps Script, the script is working ok but I keep receiving

Sorry, it is not possible to delete all non-frozen rows line 70

Here is related part of the code:

```<code>  //start delete rows
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();

  var rowsDeleted = 0;
  for (var i = 0; i+1 <= numRows - 1; i++) {
    var row = values[i+1];
    if (row > '') { // This searches all cells in columns A (change to row[1] for columns B and so on)
  and deletes row if cell is empty or has value 'delete'.
      sheet.deleteRow((parseInt(i)+1) - rowsDeleted);
      rowsDeleted++;
    }
  };
  //end delete rows

  function onOpen() {
  var menu = [
    { name: "? Help and Support »",    functionName: "help"},
    null,
    { name: "Step 1: Authorize",   functionName: "init"      },
    { name: "Step 2: Schedule Reports", functionName: "configure" },
    null,
    { name: "? Uninstall (Stop)",    functionName: "reset"     },
    null
  ];
  SpreadsheetApp.getActiveSpreadsheet()
  .addMenu("? Drive Activity Report", menu);
  }

  function help() {
  var html = HtmlService.createHtmlOutputFromFile('help')
  .setTitle("Google Scripts Support")
  .setWidth(400)
  .setHeight(160);
  var ss = SpreadsheetApp.getActive();
  ss.show(html);
  }
</code>```

I have added a picture, I don't have any lines left as they are all deleted after the emails are sent, this all works except that I receive a daily report regarding non frozen rows.
Is the report perhaps complaining because the last row is blank and cannot be frozen or deleted?
image of spreadsheet as requested

I am including a copy of the error report I receive each day, regarding non frozen rows, as stated in my last comment, there are no errors in any of the script logs.image of daily report on non frozen rows

The answer seems to be that the rows have to be frozen before delete, I have added the freeze code but I am not sure if this is now correct

```<code>//start delete rows
function deleteRows() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();
     var numRowsFr = 1;
     sheet.setFrozenRows(numRowsFr);
  var rowsDeleted = 0;
  for (var i = 0; i <= numRows - 1; i++) {
    var row = values[i];
    if (row[0] == 'delete' || row[0] == '') { // This searches all cells in columns A (change to row[1] for columns B and so on) and deletes row if cell is empty or has value 'delete'.
      sheet.deleteRow((parseInt(i)+1) - rowsDeleted);
      rowsDeleted++;
    }
  }
};

//end delete rows
</code>```

答:
Deleting Rows

```<code>function deletingRows() {
  var sh=SpreadsheetApp.getActiveSheet();
  var v=sh.getDataRange().getValues();
  var d=0;
  v.forEach(function(r,i,a){if(!r[0] || r[0]=='delete'){sh.deleteRow(i+1-d++)}});
}
</code>```

Body:
I have a script on Google Apps Script, the script is working ok but I keep receiving

Sorry, it is not possible to delete all non-frozen rows line 70

Here is related part of the code:

  //start delete rows
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();

  var rowsDeleted = 0;
  for (var i = 0; i+1 <= numRows - 1; i++) {
    var row = values[i+1];
    if (row > '') { // This searches all cells in columns A (change to row[1] for columns B and so on)
  and deletes row if cell is empty or has value 'delete'.
      sheet.deleteRow((parseInt(i)+1) - rowsDeleted);
      rowsDeleted++;
    }
  };
  //end delete rows

  function onOpen() {
  var menu = [
    { name: "? Help and Support »",    functionName: "help"},
    null,
    { name: "Step 1: Authorize",   functionName: "init"      },
    { name: "Step 2: Schedule Reports", functionName: "configure" },
    null,
    { name: "? Uninstall (Stop)",    functionName: "reset"     },
    null
  ];
  SpreadsheetApp.getActiveSpreadsheet()
  .addMenu("? Drive Activity Report", menu);
  }

  function help() {
  var html = HtmlService.createHtmlOutputFromFile('help')
  .setTitle("Google Scripts Support")
  .setWidth(400)
  .setHeight(160);
  var ss = SpreadsheetApp.getActive();
  ss.show(html);
  }

I have added a picture, I don't have any lines left as they are all deleted after the emails are sent, this all works except that I receive a daily report regarding non frozen rows.
Is the report perhaps complaining because the last row is blank and cannot be frozen or deleted?
image of spreadsheet as requested

I am including a copy of the error report I receive each day, regarding non frozen rows, as stated in my last comment, there are no errors in any of the script logs.image of daily report on non frozen rows

The answer seems to be that the rows have to be frozen before delete, I have added the freeze code but I am not sure if this is now correct

//start delete rows
function deleteRows() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();
     var numRowsFr = 1;
     sheet.setFrozenRows(numRowsFr);
  var rowsDeleted = 0;
  for (var i = 0; i <= numRows - 1; i++) {
    var row = values[i];
    if (row[0] == 'delete' || row[0] == '') { // This searches all cells in columns A (change to row[1] for columns B and so on) and deletes row if cell is empty or has value 'delete'.
      sheet.deleteRow((parseInt(i)+1) - rowsDeleted);
      rowsDeleted++;
    }
  }
};

//end delete rows

Body:
Deleting Rows

function deletingRows() {
  var sh=SpreadsheetApp.getActiveSheet();
  var v=sh.getDataRange().getValues();
  var d=0;
  v.forEach(function(r,i,a){if(!r[0] || r[0]=='delete'){sh.deleteRow(i+1-d++)}});
}


问:
Disable Pentaho Logging
I am new to Pentaho and had a question regarding the PDI Logs. All the running and error logs are appended in the file pdi.log in Kettle/Data Integration/logs. The file keeps increasing in size which is creating memory issues.
I want to find a way to stop this logging. I have removed logging from Setting->Logs of a job, but the logs are still getting created and appended to pdi.log
I am working on version 8.3
Can anyone help me with this</p>

答:
The logging defined in Log4J configuration file. By default log data append in log file available in installation folder.

To stop logging into file you have to comment out file appender's defined in loggers as below

Existing: this log4j.xml configuration file available in classes folder

This line need to be commented in both jobs and transformation logger definition

appender-ref ref="pdi-execution-appender"

Rather than disabling logging recommendation is you can redirect logging into another location where you have enough memory for future tracking. to change log file path please change path defined in corresponding appender definition.

Title: Disable Pentaho Logging


问:
aws sam cli-colored output in jenkins console
From version 0.33.1 onwards, aws-sam-cli supports colored output. I'm trying to run the sam deploy command from Jenkins pipeline and the output is not displaying in colored format. I've installed ANSIColor Jenkins plugin and wrapped the sam deploy command with ansiColor('xterm') {}. The command works as expected and the Cloudformation stack is getting created. The concern is the output is not in colored format.

```<code>node {
stage('Example') {
    ansiColor('xterm') {
        sh "sam deploy --parameter-overrides ${someparameter} --template-file ${templatefile} --stack-name ${stackname} --capabilities CAPABILITY_NAMED_IAM  --no-fail-on-empty-changeset --no-execute-changeset"
   }
 }
}
</code>```

In order to verify my Jenkins, I tried test-snippet in Jenkins and it displayed the colored output.

```<code>ansiColor('xterm') {
    stage "\u001B[31mI'm Red\u001B[0m Now not"
}
</code>```

So Jenkins is able to display ANSI color, but the aws-sam-cli output is not in colored format.

Any ideas or pointers would be helpful.

答:
aws-sam-cli uses click library to format its output, including color handling.

The documentation for click explains why you're seeing what you're seeing:

Starting with Click 2.0, the echo() function gained extra
  functionality to deal with ANSI colors and styles. [...]

Primarily this means that:

Click’s echo() function will automatically strip ANSI color codes if the stream is not connected to a terminal.

This is a typical behavior of most programs, however some programs allow overriding this, usually with --color parameter.

In your case, I'd suggest asking for an enhancement on click's issue tracker.

Edit: There's already been one.

Body:
From version 0.33.1 onwards, aws-sam-cli supports colored output. I'm trying to run the sam deploy command from Jenkins pipeline and the output is not displaying in colored format. I've installed ANSIColor Jenkins plugin and wrapped the sam deploy command with ansiColor('xterm') {}. The command works as expected and the Cloudformation stack is getting created. The concern is the output is not in colored format.

node {
stage('Example') {
    ansiColor('xterm') {
        sh "sam deploy --parameter-overrides ${someparameter} --template-file ${templatefile} --stack-name ${stackname} --capabilities CAPABILITY_NAMED_IAM  --no-fail-on-empty-changeset --no-execute-changeset"
   }
 }
}

In order to verify my Jenkins, I tried test-snippet in Jenkins and it displayed the colored output.

ansiColor('xterm') {
    stage "\u001B[31mI'm Red\u001B[0m Now not"
}

So Jenkins is able to display ANSI color, but the aws-sam-cli output is not in colored format.

Any ideas or pointers would be helpful.