问:
How make cutting in div from rectangle?
I want cutting from div the rectangle with css.

example: https://i.imgur.com/WnUDDhw.png

I want cutting area upping transparent,  which pick up body background color. (transparent)

How to make it?

答:
The basic idea could be done with borders with opacity set.

.bg {
width:400px;
height: 300px;
background-image: url('https://placekitten.com/400/300')
}

.weirdBox {
   box-sizing: border-box;
   border-style: solid;
   border-width: 30px 50px;
   border-color: rgba(0, 0, 0, .5);
   width: 200px;
   height: 200px;
   margin-left: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="bg">
<div class="weirdBox"></div>
</div></code>```

Title: How make cutting in div from rectangle?

Body:
The basic idea could be done with borders with opacity set.

.bg {
width:400px;
height: 300px;
background-image: url('https://placekitten.com/400/300')
}

.weirdBox {
   box-sizing: border-box;
   border-style: solid;
   border-width: 30px 50px;
   border-color: rgba(0, 0, 0, .5);
   width: 200px;
   height: 200px;
   margin-left: 50px;
}

<div class="bg">
<div class="weirdBox"></div>
</div>


来源: stackexchange

问:
Displaying rows dynamically
i want to show all the records which are in ms access database,but it displays only one record...
I have the following code

```<code>private void Form1_Load(object sender, EventArgs e)
    {
        OleDbConnection con = new OleDbConnection();
        con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Documents and Settings\\mayur patil\\My Documents\\Dairy_db\\tblCompany.mdb";
        con.Open();
        OleDbDataAdapter da = new OleDbDataAdapter();
        DataSet ds = new DataSet();
        string sql = "SELECT * From tblCompany";

        da = new System.Data.OleDb.OleDbDataAdapter(sql, con);
        da.Fill(ds);
        DataRow dr = ds.Tables[0].Rows[0];
        int cnt = ds.Tables[0].Rows.Count;
        textBox1.Text = cnt.ToString();
        for (int i = 0; i < cnt; i++)
        {
            dataGridView1.Rows[i].Cells[0].Value = dr.ItemArray.GetValue(1).ToString();
            dataGridView1.Rows[i].Cells[1].Value = dr.ItemArray.GetValue(2).ToString();
        }

    }
</code>```

how can i display all the records from the ms access database,in my DataGridView?

答:
```<code>dataGridView1.Rows.Add(cnt);
for (int i = 0; i < cnt; i++)
{
    DataRow row = ds.Tables[0].Rows[i];
    dataGridView1.Rows[i].Cells[0].Value = row.ItemArray.GetValue(0).ToString();
    dataGridView1.Rows[i].Cells[1].Value = row.ItemArray.GetValue(1).ToString();
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Displaying rows dynamically

Body:
i want to show all the records which are in ms access database,but it displays only one record...
I have the following code

private void Form1_Load(object sender, EventArgs e)
    {
        OleDbConnection con = new OleDbConnection();
        con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Documents and Settings\\mayur patil\\My Documents\\Dairy_db\\tblCompany.mdb";
        con.Open();
        OleDbDataAdapter da = new OleDbDataAdapter();
        DataSet ds = new DataSet();
        string sql = "SELECT * From tblCompany";

        da = new System.Data.OleDb.OleDbDataAdapter(sql, con);
        da.Fill(ds);
        DataRow dr = ds.Tables[0].Rows[0];
        int cnt = ds.Tables[0].Rows.Count;
        textBox1.Text = cnt.ToString();
        for (int i = 0; i < cnt; i++)
        {
            dataGridView1.Rows[i].Cells[0].Value = dr.ItemArray.GetValue(1).ToString();
            dataGridView1.Rows[i].Cells[1].Value = dr.ItemArray.GetValue(2).ToString();
        }

    }

how can i display all the records from the ms access database,in my DataGridView?


问:
Jest mocking return value of a static method of connected component
I am unit testing my React app with jest and enzyme and all is good until I happened to test a class component connected with Redux. I went ahead and tested it by wrapping the component with a  and then shallow mounting it. However I am not able to mock return value of the static methods defined in my connected component.

Below is my sample code:

```<code>const wrapper = shallow(
    <Provider store={store}>
        <TestComponent {...props}  />
    </Provider>
).dive();
</code>```

Now when I try to mock the return value of static method defined in TestComponent, it doesn't have any effect, it fails:

```<code>TestComponent.myStaticMethod = jest.fn().mockReturnValue(true);
</code>```

Interesting part is, if I export the unconnected component as also suggested in redux docs, the above mock syntax work well. Is it fine to export the unconnected component just for the purpose of testing? I tried mocking before the shallow and then after it, both ways didn't work.

答:
connect returns a new component so you cannot override the static methods of the wrapped component in this way, (which is not a good idea like Andrew said)

But assuming this is what you want to do, you can mock the connect function from react-redux to return the original component

then pass all the props it gets from mapStateToProps and mapDispatchToProps as a standard React props

```<code>import MyComponent from './MyComponent';

jest.mock('react-redux' () => ({
   connect: () => Component => Component
}))

MyComponent.myStaticMethod = jest.fn().mockReturnValue(true);

shallow(<MyComponent {...props}/>)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am unit testing my React app with jest and enzyme and all is good until I happened to test a class component connected with Redux. I went ahead and tested it by wrapping the component with a  and then shallow mounting it. However I am not able to mock return value of the static methods defined in my connected component.

Below is my sample code:

const wrapper = shallow(
    <Provider store={store}>
        <TestComponent {...props}  />
    </Provider>
).dive();

Now when I try to mock the return value of static method defined in TestComponent, it doesn't have any effect, it fails:

TestComponent.myStaticMethod = jest.fn().mockReturnValue(true);

Interesting part is, if I export the unconnected component as also suggested in redux docs, the above mock syntax work well. Is it fine to export the unconnected component just for the purpose of testing? I tried mocking before the shallow and then after it, both ways didn't work.

Body:
connect returns a new component so you cannot override the static methods of the wrapped component in this way, (which is not a good idea like Andrew said)

But assuming this is what you want to do, you can mock the connect function from react-redux to return the original component

then pass all the props it gets from mapStateToProps and mapDispatchToProps as a standard React props

import MyComponent from './MyComponent';

jest.mock('react-redux' () => ({
   connect: () => Component => Component
}))

MyComponent.myStaticMethod = jest.fn().mockReturnValue(true);

shallow(<MyComponent {...props}/>)


问:
-50 error when converting PCM buffer with AVAudioConverter
I'm trying to convert a AVAudioPCMBuffer with a 44100 sample rate to one with a 48000 sample rate, but I always get an exception (-50 error) when converting. Here's the code:

```<code>guard let deviceFormat = AVAudioFormat(standardFormatWithSampleRate: 48000.0, channels: 1) else {
    preconditionFailure()
}

// This file is saved as mono 44100
guard let lowToneURL = Bundle.main.url(forResource: "Tone220", withExtension: "wav") else {
    preconditionFailure()
}
guard let audioFile = try? AVAudioFile(forReading: lowToneURL) else {
    preconditionFailure()
}

let tempBuffer = AVAudioPCMBuffer(pcmFormat: audioFile.processingFormat,
                                       frameCapacity: AVAudioFrameCount(audioFile.length))!
tempBuffer.frameLength = tempBuffer.frameCapacity
    do { try audioFile.read(into: tempBuffer) } catch {
        assertionFailure("*** Caught: \(error)")
    }

guard let converter = AVAudioConverter(from: audioFile.processingFormat, to: deviceFormat) else {
    preconditionFailure()
}
guard let convertedBuffer = AVAudioPCMBuffer(pcmFormat: deviceFormat,
                                                     frameCapacity: AVAudioFrameCount(audioFile.length)) else {
    preconditionFailure()
}
convertedBuffer.frameLength = tempBuffer.frameCapacity
do { try converter.convert(to: convertedBuffer, from: tempBuffer) } catch {
     assertionFailure("*** Caught: \(error)")
}
</code>```

Any ideas?

答:
An Apple engineer answered this on their dev forums. I missed that the convert(to:from:) variant of AVAudioConverter can't convert sample rate so you have to use the withInputFrom variant. The docs on that aren't too clear but I came up with:

```<code>private func pcmBufferForFile(filename: String, sampleRate: Float) -> AVAudioPCMBuffer {

    guard let newFormat = AVAudioFormat(standardFormatWithSampleRate: Double(sampleRate), channels: 1) else {
        preconditionFailure()
    }
    guard let url = Bundle.main.url(forResource: filename, withExtension: "wav") else {
        preconditionFailure()
    }
    guard let audioFile = try? AVAudioFile(forReading: url) else {
        preconditionFailure()
    }
    guard let tempBuffer = AVAudioPCMBuffer(pcmFormat: audioFile.processingFormat,
                                            frameCapacity: AVAudioFrameCount(audioFile.length)) else {
        preconditionFailure()
    }

    let conversionRatio = sampleRate / Float(tempBuffer.format.sampleRate)
    let newLength = Float(audioFile.length) * conversionRatio
    guard let newBuffer = AVAudioPCMBuffer(pcmFormat: newFormat,
                                           frameCapacity: AVAudioFrameCount(newLength)) else {
        preconditionFailure()
    }

    do { try audioFile.read(into: tempBuffer) } catch {
        preconditionFailure()
    }
    guard let converter = AVAudioConverter(from: audioFile.processingFormat, to: newFormat) else {
        preconditionFailure()
    }
    var error: NSError?
    converter.convert(to: newBuffer, error: &error, withInputFrom: { (packetCount, statusPtr) -> AVAudioBuffer? in
        statusPtr.pointee = .haveData
        return tempBuffer
    })
    if error != nil {
        print("*** Conversion error: \(error!)")
    }
    return newBuffer
}
</code>```

Body:
I'm trying to convert a AVAudioPCMBuffer with a 44100 sample rate to one with a 48000 sample rate, but I always get an exception (-50 error) when converting. Here's the code:

guard let deviceFormat = AVAudioFormat(standardFormatWithSampleRate: 48000.0, channels: 1) else {
    preconditionFailure()
}

// This file is saved as mono 44100
guard let lowToneURL = Bundle.main.url(forResource: "Tone220", withExtension: "wav") else {
    preconditionFailure()
}
guard let audioFile = try? AVAudioFile(forReading: lowToneURL) else {
    preconditionFailure()
}

let tempBuffer = AVAudioPCMBuffer(pcmFormat: audioFile.processingFormat,
                                       frameCapacity: AVAudioFrameCount(audioFile.length))!
tempBuffer.frameLength = tempBuffer.frameCapacity
    do { try audioFile.read(into: tempBuffer) } catch {
        assertionFailure("*** Caught: \(error)")
    }

guard let converter = AVAudioConverter(from: audioFile.processingFormat, to: deviceFormat) else {
    preconditionFailure()
}
guard let convertedBuffer = AVAudioPCMBuffer(pcmFormat: deviceFormat,
                                                     frameCapacity: AVAudioFrameCount(audioFile.length)) else {
    preconditionFailure()
}
convertedBuffer.frameLength = tempBuffer.frameCapacity
do { try converter.convert(to: convertedBuffer, from: tempBuffer) } catch {
     assertionFailure("*** Caught: \(error)")
}

Any ideas?

Body:
An Apple engineer answered this on their dev forums. I missed that the convert(to:from:) variant of AVAudioConverter can't convert sample rate so you have to use the withInputFrom variant. The docs on that aren't too clear but I came up with:

private func pcmBufferForFile(filename: String, sampleRate: Float) -> AVAudioPCMBuffer {

    guard let newFormat = AVAudioFormat(standardFormatWithSampleRate: Double(sampleRate), channels: 1) else {
        preconditionFailure()
    }
    guard let url = Bundle.main.url(forResource: filename, withExtension: "wav") else {
        preconditionFailure()
    }
    guard let audioFile = try? AVAudioFile(forReading: url) else {
        preconditionFailure()
    }
    guard let tempBuffer = AVAudioPCMBuffer(pcmFormat: audioFile.processingFormat,
                                            frameCapacity: AVAudioFrameCount(audioFile.length)) else {
        preconditionFailure()
    }

    let conversionRatio = sampleRate / Float(tempBuffer.format.sampleRate)
    let newLength = Float(audioFile.length) * conversionRatio
    guard let newBuffer = AVAudioPCMBuffer(pcmFormat: newFormat,
                                           frameCapacity: AVAudioFrameCount(newLength)) else {
        preconditionFailure()
    }

    do { try audioFile.read(into: tempBuffer) } catch {
        preconditionFailure()
    }
    guard let converter = AVAudioConverter(from: audioFile.processingFormat, to: newFormat) else {
        preconditionFailure()
    }
    var error: NSError?
    converter.convert(to: newBuffer, error: &error, withInputFrom: { (packetCount, statusPtr) -> AVAudioBuffer? in
        statusPtr.pointee = .haveData
        return tempBuffer
    })
    if error != nil {
        print("*** Conversion error: \(error!)")
    }
    return newBuffer
}


问:
Service Value Isn't Persistent Between Parent Component and Children Component
I am trying to set a value in a service from one component and read it another.

The hierarchy of my components is as: parent => child => grandchild

If I set the service value in the first child component the parent gets the correct value from the service whereas if I set the value in the child more inner child the parent component doesn't get the correct value.

Below is code:

service.ts

```<code> @Injectable()
    export class ConfirmationDialogService {
        componentHasDirtyForm: boolean;// value to set
        constructor(private confirmationDialogReferenceService: ConfirmationDialogReferenceService,
                    private dialog: MatDialog) { }
</code>```

parentComponent.ts

```<code>constructor(private confirmService: ConfirmationDialogService) {
}

ngOnInit() {
}

isDirty(): boolean {
    console.log(this.confirmService.componentHasDirtyForm)
    return this.confirmService.componentHasDirtyForm;
}
</code>```

ChildComponent.ts

```<code>constructor(private confirmService: ConfirmationDialogService) { }

ngAfterViewChecked(){
    this.confirmService.componentHasDirtyForm = this.generalInfoForm.dirty;
}
</code>```

GrandchildComponent (rendered inside child component)

```<code>constructor(private confirmationService: ConfirmationDialogService) { }
    ngAfterViewChecked(){
        this.checkForDirtyForm();
    }

    checkForDirtyForm(){
        for(var i = 0; i < this.ContactFormArr.length; i++){
            if(this.ContactFormArr.at(i).dirty){
                this.confirmationService.componentHasDirtyForm = true;
                break;
            }
        }
    }
</code>```

Basically, in grandchild component I am trying to set componentHasDirtyForm prop of ConfirmationDialogService. It is read correctly in parent if I set it from child but not grandchild.

I have included the service as a provider in app.module.ts

答:
I managed to find the issue.
The Grandchildren/Children components were setting the service's value correctly. The issue was the Parent/Child component's ngAfterViewChecked() hook was running after the hooks in the Grandchildren/Children.

This was causing the service's value to basically always reflect the Parent components status (The component higher up in the chain). I got around the issue by setting the dirty check in the parent component to conditionally modify the service depending on its current value.

For example

```<code>isDirty(): boolean {
    if(!this.confirmService.componentHasDirtyForm)
        this.confirmService.componentHasDirtyForm = formStatus;
}
</code>```

Body:
I am trying to set a value in a service from one component and read it another.

The hierarchy of my components is as: parent => child => grandchild

If I set the service value in the first child component the parent gets the correct value from the service whereas if I set the value in the child more inner child the parent component doesn't get the correct value.

Below is code:

service.ts

 @Injectable()
    export class ConfirmationDialogService {
        componentHasDirtyForm: boolean;// value to set
        constructor(private confirmationDialogReferenceService: ConfirmationDialogReferenceService,
                    private dialog: MatDialog) { }

parentComponent.ts

constructor(private confirmService: ConfirmationDialogService) {
}

ngOnInit() {
}

isDirty(): boolean {
    console.log(this.confirmService.componentHasDirtyForm)
    return this.confirmService.componentHasDirtyForm;
}

ChildComponent.ts

constructor(private confirmService: ConfirmationDialogService) { }

ngAfterViewChecked(){
    this.confirmService.componentHasDirtyForm = this.generalInfoForm.dirty;
}

GrandchildComponent (rendered inside child component)

constructor(private confirmationService: ConfirmationDialogService) { }
    ngAfterViewChecked(){
        this.checkForDirtyForm();
    }

    checkForDirtyForm(){
        for(var i = 0; i < this.ContactFormArr.length; i++){
            if(this.ContactFormArr.at(i).dirty){
                this.confirmationService.componentHasDirtyForm = true;
                break;
            }
        }
    }

Basically, in grandchild component I am trying to set componentHasDirtyForm prop of ConfirmationDialogService. It is read correctly in parent if I set it from child but not grandchild.

I have included the service as a provider in app.module.ts

Body:
I managed to find the issue.
The Grandchildren/Children components were setting the service's value correctly. The issue was the Parent/Child component's ngAfterViewChecked() hook was running after the hooks in the Grandchildren/Children.

This was causing the service's value to basically always reflect the Parent components status (The component higher up in the chain). I got around the issue by setting the dirty check in the parent component to conditionally modify the service depending on its current value.

For example

isDirty(): boolean {
    if(!this.confirmService.componentHasDirtyForm)
        this.confirmService.componentHasDirtyForm = formStatus;
}


问:
SignalR won't work properly inside Windows Service in comparison with Client Version
Objective: I want to send notifications to my customers in certain operations, such as when they loged in. To say in more detail, i wanna show the notification to employer that says {{x}} employe just loged in and clearly all the Authorisation codes are ready and works.

Current State: I opened another asp.net mvc web project(let say signal project) in my solutions and inside signal project i wrote my signalr codes that send notification to users according  to their authorizations.(ClassName : Hub)

My client/signalr work flow

List item

user logs in, i check his/her authorizations.

To her/his authorizations i assign them in to groups

and send notifications to employers(which they have they own group)

At this state every thing is fine and works.
But i want to convert this signal project to a windows service.So i created one.

Problem: Windows Service is working but the notifications that should be send to certain groups won't go(in my case employers won t see any notifications).

Analyze:So i review my codes and debuged with log4net library and checked the windows event log

Tested/Debuged/Confirmed Steps

Groups Creating works

Loged in Customer assigning to groups works

Send notification to employers group WON'T work(code below)

Clients.Group("Employers", Context.ConnectionId).Send("Some Context");

So i created a method that sends notification to ALL loged in users and strangely it works
all my users including employers and employees are sees notifications.

In brief, using signalr inside asp.net mvc project, i can send notification to my users which in a specific group but while using windows service i can send notification to all my users but i can t send notification to my users which in a specific group.

I can share code if needed?
Any insights, thoughts, ideas are appreciated.

答:
Revising -

In the method are you setting the hub context?

```<code>IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<Hub>();

(do some stuff)

hubContext.Clients.Group("Employers").Send("Some Context");
</code>```

If you are can you show some code?

Body:
Revising -

In the method are you setting the hub context?

IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<Hub>();

(do some stuff)

hubContext.Clients.Group("Employers").Send("Some Context");

If you are can you show some code?


问:
Why do square brackets around HTML-bound event handlers work?
Consider the following code snippet.

function func1() {
  console.log('func1 fired');
}

function func2() {
  console.log('func2 fired');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="[[[func1(), func2()]]]">Click Me</button></code>```

Note that the onclick event attribute's value is surrounded by multiple pairs of square brackets (I used three arbitrarily, but the number of brackets doesn't appear to matter).  The code works in Firefox and Chrome, but why does it work?  Is this standard and documented somewhere, or is it just the browser trying to be helpful.

答:
It works because expressions can be used as statements in JavaScript. So it's creating nested arrays of the results of the function calls, but not doing anything with those arrays.

For the same reason you could write:

```<code>function func3() {
    [[[func1(), func2()]]];
}
func3();
</code>```

Body:
Consider the following code snippet.

function func1() {
  console.log('func1 fired');
}

function func2() {
  console.log('func2 fired');
}

<button onclick="[[[func1(), func2()]]]">Click Me</button>

Note that the onclick event attribute's value is surrounded by multiple pairs of square brackets (I used three arbitrarily, but the number of brackets doesn't appear to matter).  The code works in Firefox and Chrome, but why does it work?  Is this standard and documented somewhere, or is it just the browser trying to be helpful.

Body:
It works because expressions can be used as statements in JavaScript. So it's creating nested arrays of the results of the function calls, but not doing anything with those arrays.

For the same reason you could write:

function func3() {
    [[[func1(), func2()]]];
}
func3();


问:
Python Datastructure Suggestion
i am building a small search engine to search a collection of pdfs. From each pdf i extract a set of tokens and store it in database. I do not want to store duplicate tokens in database, instead i want to store count of each token in the database. Does python has any special datastructure that do not store duplicates but stores the counts of each token?</p>

答:
The collections package has defaultdict which can be used as a key-value storage with a counter:

```<code>>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
...     d[k] += 1
...
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]
</code>```

Just so notice: This is not a databse, it's a pure in memory storage. You would have to save this data somehow!

Title: Python Datastructure Suggestion

Body:
The collections package has defaultdict which can be used as a key-value storage with a counter:

>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
...     d[k] += 1
...
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]

Just so notice: This is not a databse, it's a pure in memory storage. You would have to save this data somehow!


问:
How to place two div side-by-side in a HTML page
I have created a simple HTML page, where I have a parent div with over-flow enabled in both axes. Now within that div, there are 2 divs which I want to place side by side.

#Result {
  margin: 0 auto;
  padding: 0;
  background-color: rgba(0, 0, 0, .02);
  padding-top: 25px;
  font-size: 16px;
  overflow: scroll;
  width: 99%;
  height: calc(100% - 90px - 70px);
  position: absolute;
}

#Left,
#Right {
  height: calc(99vh - 90px - 70px);
  width: 28vw;
  margin: 0 auto;
  padding: 0;
  display: inline-block;
  float: left;
  text-align: center;
  background-color: rgba(0, 0, 0, .04);
  border-right: 1px solid #a6a6a6;
  border-bottom: 1px solid #a6a6a6;
}

#Right {
  background-color: rgba(0, 0, 0, .5);
  border-right: 0px solid #737373;
  padding-left: 15px;
  margin-right: 15px;
  width: 2000px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='Result'>
  <div id='Left'>

  </div>
  <div id='Right'>

  </div>
</div></code>```

Codepen - https://codepen.io/Volabos/pen/qBdNyPa?editors=1100

However unfortunately, the 3rd div is moved down if its width is taken a large number. How can I place the 2nd and 3rd div side by side?

答:
You may safely use for the parent display:flex + overflow:auto and for the children flex-shrink:0 or min-width:xx

Possible example

#Result {
  display: flex;  /* flex model */
  overflow: auto;
  height: 100vh;  /* whatever or min-height or let grow from content  */
}

#Right,
#Left {
  flex-shrink: 0;  /* do not allow childd to shrink and allow overflow  */
}

#Left {
  width: 28vw;  /* whatever */
}

#Right {
  width: 100vw;  /* whatever */
}

/* demo purpose */

div div {
  border: solid;
}

#Left {
  background: lightblue;
}

#Right {
  background: lightgreen;
}

* {
  margin: 0;
  box-sizing: border-box;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='Result'>
  <div id='Left'>

  </div>
  <div id='Right'>

  </div>
</div></code>```

Body:
I have created a simple HTML page, where I have a parent div with over-flow enabled in both axes. Now within that div, there are 2 divs which I want to place side by side.

#Result {
  margin: 0 auto;
  padding: 0;
  background-color: rgba(0, 0, 0, .02);
  padding-top: 25px;
  font-size: 16px;
  overflow: scroll;
  width: 99%;
  height: calc(100% - 90px - 70px);
  position: absolute;
}

#Left,
#Right {
  height: calc(99vh - 90px - 70px);
  width: 28vw;
  margin: 0 auto;
  padding: 0;
  display: inline-block;
  float: left;
  text-align: center;
  background-color: rgba(0, 0, 0, .04);
  border-right: 1px solid #a6a6a6;
  border-bottom: 1px solid #a6a6a6;
}

#Right {
  background-color: rgba(0, 0, 0, .5);
  border-right: 0px solid #737373;
  padding-left: 15px;
  margin-right: 15px;
  width: 2000px;
}

Codepen - https://codepen.io/Volabos/pen/qBdNyPa?editors=1100

However unfortunately, the 3rd div is moved down if its width is taken a large number. How can I place the 2nd and 3rd div side by side?

Body:
You may safely use for the parent display:flex + overflow:auto and for the children flex-shrink:0 or min-width:xx

Possible example

#Result {
  display: flex;  /* flex model */
  overflow: auto;
  height: 100vh;  /* whatever or min-height or let grow from content  */
}

#Right,
#Left {
  flex-shrink: 0;  /* do not allow childd to shrink and allow overflow  */
}

#Left {
  width: 28vw;  /* whatever */
}

#Right {
  width: 100vw;  /* whatever */
}

/* demo purpose */

div div {
  border: solid;
}

#Left {
  background: lightblue;
}

#Right {
  background: lightgreen;
}

* {
  margin: 0;
  box-sizing: border-box;
}

<div id='Result'>
  <div id='Left'>

  </div>
  <div id='Right'>

  </div>
</div>


问:
ReactJS: useEffect is not run when the url changes
I have a ReactJS website, and I'm still a noob using it.

I've 2 Components

The first one is the / page, that must be rendered after a request to a web server, when the user get to that route, I've used useEffect for this.

The second one is the /mostraMaterie/:id that must be rendered after another request to the web server.

The first component work like a charm, whereas the second one doesn't trigger the useEffect function.

When the user clicks a button on the / component, it is redirected to /mostraMateria/:id with the according id.

The problem is the /mostraMateria component I have another useEffect function, but it is not triggered.

As suggested in the comment, this is the mostraMateria file in JSFiddle
mostraMaterie.js

App.js
handles the user connection

```<code>import React from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import MostraMaterie from "./Contenuti/MostraMaterie";
import "./App.css";

import Main from "./Contenuti/Main";

function App() {
  return (
    <Router>
      <Switch>
        <Route path="/mostraMateria/:id" component={MostraMaterie} />{" "}
        <Route exact path="/" component={Main} />{" "}
      </Switch>{" "}
    </Router>
  );
}

export default App;
</code>```

Main.js
handles the page rendering if the location is / and work perfectly.

```<code>import React, { useEffect, useState } from "react";
import {  Link } from "react-router-dom";
import Indirizzi from "./Indirizzi";
import Bottone from "../Util/Bottone";
import "../App.css";
import FullNavBar from "../NavBar/FullNavBar";

function Main() {
  const [indirizzi, cambiaIndirizzi] = useState([]);

  const fetchIndirizzi = () => {
    async function prendiIndirizzi() {
      let indirizzi = await fetch(
        "https://vps.lellovitiello.tk/Riassunty/API/indirizzi.php"
      );
      let ind = await indirizzi.json();

      for (let i = 0; i < ind.length; i++) {
        async function prendiMaterie() {
          let materie = await fetch(
            `https://vps.lellovitiello.tk/Riassunty/API/materie.php?indirizzo=${ind[i].Indirizzo}`
          );
          materie = await materie.json();

          for (let materia of materie) {
            Object.defineProperty(
              materia,
              "nome",
              Object.getOwnPropertyDescriptor(materia, "Materia")
            );
            delete materia["Materia"];

            Object.defineProperty(
              materia,
              "id",
              Object.getOwnPropertyDescriptor(materia, "IDMateria")
            );
            delete materia["IDMateria"];
            delete materia["Indirizzo"];
          }

          Object.defineProperty(
            ind[i],
            "nome",
            Object.getOwnPropertyDescriptor(ind[i], "Indirizzo")
          );
          delete ind[i]["Indirizzo"];
          Object.assign(ind[i], { dati: materie });
          Object.assign(ind[i], { id: i });
        }

        await prendiMaterie();
      }
      console.log("Main.js", ind);
      cambiaIndirizzi(ind);
    }
    prendiIndirizzi();
  };
  useEffect(fetchIndirizzi, []);

  return (
    <React.Fragment>
      <FullNavBar elementi={indirizzi} />{" "}
      <Link to="/Login">
        <Bottone TestoBottone="Per caricare un riassunto" />
      </Link>{" "}
      {indirizzi.map(indirizzo => {
        console.log(indirizzo);
        return <Indirizzi dati={indirizzo} />;
      })}
    </React.Fragment>
  );
}

export default Main;
</code>```

MostraMaterie.js
handles the page rendering if the location is /mostraMaterie/:id and doesn't work.

```<code>import React, { useEffect, useState } from "react";
import "../App.css";
import history from "../Util/history";
import { Link } from "react-router-dom";
import FullNavBar from "../NavBar/FullNavBar";
import Indirizzi from "./Indirizzi";
import Bottone from "../Util/Bottone";

function MostraMaterie(props) {
  const [anni, cambiaAnni] = useState([]);

  // *** this function is never called ***
  const fetchAnni = () => {
    async function prendiAnni() {
      let anniJson = await fetch(
        "https://vps.lellovitiello.tk/Riassunty/API/ottieniAnni.php"
      );
      let idMateria = props.match.params.id;
      let ann = [];
      anniJson = await anniJson.json();

      for (let anno of anniJson) {
        async function prendiAnteprime() {
          let anteprimeFetch = await fetch(
            `https://vps.lellovitiello.tk/Riassunty/API/anteprima.php?idMateria=${idMateria}&anno=${anno}`
          );

          anteprimeFetch = await anteprimeFetch.json();
          for (let anteprima of anteprimeFetch) {
            Object.defineProperty(
              anteprima,
              "nome",
              Object.getOwnPropertyDescriptor(anteprima, "Titolo")
            );

            Object.defineProperty(
              anteprima,
              "id",
              Object.getOwnPropertyDescriptor(anteprima, "ID")
            );
            delete anteprima["Titolo"];
            delete anteprima["ID"];
          }

          let annoOggetto = {
            nome: anno + "",
            anteprime: anteprimeFetch
          };
          ann.push(annoOggetto);
        }

        await prendiAnteprime();
      }
      debugger;
      cambiaAnni(ann);
    }
    console.log("Vengo eseguito");
    prendiAnni();
  };

  useEffect(fetchAnni, []);
  console.log(history.location);

  return (
    <React.Fragment>
      <FullNavBar indirizzi={anni} />{" "}
      <Link to="/Login">
        <Bottone TestoBottone="Per caricare un riassunto" />
      </Link>{" "}
      <h1> CIao CIAO CIAO CIAOC </h1>{" "}
      {
        //*** this depends on the response of the web server ***
         anni.map(anno => {
              console.log("Ciao");
              return <Indirizzi dati={anno} />;
            })}{" "}
    </React.Fragment>
  );
}

export default MostraMaterie;
</code>```

How can I make this work?

Edit

I've remove the <FullNavBar indirizzi={anni} />{" "} and it works, now my request is made to the server and the ``fetchAnni``` function in fired.

The problem is, I need the piece of code I removed, it seems that the
<FullNavBar indirizzi={anni} />{" "} is rendered before the call of fetchAnni, even adding the await prendiAnni and async fetchAnni  as suggested by Artur doesn't work.

I've also changed from useEffect(fetchAnni, []); to useEffect(fetchAnni, [props.location.pathname]); that is a string

答:
It looks as though you are passing an empty array as your second argument to useEffect(), useEffect(fetchAnni, []);

From https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects

If you want to run an effect and clean it up only once (on mount and
  unmount), you can pass an empty array ([]) as a second argument. This
  tells React that your effect doesn’t depend on any values from props
  or state, so it never needs to re-run.

If you want to run the effect on every render, you can leave off the second argument. If you want it to only run when certain props/state values change, you can pass those as array values in the second argument.

Body:
I have a ReactJS website, and I'm still a noob using it.

I've 2 Components

The first one is the / page, that must be rendered after a request to a web server, when the user get to that route, I've used useEffect for this.

The second one is the /mostraMaterie/:id that must be rendered after another request to the web server.

The first component work like a charm, whereas the second one doesn't trigger the useEffect function.

When the user clicks a button on the / component, it is redirected to /mostraMateria/:id with the according id.

The problem is the /mostraMateria component I have another useEffect function, but it is not triggered.

As suggested in the comment, this is the mostraMateria file in JSFiddle
mostraMaterie.js

App.js
handles the user connection

import React from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import MostraMaterie from "./Contenuti/MostraMaterie";
import "./App.css";

import Main from "./Contenuti/Main";

function App() {
  return (
    <Router>
      <Switch>
        <Route path="/mostraMateria/:id" component={MostraMaterie} />{" "}
        <Route exact path="/" component={Main} />{" "}
      </Switch>{" "}
    </Router>
  );
}

export default App;

Main.js
handles the page rendering if the location is / and work perfectly.

import React, { useEffect, useState } from "react";
import {  Link } from "react-router-dom";
import Indirizzi from "./Indirizzi";
import Bottone from "../Util/Bottone";
import "../App.css";
import FullNavBar from "../NavBar/FullNavBar";

function Main() {
  const [indirizzi, cambiaIndirizzi] = useState([]);

  const fetchIndirizzi = () => {
    async function prendiIndirizzi() {
      let indirizzi = await fetch(
        "https://vps.lellovitiello.tk/Riassunty/API/indirizzi.php"
      );
      let ind = await indirizzi.json();

      for (let i = 0; i < ind.length; i++) {
        async function prendiMaterie() {
          let materie = await fetch(
            `https://vps.lellovitiello.tk/Riassunty/API/materie.php?indirizzo=${ind[i].Indirizzo}`
          );
          materie = await materie.json();

          for (let materia of materie) {
            Object.defineProperty(
              materia,
              "nome",
              Object.getOwnPropertyDescriptor(materia, "Materia")
            );
            delete materia["Materia"];

            Object.defineProperty(
              materia,
              "id",
              Object.getOwnPropertyDescriptor(materia, "IDMateria")
            );
            delete materia["IDMateria"];
            delete materia["Indirizzo"];
          }

          Object.defineProperty(
            ind[i],
            "nome",
            Object.getOwnPropertyDescriptor(ind[i], "Indirizzo")
          );
          delete ind[i]["Indirizzo"];
          Object.assign(ind[i], { dati: materie });
          Object.assign(ind[i], { id: i });
        }

        await prendiMaterie();
      }
      console.log("Main.js", ind);
      cambiaIndirizzi(ind);
    }
    prendiIndirizzi();
  };
  useEffect(fetchIndirizzi, []);

  return (
    <React.Fragment>
      <FullNavBar elementi={indirizzi} />{" "}
      <Link to="/Login">
        <Bottone TestoBottone="Per caricare un riassunto" />
      </Link>{" "}
      {indirizzi.map(indirizzo => {
        console.log(indirizzo);
        return <Indirizzi dati={indirizzo} />;
      })}
    </React.Fragment>
  );
}

export default Main;

MostraMaterie.js
handles the page rendering if the location is /mostraMaterie/:id and doesn't work.

import React, { useEffect, useState } from "react";
import "../App.css";
import history from "../Util/history";
import { Link } from "react-router-dom";
import FullNavBar from "../NavBar/FullNavBar";
import Indirizzi from "./Indirizzi";
import Bottone from "../Util/Bottone";

function MostraMaterie(props) {
  const [anni, cambiaAnni] = useState([]);

  // *** this function is never called ***
  const fetchAnni = () => {
    async function prendiAnni() {
      let anniJson = await fetch(
        "https://vps.lellovitiello.tk/Riassunty/API/ottieniAnni.php"
      );
      let idMateria = props.match.params.id;
      let ann = [];
      anniJson = await anniJson.json();

      for (let anno of anniJson) {
        async function prendiAnteprime() {
          let anteprimeFetch = await fetch(
            `https://vps.lellovitiello.tk/Riassunty/API/anteprima.php?idMateria=${idMateria}&anno=${anno}`
          );

          anteprimeFetch = await anteprimeFetch.json();
          for (let anteprima of anteprimeFetch) {
            Object.defineProperty(
              anteprima,
              "nome",
              Object.getOwnPropertyDescriptor(anteprima, "Titolo")
            );

            Object.defineProperty(
              anteprima,
              "id",
              Object.getOwnPropertyDescriptor(anteprima, "ID")
            );
            delete anteprima["Titolo"];
            delete anteprima["ID"];
          }

          let annoOggetto = {
            nome: anno + "",
            anteprime: anteprimeFetch
          };
          ann.push(annoOggetto);
        }

        await prendiAnteprime();
      }
      debugger;
      cambiaAnni(ann);
    }
    console.log("Vengo eseguito");
    prendiAnni();
  };

  useEffect(fetchAnni, []);
  console.log(history.location);

  return (
    <React.Fragment>
      <FullNavBar indirizzi={anni} />{" "}
      <Link to="/Login">
        <Bottone TestoBottone="Per caricare un riassunto" />
      </Link>{" "}

 CIao CIAO CIAO CIAOC
{" "}
      {
        //*** this depends on the response of the web server ***
         anni.map(anno => {
              console.log("Ciao");
              return <Indirizzi dati={anno} />;
            })}{" "}
    </React.Fragment>
  );
}

export default MostraMaterie;

How can I make this work?

Edit

I've remove the <FullNavBar indirizzi={anni} />{" "} and it works, now my request is made to the server and the ``fetchAnni``` function in fired.

The problem is, I need the piece of code I removed, it seems that the
<FullNavBar indirizzi={anni} />{" "} is rendered before the call of fetchAnni, even adding the await prendiAnni and async fetchAnni  as suggested by Artur doesn't work.

I've also changed from useEffect(fetchAnni, []); to useEffect(fetchAnni, [props.location.pathname]); that is a string


答:
The browser will construct a function from the attribute value, using the text of the attribute as the code of the function. In your case, that'll be a function that looks like

```<code>function madeByBrowser(event) {
  [[[ func1(), func2() ]]];
}
</code>```

That is legal JavaScript. The function contains a single expression, an array initializer. A side effect of evaluating that array initializer is to call the two functions.

(The actual constructed function won't be exactly like that, and there are some odd and often problematic details about the implicit scope of the code in the function. It's close enough for the purposes of this question.)

Title: Why do square brackets around HTML-bound event handlers work?

Body:
The browser will construct a function from the attribute value, using the text of the attribute as the code of the function. In your case, that'll be a function that looks like

function madeByBrowser(event) {
  [[[ func1(), func2() ]]];
}

That is legal JavaScript. The function contains a single expression, an array initializer. A side effect of evaluating that array initializer is to call the two functions.

(The actual constructed function won't be exactly like that, and there are some odd and often problematic details about the implicit scope of the code in the function. It's close enough for the purposes of this question.)


问:
Maximum height of the staircase
Given an integer A representing the square blocks. The height of each square block is 1. The task is to create a staircase of max height using these blocks. The first stair would require only one block, the second stair would require two blocks and so on. Find and return the maximum height of the staircase.

Your submission failed for the following input: A : 92761

Your function returned the following : 65536

The expected returned value : 430

```<code>Approach:
We are interested in the number of steps and we know that each step Si uses exactly Bi number of bricks. We can represent this problem as an equation:
n * (n + 1) / 2 = T (For Natural number series starting from 1, 2, 3, 4, 5 …)
n * (n + 1) = 2 * T
n-1 will represent our final solution because our series in problem starts from 2, 3, 4, 5…

Now, we just have to solve this equation and for that we can exploit binary search to find the solution to this equation. Lower and Higher bounds of binary search are 1 and T.
</code>```

CODE

```<code>public int solve(int A) {
        int l=1,h=A,T=2*A;
        while(l<=h)
        {
            int mid=l+(h-l)/2;
            if((mid*(mid+1))==T)
                return mid;
            if((mid*(mid+1))>T && (mid!=0 && (mid*(mid-1))<=T) )
                return mid-1;
            if((mid*(mid+1))>T)
                h=mid-1;
            else
                l=mid+1;
        }
        return 0;
    }
</code>```

答:
To expand on the comment by Matt Timmermans:

You know that for n steps, you need (n * (n + 1))/2 blocks. You want know, if given B blocks, how many steps you can create.

So you have:

```<code>(n * (n + 1))/2 = B
(n^2 + n)/2 = B
n^2 + n = 2B
n^2 + n - 2B = 0
</code>```

That looks suspiciously like something for which you'd use the quadratic formula.

In this case, a=1, b=1, and c=(-2B). Plugging the numbers into the formula:

```<code>n = ((-b) + sqrt(b^2 - 4*a*c))/(2*a)
  = (-1 + sqrt(1 - 4*1*(-2B)))/(2*a)
  = (-1 + sqrt(1 + 8B))/2
  = (sqrt(1 + 8B) - 1)/2
</code>```

So if you have 5050 blocks, you get:

```<code>n = (sqrt(1 + 40400) - 1)/2
  = (sqrt(40401) - 1)/2
  = (201 - 1)/2
  = 100
</code>```

Try it with the quadratic formula calculator. Use 1 for the value of a and b, and replace c with negative two times the number of blocks you're given. So in the example above, c would be -10100.

In your program, since you can't have a partial step, you'd want to truncate the result.

Title: Maximum height of the staircase

Body:
Given an integer A representing the square blocks. The height of each square block is 1. The task is to create a staircase of max height using these blocks. The first stair would require only one block, the second stair would require two blocks and so on. Find and return the maximum height of the staircase.

Your submission failed for the following input: A : 92761

Your function returned the following : 65536

The expected returned value : 430

Approach:
We are interested in the number of steps and we know that each step Si uses exactly Bi number of bricks. We can represent this problem as an equation:
n * (n + 1) / 2 = T (For Natural number series starting from 1, 2, 3, 4, 5 …)
n * (n + 1) = 2 * T
n-1 will represent our final solution because our series in problem starts from 2, 3, 4, 5…

Now, we just have to solve this equation and for that we can exploit binary search to find the solution to this equation. Lower and Higher bounds of binary search are 1 and T.

CODE

public int solve(int A) {
        int l=1,h=A,T=2*A;
        while(l<=h)
        {
            int mid=l+(h-l)/2;
            if((mid*(mid+1))==T)
                return mid;
            if((mid*(mid+1))>T && (mid!=0 && (mid*(mid-1))<=T) )
                return mid-1;
            if((mid*(mid+1))>T)
                h=mid-1;
            else
                l=mid+1;
        }
        return 0;
    }

Body:
To expand on the comment by Matt Timmermans:

You know that for n steps, you need (n * (n + 1))/2 blocks. You want know, if given B blocks, how many steps you can create.

So you have:

(n * (n + 1))/2 = B
(n^2 + n)/2 = B
n^2 + n = 2B
n^2 + n - 2B = 0

That looks suspiciously like something for which you'd use the quadratic formula.

In this case, a=1, b=1, and c=(-2B). Plugging the numbers into the formula:

n = ((-b) + sqrt(b^2 - 4*a*c))/(2*a)
  = (-1 + sqrt(1 - 4*1*(-2B)))/(2*a)
  = (-1 + sqrt(1 + 8B))/2
  = (sqrt(1 + 8B) - 1)/2

So if you have 5050 blocks, you get:

n = (sqrt(1 + 40400) - 1)/2
  = (sqrt(40401) - 1)/2
  = (201 - 1)/2
  = 100

Try it with the quadratic formula calculator. Use 1 for the value of a and b, and replace c with negative two times the number of blocks you're given. So in the example above, c would be -10100.

In your program, since you can't have a partial step, you'd want to truncate the result.


问:
Remove undesired connected pixels from an image with Python
I'm a beginner in image processing with Python so I need help.
I'm trying to remove areas of connected pixels from my pictures with the code posted below. Actually, it works but not well.
What I desire is the removing of areas of pixels, such as those marked in red in the pictures reported below, from my images, so as to obtain a cleaned picture.
Would be also great to set a minimum and a maximum limit for the dimensions of the detected areas of connected pixels.
Example of a picture with marked areas 1
Example of a picture with marked areas 2

This is my currently code:

```<code>### LOAD MODULES ###
import numpy as np
import imutils
import cv2

def is_contour_bad(c): # Decide what I want to find and its features
    peri=cv2.contourArea(c, True) # Find areas
    approx=cv2.approxPolyDP(c, 0.3*peri, True) # Set areas approximation
    return not len(approx)>2 # Threshold to decide if add an area to the mask for its removing (if>2 remove)

### DATA PROCESSING ###
image=cv2.imread("025.jpg") # Load a picture
gray=cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Convert to grayscale
cv2.imshow("Original image", image) # Plot

edged=cv2.Canny(gray, 50, 200, 3) # Edges of areas detection
cnts=cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) # Find contours: a curve joining all the continuous points (along the boundary), having same color or intensity
cnts=imutils.grab_contours(cnts)

mask=np.ones(image.shape[:2], dtype="uint8")*255 # Setup the mask with white background
# Loop over the detected contours
for c in cnts:
    # If the contour satisfies "is_contour_bad", draw it on the mask
    if is_contour_bad(c):
        cv2.drawContours(mask, [c], -1, 0, -1) # (source image, list of contours, with -1 all contours in [c] pass, 0 is the intensity, -1 the thickness)

image_cleaned=cv2.bitwise_and(image, image, mask=mask) # Remove the contours from the original image
cv2.imshow("Adopted mask", mask) # Plot
cv2.imshow("Cleaned image", image_cleaned) # Plot
cv2.imwrite("cleaned_025.jpg", image_cleaned) # Write in a file
</code>```

答:
You may execute the following processing steps:

Threshold the image to binary image using cv2.threshold.

It's not a must, but in your case it looks like shades of gray are not important.

Use closing morphological operation, for closing small gaps in the binary image.

Use cv2.findContours with cv2.RETR_EXTERNAL parameter, for getting the contours (perimeter) surrounding the white clusters.

Modify the logic of "bad contour", to return true, only if area is large (assuming you only want to clean the large three contour).

Here is the updated code:

```<code>### LOAD MODULES ###
import numpy as np
import imutils
import cv2

def is_contour_bad(c): # Decide what I want to find and its features
    peri = cv2.contourArea(c) # Find areas
    return peri > 50 # Large area is considered "bad"

### DATA PROCESSING ###
image = cv2.imread("025.jpg") # Load a picture
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Convert to grayscale

# Convert to binary image (all values above 20 are converted to 1 and below to 0)
ret, thresh_gray = cv2.threshold(gray, 20, 255, cv2.THRESH_BINARY)

# Use "close" morphological operation to close the gaps between contours
# https://stackoverflow.com/questions/18339988/implementing-imcloseim-se-in-opencv
thresh_gray = cv2.morphologyEx(thresh_gray, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5)));

#Find contours on thresh_gray, use cv2.RETR_EXTERNAL to get external perimeter
_, cnts, _ = cv2.findContours(thresh_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # Find contours: a curve joining all the continuous points (along the boundary), having same color or intensity

image_cleaned = gray

# Loop over the detected contours
for c in cnts:
    # If the contour satisfies "is_contour_bad", draw it on the mask
    if is_contour_bad(c):
        # Draw black contour on gray image, instead of using a mask
        cv2.drawContours(image_cleaned, [c], -1, 0, -1)

#cv2.imshow("Adopted mask", mask) # Plot
cv2.imshow("Cleaned image", image_cleaned) # Plot
cv2.imwrite("cleaned_025.jpg", image_cleaned) # Write in a file

cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

Result:

Marking contours found for testing:

```<code>for c in cnts:
    if is_contour_bad(c):
        # Draw green line for marking the contour
        cv2.drawContours(image, [c], 0, (0, 255, 0), 1)
</code>```

Result:

There is still work to be done...

Update

Two iterations approach:

First iteration - remove the large contour.

Second iteration - remove small but bright contours.

Here is the code:

```<code>import numpy as np
import imutils
import cv2

def is_contour_bad(c, thrs): # Decide what I want to find and its features
    peri = cv2.contourArea(c) # Find areas
    return peri > thrs # Large area is considered "bad"

image = cv2.imread("025.jpg") # Load a picture
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Convert to grayscale

# First iteration - remove the large contour
###########################################################################
# Convert to binary image (all values above 20 are converted to 1 and below to 0)
ret, thresh_gray = cv2.threshold(gray, 20, 255, cv2.THRESH_BINARY)

# Use "close" morphological operation to close the gaps between contours
# https://stackoverflow.com/questions/18339988/implementing-imcloseim-se-in-opencv
thresh_gray = cv2.morphologyEx(thresh_gray, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5)));

#Find contours on thresh_gray, use cv2.RETR_EXTERNAL to get external perimeter
_, cnts, _ = cv2.findContours(thresh_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # Find contours: a curve joining all the continuous points (along the boundary), having same color or intensity

image_cleaned = gray

# Loop over the detected contours
for c in cnts:
    # If the contour satisfies "is_contour_bad", draw it on the mask
    if is_contour_bad(c, 1000):
        # Draw black contour on gray image, instead of using a mask
        cv2.drawContours(image_cleaned, [c], -1, 0, -1)
###########################################################################

# Second iteration - remove small but bright contours
###########################################################################
# In the second iteration, use high threshold
ret, thresh_gray = cv2.threshold(image_cleaned, 150, 255, cv2.THRESH_BINARY)

# Use "dilate" with small radius
thresh_gray = cv2.morphologyEx(thresh_gray, cv2.MORPH_DILATE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2,2)));

#Find contours on thresh_gray, use cv2.RETR_EXTERNAL to get external perimeter
_, cnts, _ = cv2.findContours(thresh_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # Find contours: a curve joining all the continuous points (along the boundary), having same color or intensity

# Loop over the detected contours
for c in cnts:
    # If the contour satisfies "is_contour_bad", draw it on the mask
    # Remove contour if  area is above 20 pixels
    if is_contour_bad(c, 20):
        # Draw black contour on gray image, instead of using a mask
        cv2.drawContours(image_cleaned, [c], -1, 0, -1)
###########################################################################
</code>```

Marked contours:

Body:
I'm a beginner in image processing with Python so I need help.
I'm trying to remove areas of connected pixels from my pictures with the code posted below. Actually, it works but not well.
What I desire is the removing of areas of pixels, such as those marked in red in the pictures reported below, from my images, so as to obtain a cleaned picture.
Would be also great to set a minimum and a maximum limit for the dimensions of the detected areas of connected pixels.
Example of a picture with marked areas 1
Example of a picture with marked areas 2

This is my currently code:

### LOAD MODULES ###
import numpy as np
import imutils
import cv2

def is_contour_bad(c): # Decide what I want to find and its features
    peri=cv2.contourArea(c, True) # Find areas
    approx=cv2.approxPolyDP(c, 0.3*peri, True) # Set areas approximation
    return not len(approx)>2 # Threshold to decide if add an area to the mask for its removing (if>2 remove)

### DATA PROCESSING ###
image=cv2.imread("025.jpg") # Load a picture
gray=cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Convert to grayscale
cv2.imshow("Original image", image) # Plot

edged=cv2.Canny(gray, 50, 200, 3) # Edges of areas detection
cnts=cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) # Find contours: a curve joining all the continuous points (along the boundary), having same color or intensity
cnts=imutils.grab_contours(cnts)

mask=np.ones(image.shape[:2], dtype="uint8")*255 # Setup the mask with white background
# Loop over the detected contours
for c in cnts:
    # If the contour satisfies "is_contour_bad", draw it on the mask
    if is_contour_bad(c):
        cv2.drawContours(mask, [c], -1, 0, -1) # (source image, list of contours, with -1 all contours in [c] pass, 0 is the intensity, -1 the thickness)

image_cleaned=cv2.bitwise_and(image, image, mask=mask) # Remove the contours from the original image
cv2.imshow("Adopted mask", mask) # Plot
cv2.imshow("Cleaned image", image_cleaned) # Plot
cv2.imwrite("cleaned_025.jpg", image_cleaned) # Write in a file

Body:
You may execute the following processing steps:

Threshold the image to binary image using cv2.threshold.

It's not a must, but in your case it looks like shades of gray are not important.

Use closing morphological operation, for closing small gaps in the binary image.

Use cv2.findContours with cv2.RETR_EXTERNAL parameter, for getting the contours (perimeter) surrounding the white clusters.

Modify the logic of "bad contour", to return true, only if area is large (assuming you only want to clean the large three contour).

Here is the updated code:

### LOAD MODULES ###
import numpy as np
import imutils
import cv2

def is_contour_bad(c): # Decide what I want to find and its features
    peri = cv2.contourArea(c) # Find areas
    return peri > 50 # Large area is considered "bad"

### DATA PROCESSING ###
image = cv2.imread("025.jpg") # Load a picture
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Convert to grayscale

# Convert to binary image (all values above 20 are converted to 1 and below to 0)
ret, thresh_gray = cv2.threshold(gray, 20, 255, cv2.THRESH_BINARY)

# Use "close" morphological operation to close the gaps between contours
# https://stackoverflow.com/questions/18339988/implementing-imcloseim-se-in-opencv
thresh_gray = cv2.morphologyEx(thresh_gray, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5)));

#Find contours on thresh_gray, use cv2.RETR_EXTERNAL to get external perimeter
_, cnts, _ = cv2.findContours(thresh_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # Find contours: a curve joining all the continuous points (along the boundary), having same color or intensity

image_cleaned = gray

# Loop over the detected contours
for c in cnts:
    # If the contour satisfies "is_contour_bad", draw it on the mask
    if is_contour_bad(c):
        # Draw black contour on gray image, instead of using a mask
        cv2.drawContours(image_cleaned, [c], -1, 0, -1)

#cv2.imshow("Adopted mask", mask) # Plot
cv2.imshow("Cleaned image", image_cleaned) # Plot
cv2.imwrite("cleaned_025.jpg", image_cleaned) # Write in a file

cv2.waitKey(0)
cv2.destroyAllWindows()

Result:

Marking contours found for testing:

for c in cnts:
    if is_contour_bad(c):
        # Draw green line for marking the contour
        cv2.drawContours(image, [c], 0, (0, 255, 0), 1)

Result:

There is still work to be done...

Update

Two iterations approach:

First iteration - remove the large contour.

Second iteration - remove small but bright contours.

Here is the code:

import numpy as np
import imutils
import cv2

def is_contour_bad(c, thrs): # Decide what I want to find and its features
    peri = cv2.contourArea(c) # Find areas
    return peri > thrs # Large area is considered "bad"

image = cv2.imread("025.jpg") # Load a picture
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Convert to grayscale

# First iteration - remove the large contour
###########################################################################
# Convert to binary image (all values above 20 are converted to 1 and below to 0)
ret, thresh_gray = cv2.threshold(gray, 20, 255, cv2.THRESH_BINARY)

# Use "close" morphological operation to close the gaps between contours
# https://stackoverflow.com/questions/18339988/implementing-imcloseim-se-in-opencv
thresh_gray = cv2.morphologyEx(thresh_gray, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5)));

#Find contours on thresh_gray, use cv2.RETR_EXTERNAL to get external perimeter
_, cnts, _ = cv2.findContours(thresh_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # Find contours: a curve joining all the continuous points (along the boundary), having same color or intensity

image_cleaned = gray

# Loop over the detected contours
for c in cnts:
    # If the contour satisfies "is_contour_bad", draw it on the mask
    if is_contour_bad(c, 1000):
        # Draw black contour on gray image, instead of using a mask
        cv2.drawContours(image_cleaned, [c], -1, 0, -1)
###########################################################################

# Second iteration - remove small but bright contours
###########################################################################
# In the second iteration, use high threshold
ret, thresh_gray = cv2.threshold(image_cleaned, 150, 255, cv2.THRESH_BINARY)

# Use "dilate" with small radius
thresh_gray = cv2.morphologyEx(thresh_gray, cv2.MORPH_DILATE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2,2)));

#Find contours on thresh_gray, use cv2.RETR_EXTERNAL to get external perimeter
_, cnts, _ = cv2.findContours(thresh_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # Find contours: a curve joining all the continuous points (along the boundary), having same color or intensity

# Loop over the detected contours
for c in cnts:
    # If the contour satisfies "is_contour_bad", draw it on the mask
    # Remove contour if  area is above 20 pixels
    if is_contour_bad(c, 20):
        # Draw black contour on gray image, instead of using a mask
        cv2.drawContours(image_cleaned, [c], -1, 0, -1)
###########################################################################

Marked contours:


问:
How can I cast a tensor to the complex type in Pytorch?
I want to do some quantum mechanics calculations with Pytorch, where the quantities are sometimes complex. I would like to know how can I cast an existing real tensor to the complex type.</p>

答:
PyTorch does have complex number support.

Try this:

import torch

a = torch.tensor([1.0, 2.0], dtype=torch.double)
b = a.type(torch.complex64)
```


问:
Very simple code - Unity 3d - IndexOutOfRangeException: Index was outside the bounds of the array
```<code>public class Button : MonoBehaviour {
    public Material[] mButton;
    Renderer rend;

    // Start is called before the first frame update
    void Start()
    {
        Debug.Log(mButton[0]);
        rend = GetComponent<Renderer>();
        rend.sharedMaterial = mButton[0];
    }
</code>```

I am getting a "Index Out of Bounds" error at the rend.sharedMaterial=mButton[0] line. It is an array of two elements. I have different materials in each of the two locations of the array. The Debug.Log accurately shows which material is in the [0] location.

Any ideas? Thanks in advance.

答:
The comment posted by @PhilippLenssen solved the issue.

His comment:
"Can you please double-check that the error happens at the rend.sharedMaterial line, and not the Debug.Log line? (E.g. it sometimes happens that one assigns the same script to two different gameObjects accidentally -- one would now have an empty material list, thus throw an error at the Debug.Log line.) "

Once I commented out the Debug.Log(mButton[0]); line, the error cleared.

Body:
public class Button : MonoBehaviour {
    public Material[] mButton;
    Renderer rend;

    // Start is called before the first frame update
    void Start()
    {
        Debug.Log(mButton[0]);
        rend = GetComponent<Renderer>();
        rend.sharedMaterial = mButton[0];
    }

I am getting a "Index Out of Bounds" error at the rend.sharedMaterial=mButton[0] line. It is an array of two elements. I have different materials in each of the two locations of the array. The Debug.Log accurately shows which material is in the [0] location.

Any ideas? Thanks in advance.


问:
How to do "call by reference" in Java?

How to do "call by reference" in Java?  (Assume that we are using that term in the same way that it has been used in peer-reviewed CS literature since the 1960's; see this Wikipedia page for a simple explanation.)

Since Java doesn't support pointers, how is it possible to call a function by reference in Java like we do in C and C++??

答:
The best way is to use an interface which performs the action.

```<code>// Pass a Runnable which calls the task() method
executor.submit(new Runnable() {
    public void run() {
        task();
    }
});

public void task() { }
</code>```

You can use reflections to call any method

```<code>Method method = MyClass.class.getMethod("methodToCall", ParameterType.class);
result = method.invoke(object, args);
</code>```

Title: How to do "call by reference" in Java?

Body:
The best way is to use an interface which performs the action.

// Pass a Runnable which calls the task() method
executor.submit(new Runnable() {
    public void run() {
        task();
    }
});

public void task() { }

You can use reflections to call any method

Method method = MyClass.class.getMethod("methodToCall", ParameterType.class);
result = method.invoke(object, args);


问:
Finding if the x and y coordinate is within a view is enclosed by two intersecting rectangles, in java
Say I have this view with two subviews A and B, A and B has a color property mColor,

I want a function in the parent view that has this signature: int getColor(int x, int y), which for any given x and y coordinate, return the color at that position, if the x and y coordinates land and the two shapes are overlapped, return the average color of A and B

The problem I am running into is i see myself doing a lot of conditional checks, checking if A is left of B or if A is right of B etc. I feel like I am missing some key intuition

I have a Point class that handles the coordinates"

```<code>public class Point {
    private final int mX;
    private final int mY;

    public Point(int mX, int mY) {
        this.mX = mX;
        this.mY = mY;
    }

    public int getX() {
        return mX;
    }

    public int getY() {
        return mY;
    }
}
</code>```

Here is my subview class:

```<code>public class Chart  {

    private int mColor;
    private Point mTopLeft;
    private Point mBottomRight;

    public Point getTopLeft() {
        return mTopLeft;
    }

    public Point getBottomRight() {
        return mBottomRight;
    }

    public Chart(int mColor, Point topLeft, Point bottomRight) {
        this.mColor = mColor;
        this.mTopLeft = topLeft;
        this.mBottomRight = bottomRight;
    }

    public int getColor() {
        return mColor;
    }

    public Point getTopRightCorner() {
        return new Point(getBottomRight().getX(), getTopLeft().getY());
    }

    public Point getBottomLeftCorner() {
        return new Point(getTopLeft().getX(), getBottomRight().getY());
    }
}
</code>```

My parent view class:

```<code>public class View {

    private Chart mChartA;
    private Chart mChartB;

    public View(Chart chartA,
                Chart chartB) {
        mChartA = chartA;
        mChartB = chartB;
    }

    public boolean doChartsOverlap() {
        boolean isOverlapped = true;

        if(isChartALeftOfChartBInX() || isChartARightOfChartBInX()) {
            isOverlapped = false;
        }

        if(isChartABottomOfChartBInY() || isChartATopOfChartBInY()) {
            isOverlapped = false;
        }
        return isOverlapped;
    }

    public final boolean isChartALeftOfChartBInX() {
        return mChartA.getBottomRight().getX() <= mChartB.getTopLeft().getX();
    }

    public final boolean isChartARightOfChartBInX() {
        return mChartA.getTopLeft().getX() >= mChartB.getBottomRight().getX();
    }

    public final boolean isChartATopOfChartBInY() {
        return mChartA.getBottomRight().getY() <= mChartB.getTopLeft().getY();
    }

    public final boolean isChartABottomOfChartBInY() {
        return mChartA.getTopLeft().getY() >= mChartB.getBottomRight().getY();
    }

    public void setChartA(Chart mChartA) {
        this.mChartA = mChartA;
    }

    public void setChartB(Chart mChartB) {
        this.mChartB = mChartB;
    }
}
</code>```

答:
```<code>Rectangle r1 = new Rectangle(x1, y1, width1, height1 );
Rectangle r2 = new Rectangle(x2, y2, width2, height2);
if ( r1.contains( x3, y3 ) && r2.contains( x3, y3 ) ) {
   // (x3,y3) is in both rectangles
}
</code>```

Body:
Say I have this view with two subviews A and B, A and B has a color property mColor,

I want a function in the parent view that has this signature: int getColor(int x, int y), which for any given x and y coordinate, return the color at that position, if the x and y coordinates land and the two shapes are overlapped, return the average color of A and B

The problem I am running into is i see myself doing a lot of conditional checks, checking if A is left of B or if A is right of B etc. I feel like I am missing some key intuition

I have a Point class that handles the coordinates"

public class Point {
    private final int mX;
    private final int mY;

    public Point(int mX, int mY) {
        this.mX = mX;
        this.mY = mY;
    }

    public int getX() {
        return mX;
    }

    public int getY() {
        return mY;
    }
}

Here is my subview class:

public class Chart  {

    private int mColor;
    private Point mTopLeft;
    private Point mBottomRight;

    public Point getTopLeft() {
        return mTopLeft;
    }

    public Point getBottomRight() {
        return mBottomRight;
    }

    public Chart(int mColor, Point topLeft, Point bottomRight) {
        this.mColor = mColor;
        this.mTopLeft = topLeft;
        this.mBottomRight = bottomRight;
    }

    public int getColor() {
        return mColor;
    }

    public Point getTopRightCorner() {
        return new Point(getBottomRight().getX(), getTopLeft().getY());
    }

    public Point getBottomLeftCorner() {
        return new Point(getTopLeft().getX(), getBottomRight().getY());
    }
}

My parent view class:

public class View {

    private Chart mChartA;
    private Chart mChartB;

    public View(Chart chartA,
                Chart chartB) {
        mChartA = chartA;
        mChartB = chartB;
    }

    public boolean doChartsOverlap() {
        boolean isOverlapped = true;

        if(isChartALeftOfChartBInX() || isChartARightOfChartBInX()) {
            isOverlapped = false;
        }

        if(isChartABottomOfChartBInY() || isChartATopOfChartBInY()) {
            isOverlapped = false;
        }
        return isOverlapped;
    }

    public final boolean isChartALeftOfChartBInX() {
        return mChartA.getBottomRight().getX() <= mChartB.getTopLeft().getX();
    }

    public final boolean isChartARightOfChartBInX() {
        return mChartA.getTopLeft().getX() >= mChartB.getBottomRight().getX();
    }

    public final boolean isChartATopOfChartBInY() {
        return mChartA.getBottomRight().getY() <= mChartB.getTopLeft().getY();
    }

    public final boolean isChartABottomOfChartBInY() {
        return mChartA.getTopLeft().getY() >= mChartB.getBottomRight().getY();
    }

    public void setChartA(Chart mChartA) {
        this.mChartA = mChartA;
    }

    public void setChartB(Chart mChartB) {
        this.mChartB = mChartB;
    }
}


问:
How to leave/exit/deactivate a Python virtualenv
I'm using virtualenv and the virtualenvwrapper. I can switch between virtualenv's just fine using the workon command.

```<code>me@mymachine:~$ workon env1
(env1)me@mymachine:~$ workon env2
(env2)me@mymachine:~$ workon env1
(env1)me@mymachine:~$
</code>```

How do I exit all virtual environments and work on my system environment again? Right now, the only way I have of getting back to me@mymachine:~$ is to exit the shell and start a new one. That's kind of annoying. Is there a command to work on "nothing", and if so, what is it? If such a command does not exist, how would I go about creating it?

答:
Using the deactivate feature provided by the venv's activate script requires you to trust the deactivation function to be properly coded to cleanly reset all environment variables back to how they were before— taking into account not only the original activation, but also any switches, configuration, or other work you may have done in the meantime.

It's probably fine, but it does introduce a new, non-zero risk of leaving your environment modified afterwards.

However, it's not technically possible for a process to directly alter the environment variables of its parent, so we can use a separate sub-shell to be absolutely sure our venvs don't leave any residual changes behind:

To activate:

$ bash --init-file PythonVenv/bin/activate

This starts a new shell around the venv. Your original bash shell remains unmodified.

To deactivate:

$ exit OR [CTRL]+[D]

This exits the entire shell the venv is in, and drops you back to the original shell from before the activation script made any changes to the environment.

Example:

```<code>[user@computer ~]$ echo $VIRTUAL_ENV
No virtualenv!

[user@computer ~]$ bash --init-file PythonVenv/bin/activate

(PythonVenv) [user@computer ~]$ echo $VIRTUAL_ENV
/home/user/PythonVenv

(PythonVenv) [user@computer ~]$ exit
exit

[user@computer ~]$ echo $VIRTUAL_ENV
No virtualenv!
</code>```

Body:
I'm using virtualenv and the virtualenvwrapper. I can switch between virtualenv's just fine using the workon command.

me@mymachine:~$ workon env1
(env1)me@mymachine:~$ workon env2
(env2)me@mymachine:~$ workon env1
(env1)me@mymachine:~$

How do I exit all virtual environments and work on my system environment again? Right now, the only way I have of getting back to me@mymachine:~$ is to exit the shell and start a new one. That's kind of annoying. Is there a command to work on "nothing", and if so, what is it? If such a command does not exist, how would I go about creating it?

Body:
Using the deactivate feature provided by the venv's activate script requires you to trust the deactivation function to be properly coded to cleanly reset all environment variables back to how they were before— taking into account not only the original activation, but also any switches, configuration, or other work you may have done in the meantime.

It's probably fine, but it does introduce a new, non-zero risk of leaving your environment modified afterwards.

However, it's not technically possible for a process to directly alter the environment variables of its parent, so we can use a separate sub-shell to be absolutely sure our venvs don't leave any residual changes behind:

To activate:

$ bash --init-file PythonVenv/bin/activate

This starts a new shell around the venv. Your original bash shell remains unmodified.

To deactivate:

$ exit OR [CTRL]+[D]

This exits the entire shell the venv is in, and drops you back to the original shell from before the activation script made any changes to the environment.

Example:

[user@computer ~]$ echo $VIRTUAL_ENV
No virtualenv!

[user@computer ~]$ bash --init-file PythonVenv/bin/activate

(PythonVenv) [user@computer ~]$ echo $VIRTUAL_ENV
/home/user/PythonVenv

(PythonVenv) [user@computer ~]$ exit
exit

[user@computer ~]$ echo $VIRTUAL_ENV
No virtualenv!


问:
Blocking the movement of an object in a boundary
I am trying to make an web application that would simulate a joystick control. I have managed to generate 2 circles on click. (one stationary as a boundary and another following my mouse cursor as a joystick). Right now I am trying to figure out how to restrict the joystick movement inside the generated boundary. Any help would be appreciated.</p>

```<code><div class="eye"> </div>
    <div class="ball">

    </div>
</div>
<script>
    var balls = document.getElementsByClassName("ball");
    document.onmousemove = function () {
        var x = event.clientX + "px";
        var y = event.clientY + "px";
        // event.clientX => gets the horizontal coordinate of the mouse
        // event.clientY => gets the vertical coordinate of the mouse
        // window.innerWidth => gets the browser width
        // window.innerHeight => gets the browser height

        for (var i = 0; i < 20; i++) {
            balls[i].style.left = x;
            balls[i].style.top = y;
            balls[i].style.transform = "translate(x , y)"
        }
</code>```

答:
Maybe quickest solution is to divide x to a number. Tricky but should work.

```<code>balls[i].style.left = x /10;
balls[i].style.top = y/10;
</code>```

and why do you need that loop? It will prevent this solution.

Body:
Maybe quickest solution is to divide x to a number. Tricky but should work.

balls[i].style.left = x /10;
balls[i].style.top = y/10;

and why do you need that loop? It will prevent this solution.


问:
Why parallel for of openmp does not work for vectorized color space conversion?
I have vectorized the color space conversion algorithm (RGB to YCbCr). when I don't use threads (#pragma omp parallel for) everything seems to be fine. But when I try to use threads it can not improve the performance of the vectorized version of my codes (It also disimproves).

Threads speedups the scalar code, the auto-vectorized code and the OpenMP SIMDized code (#pragma omp parallel for simd)

I have no idea what is going on and need your help.

Thanks in advance

I use fedora 31, Intel corei7 6700HQ, 12GB RAM, ICC 19.0.3 (-Ofast [-no-vec] -qopenmp -xHOST

Codes are as follows:

Scalar:

```<code>//Scalar for basline
#include <stdio.h>
#define MAX1 512
#define MAX2 MAX1

float  __attribute__(( aligned(32))) image_r[MAX1][MAX2], image_g[MAX1][MAX2], image_b[MAX1][MAX2], image_y[MAX1][MAX2], image_cb[MAX1][MAX2], image_cr[MAX1][MAX2];
float coeff_RTY[3][3] = {{0.299, 0.587, 0.114},{-0.169, -0.331, 0.500},{0.500, -0.419, -0.081}};

inline void fill_float(float a[MAX1][MAX1])
{
    int i,j;
    for(i=0; i<MAX1; i++){

        for(j=0; j<MAX2; j++){
            a[i][j] = (i+j+100)%256;

        }
    }
}
int main()
{
    fill_float(image_r);
    fill_float(image_g);
    fill_float(image_b);

    int i, j;
    long t1,t2,min=100000000000000;
    do{
        t1=_rdtsc();
        //#pragma omp parallel for
        for( i=0; i<MAX1; i++){
        for( j=0; j<MAX2; j++){

        image_y[i][j] = coeff_RTY[0][0]*image_r[i][j] + coeff_RTY[0][1]*image_g[i][j] + coeff_RTY[0][2]*image_b[i][j];
        image_cb[i][j] = coeff_RTY[1][0]*image_r[i][j] + coeff_RTY[1][1]*image_g[i][j] + coeff_RTY[1][2]*image_b[i][j] + 128;
        image_cr[i][j] = coeff_RTY[2][0]*image_r[i][j] + coeff_RTY[2][1]*image_g[i][j] + coeff_RTY[2][2]*image_b[i][j] + 128;

        }
        }

        t2=_rdtsc();

        if((t2-t1)<min){
            min=t2-t1;
            printf("\n%li", t2-t1);
        }
    }while(1);
    printf("%f", image_y[MAX1/2][MAX2/2]);
    printf("%f", image_cb[MAX1/2][MAX2/2]);
    printf("%f", image_cr[MAX1/2][MAX2/2]);
    return 0;
}
</code>```

And the vectorized version using AVX (floating point):

```<code>//AVX
#include <stdio.h>
#include <x86intrin.h>
#define MAX1 512
#define MAX2 MAX1

float  __attribute__(( aligned(32))) image_r[MAX1][MAX2], image_g[MAX1][MAX2], image_b[MAX1][MAX2], image_y[MAX1][MAX2], image_cb[MAX1][MAX2], image_cr[MAX1][MAX2];
float coeff_RTY[3][3] = {{0.299, 0.587, 0.114},{-0.169, -0.331, 0.500},{0.500, -0.419, -0.081}};

inline void fill_float(float a[MAX1][MAX1])
{
    int i,j;
    for(i=0; i<MAX1; i++){

        for(j=0; j<MAX2; j++){
            a[i][j] = (i+j+100)%256;

        }
    }
}
int main()
{

    //program variables:
    //calculate filter coeff or use an existing one
    __m256 vec_c[3][3], vec_128;
    __m256 vec_r, vec_g, vec_b, vec_y, vec_cb, vec_cr;
    __m256 vec_t[3][3], vec_sum;

    vec_c[0][0] = _mm256_set1_ps(coeff_RTY[0][0]);
    vec_c[0][1] = _mm256_set1_ps(coeff_RTY[0][1]);
    vec_c[0][2] = _mm256_set1_ps(coeff_RTY[0][2]);

    vec_c[1][0] = _mm256_set1_ps(coeff_RTY[1][0]);
    vec_c[1][1] = _mm256_set1_ps(coeff_RTY[1][1]);
    vec_c[1][2] = _mm256_set1_ps(coeff_RTY[1][2]);

    vec_c[2][0] = _mm256_set1_ps(coeff_RTY[2][0]);
    vec_c[2][1] = _mm256_set1_ps(coeff_RTY[2][1]);
    vec_c[2][2] = _mm256_set1_ps(coeff_RTY[2][2]);

    vec_128 = _mm256_set1_ps(128);
    //iorder to avoid optimization for zero values
    fill_float(image_r);
    fill_float(image_g);
    fill_float(image_b);
    int i, j=0;
    long t1,t2,min=100000000000000;
    do{
        t1=_rdtsc();

        //#pragma omp parallel for
        for( i=0; i<MAX1; i++){
            for( j=0; j<MAX2; j+=8){
            //_mm_prefetch(&image_r[i][j+8],_MM_HINT_T0);
            //_mm_prefetch(&image_g[i][j+8],_MM_HINT_T0);
            //_mm_prefetch(&image_b[i][j+8],_MM_HINT_T0);
            vec_r = _mm256_load_ps(&image_r[i][j]);
            vec_g = _mm256_load_ps(&image_g[i][j]);
            vec_b = _mm256_load_ps(&image_b[i][j]);

            vec_t[0][0] = _mm256_mul_ps(vec_r, vec_c[0][0]);
            vec_t[0][1] = _mm256_mul_ps(vec_g, vec_c[0][1]);
            vec_t[0][2] = _mm256_mul_ps(vec_b, vec_c[0][2]);

            vec_t[1][0] = _mm256_mul_ps(vec_r, vec_c[1][0]);
            vec_t[1][1] = _mm256_mul_ps(vec_g, vec_c[1][1]);
            vec_t[1][2] = _mm256_mul_ps(vec_b, vec_c[1][2]);

            vec_t[2][0] = _mm256_mul_ps(vec_r, vec_c[2][0]);
            vec_t[2][1] = _mm256_mul_ps(vec_g, vec_c[2][1]);
            vec_t[2][2] = _mm256_mul_ps(vec_b, vec_c[2][2]);

            //vec_y = vec_t[0][0] + vec_t[0][1] + vec_t[0][2]
            vec_sum = _mm256_add_ps(vec_t[0][0], vec_t[0][1]);
            vec_y = _mm256_add_ps(vec_t[0][2], vec_sum);

            //vec_cb = vec_t[1][0] + vec_t[1][1] + vec_t[1][2] +128
            vec_sum = _mm256_add_ps(vec_t[1][0], vec_t[1][1]);
            vec_sum = _mm256_add_ps(vec_t[1][2], vec_sum);
            vec_cb = _mm256_add_ps(vec_128, vec_sum);

            //vec_cr = vec_t[2][0] + vec_t[2][1] + vec_t[2][2] +128
            vec_sum = _mm256_add_ps(vec_t[2][0], vec_t[2][1]);
            vec_sum = _mm256_add_ps(vec_t[2][2], vec_sum);
            vec_cr = _mm256_add_ps(vec_128, vec_sum);

            _mm256_stream_ps(&image_y[i][j], vec_y);
            _mm256_stream_ps(&image_cb[i][j], vec_cb);
            _mm256_stream_ps(&image_cr[i][j], vec_cr);

            }
        }
        t2=_rdtsc();

        if((t2-t1)<min){
            min=t2-t1;
            printf("\n%li", t2-t1);
        }
    }while(1);

    //inorder to avoid optimization for non used values
    printf("%f", image_y[MAX1/2][MAX2/2]);
    printf("%f", image_cb[MAX1/2][MAX2/2]);
    printf("%f", image_cr[MAX1/2][MAX2/2]);

    return 0;
}
</code>```

UPDATE:

The best recorded cycles for 128x128 image size is as follows:

Single core:

```<code>Scalar code: 88k
Auto-vectorized: 59k
Vectorized using intrinsics: **21k**
vectorized by #pragma omp simd: 59k
</code>```

Multiple cores:

```<code>Scalar code: 25k
Auto-vectorized: 13k
Vectorized using intrinsics: **226k**
vectorized by #pragma omp .. simd: 22k
</code>```

For 1024x1024 image size is as follows:

Single core:

```<code>Scalar code: 7M
Auto-vectorized: 3M
Vectorized using intrinsics: **3M**
vectorized by #pragma omp simd: 3M
</code>```

Multiple cores:

```<code>Scalar code: 6M
Auto-vectorized: 6M
Vectorized using intrinsics: **15M**
vectorized by #pragma omp parallel for simd: 8M
</code>```

答:
After experimenting with different ideas, the problem was solved by adding the following line of OpenMP statements before the #pragma omp parallel for

omp_set_dynamic(3);

Therefore the results are:

Vectorized using intrinsics and
   Multi-core:

```<code>MAX1=128 --> 28k

MAX1=1024 --> 3M
</code>```

these results are not weird any more.

Any new results will be added to this answer in futures updates.

Body:
I have vectorized the color space conversion algorithm (RGB to YCbCr). when I don't use threads (#pragma omp parallel for) everything seems to be fine. But when I try to use threads it can not improve the performance of the vectorized version of my codes (It also disimproves).

Threads speedups the scalar code, the auto-vectorized code and the OpenMP SIMDized code (#pragma omp parallel for simd)

I have no idea what is going on and need your help.

Thanks in advance

I use fedora 31, Intel corei7 6700HQ, 12GB RAM, ICC 19.0.3 (-Ofast [-no-vec] -qopenmp -xHOST

Codes are as follows:

Scalar:

//Scalar for basline
#include <stdio.h>
#define MAX1 512
#define MAX2 MAX1

float  __attribute__(( aligned(32))) image_r[MAX1][MAX2], image_g[MAX1][MAX2], image_b[MAX1][MAX2], image_y[MAX1][MAX2], image_cb[MAX1][MAX2], image_cr[MAX1][MAX2];
float coeff_RTY[3][3] = {{0.299, 0.587, 0.114},{-0.169, -0.331, 0.500},{0.500, -0.419, -0.081}};

inline void fill_float(float a[MAX1][MAX1])
{
    int i,j;
    for(i=0; i<MAX1; i++){

        for(j=0; j<MAX2; j++){
            a[i][j] = (i+j+100)%256;

        }
    }
}
int main()
{
    fill_float(image_r);
    fill_float(image_g);
    fill_float(image_b);

    int i, j;
    long t1,t2,min=100000000000000;
    do{
        t1=_rdtsc();
        //#pragma omp parallel for
        for( i=0; i<MAX1; i++){
        for( j=0; j<MAX2; j++){

        image_y[i][j] = coeff_RTY[0][0]*image_r[i][j] + coeff_RTY[0][1]*image_g[i][j] + coeff_RTY[0][2]*image_b[i][j];
        image_cb[i][j] = coeff_RTY[1][0]*image_r[i][j] + coeff_RTY[1][1]*image_g[i][j] + coeff_RTY[1][2]*image_b[i][j] + 128;
        image_cr[i][j] = coeff_RTY[2][0]*image_r[i][j] + coeff_RTY[2][1]*image_g[i][j] + coeff_RTY[2][2]*image_b[i][j] + 128;

        }
        }

        t2=_rdtsc();

        if((t2-t1)<min){
            min=t2-t1;
            printf("\n%li", t2-t1);
        }
    }while(1);
    printf("%f", image_y[MAX1/2][MAX2/2]);
    printf("%f", image_cb[MAX1/2][MAX2/2]);
    printf("%f", image_cr[MAX1/2][MAX2/2]);
    return 0;
}

And the vectorized version using AVX (floating point):

//AVX
#include <stdio.h>
#include <x86intrin.h>
#define MAX1 512
#define MAX2 MAX1

float  __attribute__(( aligned(32))) image_r[MAX1][MAX2], image_g[MAX1][MAX2], image_b[MAX1][MAX2], image_y[MAX1][MAX2], image_cb[MAX1][MAX2], image_cr[MAX1][MAX2];
float coeff_RTY[3][3] = {{0.299, 0.587, 0.114},{-0.169, -0.331, 0.500},{0.500, -0.419, -0.081}};

inline void fill_float(float a[MAX1][MAX1])
{
    int i,j;
    for(i=0; i<MAX1; i++){

        for(j=0; j<MAX2; j++){
            a[i][j] = (i+j+100)%256;

        }
    }
}
int main()
{

    //program variables:
    //calculate filter coeff or use an existing one
    __m256 vec_c[3][3], vec_128;
    __m256 vec_r, vec_g, vec_b, vec_y, vec_cb, vec_cr;
    __m256 vec_t[3][3], vec_sum;

    vec_c[0][0] = _mm256_set1_ps(coeff_RTY[0][0]);
    vec_c[0][1] = _mm256_set1_ps(coeff_RTY[0][1]);
    vec_c[0][2] = _mm256_set1_ps(coeff_RTY[0][2]);

    vec_c[1][0] = _mm256_set1_ps(coeff_RTY[1][0]);
    vec_c[1][1] = _mm256_set1_ps(coeff_RTY[1][1]);
    vec_c[1][2] = _mm256_set1_ps(coeff_RTY[1][2]);

    vec_c[2][0] = _mm256_set1_ps(coeff_RTY[2][0]);
    vec_c[2][1] = _mm256_set1_ps(coeff_RTY[2][1]);
    vec_c[2][2] = _mm256_set1_ps(coeff_RTY[2][2]);

    vec_128 = _mm256_set1_ps(128);
    //iorder to avoid optimization for zero values
    fill_float(image_r);
    fill_float(image_g);
    fill_float(image_b);
    int i, j=0;
    long t1,t2,min=100000000000000;
    do{
        t1=_rdtsc();

        //#pragma omp parallel for
        for( i=0; i<MAX1; i++){
            for( j=0; j<MAX2; j+=8){
            //_mm_prefetch(&image_r[i][j+8],_MM_HINT_T0);
            //_mm_prefetch(&image_g[i][j+8],_MM_HINT_T0);
            //_mm_prefetch(&image_b[i][j+8],_MM_HINT_T0);
            vec_r = _mm256_load_ps(&image_r[i][j]);
            vec_g = _mm256_load_ps(&image_g[i][j]);
            vec_b = _mm256_load_ps(&image_b[i][j]);

            vec_t[0][0] = _mm256_mul_ps(vec_r, vec_c[0][0]);
            vec_t[0][1] = _mm256_mul_ps(vec_g, vec_c[0][1]);
            vec_t[0][2] = _mm256_mul_ps(vec_b, vec_c[0][2]);

            vec_t[1][0] = _mm256_mul_ps(vec_r, vec_c[1][0]);
            vec_t[1][1] = _mm256_mul_ps(vec_g, vec_c[1][1]);
            vec_t[1][2] = _mm256_mul_ps(vec_b, vec_c[1][2]);

            vec_t[2][0] = _mm256_mul_ps(vec_r, vec_c[2][0]);
            vec_t[2][1] = _mm256_mul_ps(vec_g, vec_c[2][1]);
            vec_t[2][2] = _mm256_mul_ps(vec_b, vec_c[2][2]);

            //vec_y = vec_t[0][0] + vec_t[0][1] + vec_t[0][2]
            vec_sum = _mm256_add_ps(vec_t[0][0], vec_t[0][1]);
            vec_y = _mm256_add_ps(vec_t[0][2], vec_sum);

            //vec_cb = vec_t[1][0] + vec_t[1][1] + vec_t[1][2] +128
            vec_sum = _mm256_add_ps(vec_t[1][0], vec_t[1][1]);
            vec_sum = _mm256_add_ps(vec_t[1][2], vec_sum);
            vec_cb = _mm256_add_ps(vec_128, vec_sum);

            //vec_cr = vec_t[2][0] + vec_t[2][1] + vec_t[2][2] +128
            vec_sum = _mm256_add_ps(vec_t[2][0], vec_t[2][1]);
            vec_sum = _mm256_add_ps(vec_t[2][2], vec_sum);
            vec_cr = _mm256_add_ps(vec_128, vec_sum);

            _mm256_stream_ps(&image_y[i][j], vec_y);
            _mm256_stream_ps(&image_cb[i][j], vec_cb);
            _mm256_stream_ps(&image_cr[i][j], vec_cr);

            }
        }
        t2=_rdtsc();

        if((t2-t1)<min){
            min=t2-t1;
            printf("\n%li", t2-t1);
        }
    }while(1);

    //inorder to avoid optimization for non used values
    printf("%f", image_y[MAX1/2][MAX2/2]);
    printf("%f", image_cb[MAX1/2][MAX2/2]);
    printf("%f", image_cr[MAX1/2][MAX2/2]);

    return 0;
}

UPDATE:

The best recorded cycles for 128x128 image size is as follows:

Single core:

Scalar code: 88k
Auto-vectorized: 59k
Vectorized using intrinsics: **21k**
vectorized by #pragma omp simd: 59k

Multiple cores:

Scalar code: 25k
Auto-vectorized: 13k
Vectorized using intrinsics: **226k**
vectorized by #pragma omp .. simd: 22k

For 1024x1024 image size is as follows:

Single core:

Scalar code: 7M
Auto-vectorized: 3M
Vectorized using intrinsics: **3M**
vectorized by #pragma omp simd: 3M

Multiple cores:

Scalar code: 6M
Auto-vectorized: 6M
Vectorized using intrinsics: **15M**
vectorized by #pragma omp parallel for simd: 8M

Body:
After experimenting with different ideas, the problem was solved by adding the following line of OpenMP statements before the #pragma omp parallel for

omp_set_dynamic(3);

Therefore the results are:

Vectorized using intrinsics and
   Multi-core:

MAX1=128 --> 28k

MAX1=1024 --> 3M

these results are not weird any more.

Any new results will be added to this answer in futures updates.


问:
"Must provide query string." graphene-python
i try to send a file as following in Altair tool to graphql (backend is graphene-python).
I use this library  for backend

but every it raises this error: Must provide query string.
how can I upload a file to graphql?

答:
There are a couple of things that could be the culprit here:

The file attached might not be valid (Extra validations have been added to Altair to inform you about this)

The server might not recognize the multipart request, and might still be expecting JSON, which wouldn't work in this case (since the file upload requires the request to be using the multipart specification)

To verify what the issue is, you can verify that the right data is being sent from Altair by looking at the network tab of the developer tools in Altair, and also checking that the server is properly configured to work with the multipart format.


问:
Lombok is not generating getter and setter
I just tried to send a Maven-based project to another computer and HORROR,
red markers everywhere!!

However, mvn clean install is building just fine.

Quickly, I noticed that Lombok is not generating getters and setters for my classes, although the @Getter and @Setter are being correctly recognised by Eclipse.

Both computers use the same Maven version (3.0.4) but different JDKs (1.6_23 and 1.6_33). They both use Eclipse Indigo 32 bit. Do you have an idea about how to solve the problem?

答:
What I had to do was to install lombok in the eclipse installation directory.

Download the lombok.jar from here and then install it using the following command:

```<code>java -jar lombok.jar
</code>```

After that make sure that the lombok.jar is added in your build path. But make sure you don't add it twice by adding once through maven or gradle and once again in eclipse path.

After that clean and build the project again and see all the errors go away.

Body:
What I had to do was to install lombok in the eclipse installation directory.

Download the lombok.jar from here and then install it using the following command:

java -jar lombok.jar

After that make sure that the lombok.jar is added in your build path. But make sure you don't add it twice by adding once through maven or gradle and once again in eclipse path.

After that clean and build the project again and see all the errors go away.


问:
How to deploy SAM stack with localstack?
I've written a SAM stack and I can build, package and deploy it on AWS. I can also use start-local or invoke to test. Now I need to test to other AWS resources. I've added those resources to my SAM template. It works well on AWS but I'm searching for a way to deploy my SAM stack in localstack (local dynamodb e.g.). Now I have to create the resources with the CLI and after that I can deploy my SAM stack (only lambda, API GW in this case). How can I do this?</p>

答:
I've just gone through this.  I think the following is correct.

AWS SAM is a wrapper round Cloudformation.   So your SAM template is actually a Cloudformation template.   Your Cloudformation template defines your lambdas and dynamodb etc.   When you deploy to AWS all of your lambdas and dynamodb go into AWS and you can test in the cloud.

When you run AWS SAM locally you run your lambda locally (in a docker container) but it still access resources in the AWS cloud.

LocalStack does have a CloudFormation interface, so it should be possible to deploy your CloudFormation template file.  But I ran into a few issues with this and gave up.

Serverless Framework is similar to AWS SAM in that it is a framework to develop your serveless (lambda) code and to deploy that to AWS.  Serverless has it's own yaml specification for defining a stack.  Converting from Cloudformation to Serverless yaml is a little bit of work.

There is a serverless plugin for localstack.  It is then possible to deploy your code to localstack.  If you have API Gateway infront of your lambdas then there will be a local url you can hit which triggers your lambdas.  This is fully within localstack and not using AWS SAM.

At this point you may find your code still hits the real AWS services.  So you need to change the endpoint-url to point locally, as Andrew A. mentioned.   For this, and to keep your code the same for test and production you can use environment variables for each of the service endpoints.

As Andrew A. mentions it should be possible to run code using SAM local which accesses resources provided by localstack.  However, it may be preferrable to keep to one tool, if this was done within a testing pipeline say.


问:
Passing data via URL with a post request in Slim
I’m creating an API and I’m wondering if there is any way to pass data via an URL with a post method for example

```<code>add?name={name}&age={age}…
</code>```

I don’t have much experience with API development, but I remember this URL thingy worked in Spring Boot.

Thanks in advance.

答:
You can pass data in URL like that in any type of HTTP Request.
That said when using POST / PUT / PATCH I would recommend using JSON payload sent as Request Body.

If you want to read an argument in Slim

```<code><?php
$app->get('/hello/{name}', function (Request $request, Response $response, array $args) {

    $name = $args['name'];

    // or
    $name = $request->getArgument('name');

    // When Request URL is
    // /hello/world?age=24
    // you can read the age argument as
    $name = $request->getArgument('age');

    // This behaviour is defined in PSR-7 and available across PHP frameworks

    return $response;
});
</code>```

In plain PHP you can read an argument using superglobal $_GET or $_POST

```<code><?php
$name = $_GET['age'];
</code>```

Body:
I’m creating an API and I’m wondering if there is any way to pass data via an URL with a post method for example

add?name={name}&age={age}…

I don’t have much experience with API development, but I remember this URL thingy worked in Spring Boot.

Thanks in advance.

Body:
You can pass data in URL like that in any type of HTTP Request.
That said when using POST / PUT / PATCH I would recommend using JSON payload sent as Request Body.

If you want to read an argument in Slim

<?php
$app->get('/hello/{name}', function (Request $request, Response $response, array $args) {

    $name = $args['name'];

    // or
    $name = $request->getArgument('name');

    // When Request URL is
    // /hello/world?age=24
    // you can read the age argument as
    $name = $request->getArgument('age');

    // This behaviour is defined in PSR-7 and available across PHP frameworks

    return $response;
});

In plain PHP you can read an argument using superglobal $_GET or $_POST

<?php
$name = $_GET['age'];


问:
How to get OperationDescription from OperationContext on AfterReceiveRequest in WCF?
In my implementation of IDispatchMessageInspector on the AfterReceiveRequest
I want to check if an OperationBehavior is applied on the current operation being called.
So I need to access OperationDescription of the operation that's about to get invoked??
Any direct way instead of having to compare the Action of the current operation with all the in the DispatchRuntime?

Thanks..

答:
I had the same issue and solved through below way.

```<code>OperationContext ctx = OperationContext.Current;
ServiceDescription hostDesc = ctx.Host.Description;
ServiceEndpoint endpoint = hostDesc.Endpoints.Find(ctx.IncomingMessageHeaders.To);
string operationName = ctx.IncomingMessageHeaders.Action.Replace(
  endpoint.Contract.Namespace + endpoint.Contract.Name + "/", "");
OperationDescription operation =
endpoint.Contract.Operations.Find(operationName);
</code>```

This is suggested solution at msdn forum

ContentLicense: CC BY-SA 2.5

Body:
I had the same issue and solved through below way.

OperationContext ctx = OperationContext.Current;
ServiceDescription hostDesc = ctx.Host.Description;
ServiceEndpoint endpoint = hostDesc.Endpoints.Find(ctx.IncomingMessageHeaders.To);
string operationName = ctx.IncomingMessageHeaders.Action.Replace(
  endpoint.Contract.Namespace + endpoint.Contract.Name + "/", "");
OperationDescription operation =
endpoint.Contract.Operations.Find(operationName);

This is suggested solution at msdn forum


问:
AWS CloudTrail: Can I disable S3 storage for trails, since I'm using CloudWatch
When setting up CloudTrail, you must specific a S3 bucket to store the data in.

Since I'm using CloudWatch (and CloudWatch metrics/alarms) for storage, I do not believe that I also need to store the data redundantly in S3.

Is there a reason even after configuring CloudWatch for CloudTrail, that I must also keep using S3 storage? Is there a way to turn off S3 storage for CloudTrail?

答:
You can turn off logging for any trail:

When you create a trail, logging is turned on automatically. You can turn off logging for a trail. Previous logs will still be accessible.

See https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-turning-off-logging.html