问:
Calling an overridden function from a base constructor
It makes sense that I should not call an overridden function from a base constructor, since the derived class is not yet constructed.

But I want to use this design pattern, where each derived class provides methods for calculating the properties of the base class since the properties should be immutable and assigned at the constructor.

Shape.cs

```<code>public abstract class Shape
{
    protected Shape()
    {
        Area = 0f;
        Center = Vector2.Zero;
        const int n = 36;
        float du = 1/(float)n, dv = 1/(float)n;
        for (int i = 0; i < n; i++)
        {
            float u = (i+0.5f)*du;
            for (int j = 0; j < n; j++)
            {
                float v = (i+0.5f)*dv;
                float f = GetAreaElement(u, v);
                // Warning: Remove this call from a constructor to the overridable 'GetAreaElement' method.
                Area += f*du*dv;
                Center += GetPosition(u, v)*f*du*dv;
                // Warning: Remove this call from a constructor to the overridable 'GetPosition' method.
            }
        }
        Center /= Area;
    }

    public abstract Vector2 GetPosition(float u, float v);
    protected abstract float GetAreaElement(float u, float v);

    public float Area { get;  }
    public Vector2 Center { get; }
}

public class Circle : Shape
{
    public Circle(float radius)
    {
        Radius=radius;
    }

    public float Radius { get; }

    public override Vector2 GetPosition(float u, float v)
    {
        float r = u*Radius, θ = (float)(2*Math.PI)*v;
        return new Vector2(
            r*(float)Math.Cos(θ),
            r*(float)Math.Sin(θ));
    }

    protected override float GetAreaElement(float u, float v)
    {
        return u*Radius;
    }
}

public class Rectangle : Shape
{
    public Rectangle(float side1, float side2)
    {
        Side1=side1;
        Side2=side2;
    }

    public float Side1 { get; }
    public float Side2 { get; }

    public override Vector2 GetPosition(float u, float v)
    {
        return new Vector2((u-0.5f)*Side1, (v-0.5f)*Side2);
    }

    protected override float GetAreaElement(float u, float v)
    {
        return Side1*Side2;
    }
}
</code>```

So what is the solution here? I want to use the base constructor to define the properties, and the calculation depends on the implementation of the derived class.

Workaround 1 - Future calculator

A workaround would be to provide a protected function that calculates the properties, each to be called from each constructor of the derived class, but there is no enforcement here. If one class forgets to call the calculator function the whole thing falls apart. And the properties are now private set which is not immutable really.

```<code>public abstract class Shape
{
    protected void Calculate()
    {
        ...
        float f = GetAreaElement(u, v);
        ...
        Center += GetPosition(u, v)*f*du*dv;
        ...
    }

    public abstract Vector2 GetPosition(float u, float v);
    protected abstract float GetAreaElement(float u, float v);

    public float Area { get; private set; }
    public Vector2 Center { get; private set; }
}

public class Circle : Shape
{
    public Circle(float radius)
    {
        Radius=radius;

        base.Calculate();
    }

    public float Radius { get; }

    public override Vector2 GetPosition(float u, float v)
    {
        ...
    }

    protected override float GetAreaElement(float u, float v)
    {
        ...
    }
}
</code>```

Workaround 2 - Function delegates

Another workaround would be to supply the delegates to the required function implementations as arguments to the base class constructor.

```<code>public delegate float AreaFactor(float u, float v);
public delegate Vector2 PositionFunc(float u, float v);
public abstract class Shape
{
    protected Shape(AreaFactor a, PositionFunc p)
    {
        this.GetAreaElement = a;
        this.GetPosition = p;
        ...
        float f = a(u, v);
        this.Center += p(u, v)*f*du*dv;
        ...
    }

    public float Area { get; }
    public Vector2 Center { get;  }

    public AreaFactor GetAreaElement { get; }
    public PositionFunc GetPosition { get; }
}

public class Circle : Shape
{
    public Circle(float radius)
        : base(
              (u, v) => u*radius,
              (u,v)=>
                {
                    float r = u*radius, θ = (float)(2*Math.PI)*v;
                    return new Vector2(
                        r*(float)Math.Cos(θ),
                        r*(float)Math.Sin(θ));
                })
    {
        Radius=radius;
    }

    public float Radius { get; }
}
</code>```

This seems a bit clunky to me, and I am not sure I like the function delegate properties, instead of overridden methods.

Question/Challege

Can [SO] provide some other ways of achieving the above-stated goals

Base properties are immutable

Base properties are calculated at the constructor based on the implementation details of the derived classes.

Each derived class holds its own immutable properties used to describe the derived class.

答:
My preference is to go with Option 2 - passing to the base constructor the methods to generate the derived properties. It does satisfy all your requirements. If aesthetics is a concern, perhaps using a Func might make the code easier to read. The key is that the Func's are static methods, which should not be a problem since they calculate immutable properties of the object.

```<code>void Main()
{
    var square = new Square(5);
}

public abstract class Shape
{
    protected Shape(Func<int> areaFunc)
    {
        Area = areaFunc();
    }

    public int Area { get; }
}

public class Square : Shape
{
    public Square(int side): base( () =>  CalcArea(side) )
    {
        Side = side;
    }

    static int CalcArea(int side) => side * side;

    public int Side { get; }
}
</code>```

Body:
It makes sense that I should not call an overridden function from a base constructor, since the derived class is not yet constructed.

But I want to use this design pattern, where each derived class provides methods for calculating the properties of the base class since the properties should be immutable and assigned at the constructor.

Shape.cs

public abstract class Shape
{
    protected Shape()
    {
        Area = 0f;
        Center = Vector2.Zero;
        const int n = 36;
        float du = 1/(float)n, dv = 1/(float)n;
        for (int i = 0; i < n; i++)
        {
            float u = (i+0.5f)*du;
            for (int j = 0; j < n; j++)
            {
                float v = (i+0.5f)*dv;
                float f = GetAreaElement(u, v);
                // Warning: Remove this call from a constructor to the overridable 'GetAreaElement' method.
                Area += f*du*dv;
                Center += GetPosition(u, v)*f*du*dv;
                // Warning: Remove this call from a constructor to the overridable 'GetPosition' method.
            }
        }
        Center /= Area;
    }

    public abstract Vector2 GetPosition(float u, float v);
    protected abstract float GetAreaElement(float u, float v);

    public float Area { get;  }
    public Vector2 Center { get; }
}

public class Circle : Shape
{
    public Circle(float radius)
    {
        Radius=radius;
    }

    public float Radius { get; }

    public override Vector2 GetPosition(float u, float v)
    {
        float r = u*Radius, θ = (float)(2*Math.PI)*v;
        return new Vector2(
            r*(float)Math.Cos(θ),
            r*(float)Math.Sin(θ));
    }

    protected override float GetAreaElement(float u, float v)
    {
        return u*Radius;
    }
}

public class Rectangle : Shape
{
    public Rectangle(float side1, float side2)
    {
        Side1=side1;
        Side2=side2;
    }

    public float Side1 { get; }
    public float Side2 { get; }

    public override Vector2 GetPosition(float u, float v)
    {
        return new Vector2((u-0.5f)*Side1, (v-0.5f)*Side2);
    }

    protected override float GetAreaElement(float u, float v)
    {
        return Side1*Side2;
    }
}

So what is the solution here? I want to use the base constructor to define the properties, and the calculation depends on the implementation of the derived class.

Workaround 1 - Future calculator

A workaround would be to provide a protected function that calculates the properties, each to be called from each constructor of the derived class, but there is no enforcement here. If one class forgets to call the calculator function the whole thing falls apart. And the properties are now private set which is not immutable really.

public abstract class Shape
{
    protected void Calculate()
    {
        ...
        float f = GetAreaElement(u, v);
        ...
        Center += GetPosition(u, v)*f*du*dv;
        ...
    }

    public abstract Vector2 GetPosition(float u, float v);
    protected abstract float GetAreaElement(float u, float v);

    public float Area { get; private set; }
    public Vector2 Center { get; private set; }
}

public class Circle : Shape
{
    public Circle(float radius)
    {
        Radius=radius;

        base.Calculate();
    }

    public float Radius { get; }

    public override Vector2 GetPosition(float u, float v)
    {
        ...
    }

    protected override float GetAreaElement(float u, float v)
    {
        ...
    }
}

Workaround 2 - Function delegates

Another workaround would be to supply the delegates to the required function implementations as arguments to the base class constructor.

public delegate float AreaFactor(float u, float v);
public delegate Vector2 PositionFunc(float u, float v);
public abstract class Shape
{
    protected Shape(AreaFactor a, PositionFunc p)
    {
        this.GetAreaElement = a;
        this.GetPosition = p;
        ...
        float f = a(u, v);
        this.Center += p(u, v)*f*du*dv;
        ...
    }

    public float Area { get; }
    public Vector2 Center { get;  }

    public AreaFactor GetAreaElement { get; }
    public PositionFunc GetPosition { get; }
}

public class Circle : Shape
{
    public Circle(float radius)
        : base(
              (u, v) => u*radius,
              (u,v)=>
                {
                    float r = u*radius, θ = (float)(2*Math.PI)*v;
                    return new Vector2(
                        r*(float)Math.Cos(θ),
                        r*(float)Math.Sin(θ));
                })
    {
        Radius=radius;
    }

    public float Radius { get; }
}

This seems a bit clunky to me, and I am not sure I like the function delegate properties, instead of overridden methods.

Question/Challege

Can [SO] provide some other ways of achieving the above-stated goals

Base properties are immutable

Base properties are calculated at the constructor based on the implementation details of the derived classes.

Each derived class holds its own immutable properties used to describe the derived class.

Body:
My preference is to go with Option 2 - passing to the base constructor the methods to generate the derived properties. It does satisfy all your requirements. If aesthetics is a concern, perhaps using a Func might make the code easier to read. The key is that the Func's are static methods, which should not be a problem since they calculate immutable properties of the object.

void Main()
{
    var square = new Square(5);
}

public abstract class Shape
{
    protected Shape(Func<int> areaFunc)
    {
        Area = areaFunc();
    }

    public int Area { get; }
}

public class Square : Shape
{
    public Square(int side): base( () =>  CalcArea(side) )
    {
        Side = side;
    }

    static int CalcArea(int side) => side * side;

    public int Side { get; }
}


来源: stackexchange

问:
How to import multiple components to main.js in svelte js?
How could import an svelte component to a "target" different to body?

https://github.com/sveltejs/template/blob/master/src/main.js

I am trying the next:

```<code>import App from './App.svelte';
export default new App({ target: document.body.div});
</code>```

How could I export multiple componentes to different targets?

```<code>import App1 from './App1.svelte';
import App2 from './App2.svelte';
export default new App1({ target: document.body.div1});
export default new App2({ target: document.body.div2});
</code>```

答:
You can use named exports, like:

```<code>import App1 from './App1.svelte';
import App2 from './App2.svelte';

export const app1 = new App1({ target: document.getElementById("app1")});
export const app2 = new App2({ target: document.getElementById("app2")});
</code>```

And in Your html you need to have the following elements:

```<code><div id="app1"></div>
<div id="app2"></div>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How could import an svelte component to a "target" different to body?

https://github.com/sveltejs/template/blob/master/src/main.js

I am trying the next:

import App from './App.svelte';
export default new App({ target: document.body.div});

How could I export multiple componentes to different targets?

import App1 from './App1.svelte';
import App2 from './App2.svelte';
export default new App1({ target: document.body.div1});
export default new App2({ target: document.body.div2});

Body:
You can use named exports, like:

import App1 from './App1.svelte';
import App2 from './App2.svelte';

export const app1 = new App1({ target: document.getElementById("app1")});
export const app2 = new App2({ target: document.getElementById("app2")});

And in Your html you need to have the following elements:

<div id="app1"></div>
<div id="app2"></div>


问:
Multi Object Unbound Action for updating Contained Entities in OData
In OData, a contained entity does not have an entity set. All operations on it should be through the parent entity. And this is true for single-object APIs.

Can we have an unbound action to update multiple such contained entities by directly providing the ID with no parent in context? Would this be according to the Odata specs?

Thanks and Regards,
Jyothi

答:
You could do it, but as an Unbound Function that is technically all it is, Unbound, there is nothing in the specification preventing you from doing it this way but it would not be constrained to a specific resource by route. That makes the Action unintuitive in terms of both discovery and expectations.

The OData way to do this would be to bind the operation to the Parent Entity. If the operation affects or retrieves data across multiple entities or you really want to avoid needing to resolve the Parent key, then it should still be bound to the Collection rather than being Unbound.

Reserve Unbound Actions for operations that are outside of the model, diagnostics  or other esoteric implementations that otherwise don't have a single natural place in the OData Schema.

Having an Action That targets single or multiple Contained Entities without reference to the Parent is in the vicinity of being an Anti-Pattern, though I can not cite any sources that explicitly support this claim, the general reason for Contained Entities at all is because you can't directly reference the contained entity without the Parent Key, it was designed for scenarios where the Parent Key forms part of the Key for the contained item.

A classic example is Invoice and InvoiceLines. If your InvoiceLines Key is a simple Line Number and is only unique within the Invoice parent, so in the Database this might be a composite key using InvoiceId  and LineNumber. In this case we can only expose this Entity as being Contained within a specific Invoice because there is no other way to uniquely reference a single InvoiceLine item.

If your Contained Entity has a unique Key AND you intend on performing operations directly against these Entities without reference to the Parent Entity then that Entity really should be exposed as a top-level collection of it's own.


问:
Python os.path.join() and "+" in string concatenation
If I want to use a path "a/b", what is the difference between
os.path.join("a/","b") and "a/"+"b"  ?

Like this:

答:
The separator character is OS dependent. If you're going to be using your script on both windows and, say, linux, you should use the os.path.join function.

It probably doesn't matter if you're going to keep your script on the same machine, but you could also use the os.sep function to get the current system's separator character: https://docs.python.org/3/library/os.html#os.sep

In short, use os.path.join to keep your script multiplatform safe


问:
React-waypoint topOffset example code or how to use in reactjs
Can any one please tell me or send me sample code for how to write the code for topOffset in react-waypoint please.</p>

答:
Its really simple, you just need to add it as a prop < Waypoint topOffset="50px" />

For instance, if your app has a 50px fixed header, then you may want to specify topOffset='50px', so that the onEnter callback is called when waypoints scroll into view from beneath the header. You can check the documentation here

I coded a simple example that might help in case you need it

https://codesandbox.io/s/testing-react-waypoint-mhukn?file=/src/App.tsx


问:
Remove item from array according to condition
I have an array (given below). I want to remove files, if minified version of the same file exist.

var files = ["foo.js", "foo.min.js", "bar.css","bar.min.css"];

// Should return: [foo.min.js", "bar.min.css"]

```
<pre class="lang-js prettyprint-override"><code>var files = ["foo.js", "foo.min.js", "bar.css"];

// Should return: [foo.min.js", "bar.css"]

</code>```

What i have tried

var files = ["foo.js", "bar.css"];

var tempUnMinified = [];
var tempMinified = [];
files.forEach(function (file) {
  if (file.endsWith(".min.js") || file.endsWith(".min.css")) {
    tempMinified.push(file);
  } else {
    tempUnMinified.push(file);
  }
});

tempUnMinified.forEach(function (unMinFile) {
  var tempRf = unMinFile.replace(".js", ".min.js").replace(".css", ".min.css");
  if (files.includes(tempRf)) {
    files.splice(files.indexOf(unMinFile), 1);
  }
});

console.log(files);

```

What i have tried does works, but i'm not sure if it works every time

and so on.. Thanks in advance

答:
It can be done a little more concisely and in a way that's independent of file type...

const files = ["foo.js", "foo.min.js", "bar.css","bar.min.css"];
const remove = {}

files.forEach(fn => {
  let comps = fn.split('.');
  // is the middle token min?
  if (comps.length === 3 && comps[1] === 'min') {
    // remember to remove the file without the middle token
    remove[`${comps[0]}.${comps[2]}`] = true;
  }
});
console.log(`will remove: ${Object.keys(remove)}`);

const filtered = files.filter(fn => !remove[fn]);
console.log(filtered);```

Body:
I have an array (given below). I want to remove files, if minified version of the same file exist.

var files = ["foo.js", "foo.min.js", "bar.css","bar.min.css"];

// Should return: [foo.min.js", "bar.min.css"]

var files = ["foo.js", "foo.min.js", "bar.css"];

// Should return: [foo.min.js", "bar.css"]

What i have tried

var files = ["foo.js", "bar.css"];

var tempUnMinified = [];
var tempMinified = [];
files.forEach(function (file) {
  if (file.endsWith(".min.js") || file.endsWith(".min.css")) {
    tempMinified.push(file);
  } else {
    tempUnMinified.push(file);
  }
});

tempUnMinified.forEach(function (unMinFile) {
  var tempRf = unMinFile.replace(".js", ".min.js").replace(".css", ".min.css");
  if (files.includes(tempRf)) {
    files.splice(files.indexOf(unMinFile), 1);
  }
});

console.log(files);

What i have tried does works, but i'm not sure if it works every time

and so on.. Thanks in advance


问:
How to use Java doulbe colon operator (::) in a multi-step sentence correctly?
I have a POJO class News with a method getAuthor(), that returns another POJO, Author. Author itself has a getter getRate(), this one returns int value. But I can't just make Comparator for News using double colons. I mean something like this (but, of course, that doesn't work):

```<code>Set<News> sortedNews = new TreeSet<>(Comparator.comparingInt(News::getAuthor::getRate));
</code>```

So the question is, how to write this correctly.

答:
The language doesn't allow you do it. Use a normal lambda expression.</p>
```<code>Comparator.comparingInt(news -> news.getAuthor().getRate())
</code>```

Body:
I have a POJO class News with a method getAuthor(), that returns another POJO, Author. Author itself has a getter getRate(), this one returns int value. But I can't just make Comparator for News using double colons. I mean something like this (but, of course, that doesn't work):

Set<News> sortedNews = new TreeSet<>(Comparator.comparingInt(News::getAuthor::getRate));

So the question is, how to write this correctly.

Body:
The language doesn't allow you do it. Use a normal lambda expression.

Comparator.comparingInt(news -> news.getAuthor().getRate())


问:
How to setState with fetched data in React
I need to setState with an object that I'm getting from a redux store. The problem is when I call setState in my component I am getting undefined. Any idea on how to set a default value of state with fetched data?

Here is my component:

```<code>import React, { useEffect, Fragment, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';

const contactDetails = useSelector((state) => state.contactDetails)

const upFields = contactDetails?.contact?.data?.fields

const [contact, setContact] = useState({
    fields:  upFields <---- this is returning undefined.. The name is correct, but maybe setState is running too fast?
  })

console.log(contact) <---- this shows {fields: undefined}

console.log(upFields) <---- this console.logs just fine
</code>```

答: So, I ended up setting my state one component higher, and passing the "upFields" to the child component that needed this state. Once in the child component I just ran a useEffect and setState with the data I needed</p>

Body:
I need to setState with an object that I'm getting from a redux store. The problem is when I call setState in my component I am getting undefined. Any idea on how to set a default value of state with fetched data?

Here is my component:

import React, { useEffect, Fragment, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';

const contactDetails = useSelector((state) => state.contactDetails)

const upFields = contactDetails?.contact?.data?.fields

const [contact, setContact] = useState({
    fields:  upFields <---- this is returning undefined.. The name is correct, but maybe setState is running too fast?
  })

console.log(contact) <---- this shows {fields: undefined}

console.log(upFields) <---- this console.logs just fine


问:
How to refer to LinearLayout in program code?
I am new to Kotlin and Android Studio. I'm trying to create a "Snake" game. I created a RelativeLayout and added two LinearLayouts to it. The first is for displaying the score, the second for the field of play and the snake itself. But when accessing the second LinearLayout via Id, I get an error. I also want to ask for help. I don't want to create a simple "snake", I'm trying to create a "beautiful" game. Like Google games "Snake". And who could help with my questions and writing code, could we go to the chat?)

答:
You should get the reference of linear layout in activity like this</p>
```<code>val llayout : LinearLayout = findViewById(R.id.snake)
</code>```

Body:
You should get the reference of linear layout in activity like this

val llayout : LinearLayout = findViewById(R.id.snake)


问:
Why is document.execCommand("paste") not working in Google Chrome?
I have a problem with my extension. I want to paste data from the clipboard.

So far, I've got this:

function pasteAndGo()
{
    document.execCommand('paste')
    alert("Pasted")
}
```

The alert comes up, but nothing has been pasted.

I've got a feeling it's the document part that needs changing, but I don't know what to do. Any ideas?

答:
There used to be an experimental clipboard API in Chrome, but this was removed in Chrome 13.

Chrome has moved towards the more standard document.execCommand('paste'), document.execCommand('copy') and document.execCommand('cut') commands: https://developer.mozilla.org/en/Rich-Text_Editing_in_Mozilla#Executing%5FCommands

In Chrome you'll need permissions need to be added to your manifest: "clipboardRead" and "clipboardWrite". http://developer.chrome.com/extensions/declare_permissions.html

Up until Chrome 38, these clipboard permissions were only available to extension pages such as background scripts. As of Chrome 39, content scripts can also use these clipboard APIs after declaring the clipboard permissions in the manifest file (crbug.com/395376).

Body:
I have a problem with my extension. I want to paste data from the clipboard.

So far, I've got this:

function pasteAndGo()
{
    document.execCommand('paste')
    alert("Pasted")
}

The alert comes up, but nothing has been pasted.

I've got a feeling it's the document part that needs changing, but I don't know what to do. Any ideas?

ContentLicense: CC BY-SA 3.0


问:
Eclipse Content Assist doesn't suggest jdk.* classes
I configured my project to use a Project Panama EA JDK, I can use jdk.incubator.foreign.* manually but Content Assist and Quick Fix don't suggest/fix anything from this package.

Is there a way to configure Content Assist or something?

(I looked into Preferences->Java->Editor->Content Assist, No luck there)

答:
I had the same problem, and found that eclipse by default is configured to not assist with classes named jdk.*.

I found this setting under Preferences -> Java -> Appearance -> Type Filters

Just remove jdk.* from this list.

(You may add jdk.*.internal.* instead)


问:
Set Application to cover area above taskbar, not over or under
Is there an existing function to place fullscreen window to cover full area above taskbar so taskbar is visible?</p>

答:
According to Player Settings -> Resolution

Fullscreen Mode
Choose the full-screen mode. This defines the default window mode at startup.

This is only possible on MAC:

Maximized Window (Mac only)
   Set the app window to the operating system’s definition of “maximized”. On macOS, this means a full-screen window with an auto-hidden menu bar and dock. This option is only supported on macOS; on other platforms, the setting falls back to Fullscreen Window.


问:
Cannot connect to the Docker daemon on macOS
I normally prefer to manage my apps on my OSX with brew

I am able to install docker, docker-compose and docker-machine

```<code>docker --version
Docker version 17.05.0-ce, build 89658be
docker-compose --version
docker-compose version 1.13.0, build unknown
docker-machine --version
docker-machine version 0.11.0, build 5b27455
</code>```

I did not download and run 'Docker for Mac' app.

However when I try to run

```<code>> docker run -d -p 80:80 --name webserver nginx
docker: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?.
See 'docker run --help'.
</code>```

I have already checked the sock file

```<code>ls -lah /var/run/docker.sock /var/tmp/docker.sock
ls: /var/run/docker.sock: No such file or directory
ls: /var/tmp/docker.sock: No such file or directory
</code>```

I have also tried this proposed solution: Mac OS X sudo docker Cannot connect to the Docker daemon. Is the docker daemon running on this host?

But I got this error message:

```<code>$ eval $(docker-machine env default)
Host does not exist: "default"
</code>```

Is it possible to get a docker service to run by command line tools?

答:
Docker was designed to run on Linux. It can, however, run in a VM on macOS. To do so is a bit of a kludge and that's perhaps why Docker Desktop exists in the first place. But that doesn't mean you can't enjoy using Docker from the comfort of the command line on a Mac.

Some options to consider:

You could use lima and add an alias docker='lima nerdctl' to your bash profile.

You could install a Linux VM on your machine and use it instead (not recommended).

Dual-boot Linux on Mac. Even machines with the T2 and M1 chips are supported now.

Body:
I normally prefer to manage my apps on my OSX with brew

I am able to install docker, docker-compose and docker-machine

docker --version
Docker version 17.05.0-ce, build 89658be
docker-compose --version
docker-compose version 1.13.0, build unknown
docker-machine --version
docker-machine version 0.11.0, build 5b27455

I did not download and run 'Docker for Mac' app.

However when I try to run

> docker run -d -p 80:80 --name webserver nginx
docker: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?.
See 'docker run --help'.

I have already checked the sock file

ls -lah /var/run/docker.sock /var/tmp/docker.sock
ls: /var/run/docker.sock: No such file or directory
ls: /var/tmp/docker.sock: No such file or directory

I have also tried this proposed solution: Mac OS X sudo docker Cannot connect to the Docker daemon. Is the docker daemon running on this host?

But I got this error message:

$ eval $(docker-machine env default)
Host does not exist: "default"

Is it possible to get a docker service to run by command line tools?


问:
How to call an outer method from within a handler
So I have A MouseListener class inside a public class with a few methods.
I have attached the mouseListener to a component in the public class.

The problem is I can't figure out a simple way to call the methods in the public class, whenever I say for example this.showRemove(); the scope is from within the handler class and not the public class. Here is some example code

```<code>public class Game {

 public Game() {

  JPanel pnl = new JPanel();
  pnl.addMouseListener(new GameMouseListener());

 }

 public void showRemove(){

  //Code Here

 }

 class GameMouseListener implements MouseListener {

  public void mouseClicked(MouseEvent e) {
     this.showRemove(); //Can't Find Symbol Here

  }

 }

}
</code>```

答:
Since showRemove is a non-static method of Game you need an instance of that class on which to call the method.

You could instead create an anonymous inner class like this:

```<code>pnl.addMouseListener(new MouseAdapter() {
  public void MouseClicked (MouseEvent e) {
    showRemove();
  }
});
</code>```

This listener will be associated with the running instance of Game and will therefore have access to its non-static methods.

Body:
So I have A MouseListener class inside a public class with a few methods.
I have attached the mouseListener to a component in the public class.

The problem is I can't figure out a simple way to call the methods in the public class, whenever I say for example this.showRemove(); the scope is from within the handler class and not the public class. Here is some example code

public class Game {

 public Game() {

  JPanel pnl = new JPanel();
  pnl.addMouseListener(new GameMouseListener());

 }

 public void showRemove(){

  //Code Here

 }

 class GameMouseListener implements MouseListener {

  public void mouseClicked(MouseEvent e) {
     this.showRemove(); //Can't Find Symbol Here

  }

 }

}

Body:
Since showRemove is a non-static method of Game you need an instance of that class on which to call the method.

You could instead create an anonymous inner class like this:

pnl.addMouseListener(new MouseAdapter() {
  public void MouseClicked (MouseEvent e) {
    showRemove();
  }
});

This listener will be associated with the running instance of Game and will therefore have access to its non-static methods.


答:
you use useEffect() and trigger it using the object

```<code>useEffect(()=>{
  setContact(fetched_data)
}, [fetched_data]) // <-- data array will trigger every time this data change
</code>```

you can trigger it on first component mount with

```<code>useEffect(()=>{
  setContact(fetched_data)
}, []) // <-- empty array will only trigger once
</code>```

Title: How to setState with fetched data in React

Body:
you use useEffect() and trigger it using the object

useEffect(()=>{
  setContact(fetched_data)
}, [fetched_data]) // <-- data array will trigger every time this data change

you can trigger it on first component mount with

useEffect(()=>{
  setContact(fetched_data)
}, []) // <-- empty array will only trigger once


问:
set codeigniter output cache for individual users
$this->output->cache(MINUTES);
Is it possible for setting cache for individual users? There's a tourist spot listing page and showing it using cache. when one customer changes the location filter from  one computer, the next user results the other users list.

cache one users results on cache and showing it individually?

答: No, Caching For Individual User is not applicable till now in code igniter.You can check and learn for  caching : https://codeigniter.com/userguide3/general/caching.html</p>


问:
numpy.dot for dimensions > 2
I am trying to understand how dot product works for dimensions more than 2.

The documentation says:

If a is an N-D array and b is an M-D array (where M>=2), it is a sum product over the last # axis of a and the second-to-last axis of b:

```<code>dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
</code>```

I don't understand this rule -- where does it come from? Why is it the last axis of a and the second-to-last axis of b?

答:
It may be easier to visualize this using the notation of np.einsum. Start with regular 2D matrix multiplication, which is pretty unambiguous, and follows "normal math" rules:

```<code>a = np.ones((2, 3))
b = np.ones((3, 4))
np.einsum('ij,jk->ik', a, b)  # Same as a.dot(b)
</code>```

Now prepend a few dimensions:

```<code>a = np.ones((2, 3, 4, 5))
b = np.ones((8, 7, 5, 6))
np.einsum('ijkl,nolp->ijknop', a, b)  # Same as a.dot(b)
</code>```

In general, a multidimensional array can be thought of as a stack of matrices. There are a number of reasons that numpy generally places the "elements" of an array, whether features, samples, vectors, or matrices along the last dimensions. So, regardless of dot, it is fairly standard to think of a as a 2x3 array of 4x5 matrices. Similarly, b is a 8x7 array of 5x6 matrices.

There are two options going forward. The last two dimensions of the result are unambiguous no matter what choice you make: the output will contain 4x6 matrices. You can compute all the possible combinations of 2x3x8x7 such matrices, or you can expect the leading dimensions to broadcast together. np.dot takes the former approach, while @/np.matmul takes the latter. Anecdotally, I've found that most people will find the latter more intitive.

The exact reason that np.dot computes the matrix product of all possible combinations of a and b is known only to the developers making that choice. It likely revolves around not wanting to raise an error, and the rules of broadcasting not being as universally cemented at the time dot was first implemented. Once you decide to take the products of all the combinations, you can decide to do it like this:

```<code>np.einsum('ijkl,nolp->ijnokp', a, b)  # Not `np.dot`
</code>```

On the one hand, this would reflect the idea of a 2x3x8x7 array of 4x6 matrices better. On the other hand, it creates an awkward permutation of dimensions with k out of place in the sequence. The developers went with the arguably less awkward approach of grouping the dimensions from each array separately.

You can always a transpose an array to the shape you want after all.

Title: numpy.dot for dimensions > 2

Body:
I am trying to understand how dot product works for dimensions more than 2.

The documentation says:

If a is an N-D array and b is an M-D array (where M>=2), it is a sum product over the last # axis of a and the second-to-last axis of b:

dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])

I don't understand this rule -- where does it come from? Why is it the last axis of a and the second-to-last axis of b?

Body:
It may be easier to visualize this using the notation of np.einsum. Start with regular 2D matrix multiplication, which is pretty unambiguous, and follows "normal math" rules:

a = np.ones((2, 3))
b = np.ones((3, 4))
np.einsum('ij,jk->ik', a, b)  # Same as a.dot(b)

Now prepend a few dimensions:

a = np.ones((2, 3, 4, 5))
b = np.ones((8, 7, 5, 6))
np.einsum('ijkl,nolp->ijknop', a, b)  # Same as a.dot(b)

In general, a multidimensional array can be thought of as a stack of matrices. There are a number of reasons that numpy generally places the "elements" of an array, whether features, samples, vectors, or matrices along the last dimensions. So, regardless of dot, it is fairly standard to think of a as a 2x3 array of 4x5 matrices. Similarly, b is a 8x7 array of 5x6 matrices.

There are two options going forward. The last two dimensions of the result are unambiguous no matter what choice you make: the output will contain 4x6 matrices. You can compute all the possible combinations of 2x3x8x7 such matrices, or you can expect the leading dimensions to broadcast together. np.dot takes the former approach, while @/np.matmul takes the latter. Anecdotally, I've found that most people will find the latter more intitive.

The exact reason that np.dot computes the matrix product of all possible combinations of a and b is known only to the developers making that choice. It likely revolves around not wanting to raise an error, and the rules of broadcasting not being as universally cemented at the time dot was first implemented. Once you decide to take the products of all the combinations, you can decide to do it like this:

np.einsum('ijkl,nolp->ijnokp', a, b)  # Not `np.dot`

On the one hand, this would reflect the idea of a 2x3x8x7 array of 4x6 matrices better. On the other hand, it creates an awkward permutation of dimensions with k out of place in the sequence. The developers went with the arguably less awkward approach of grouping the dimensions from each array separately.

You can always a transpose an array to the shape you want after all.


问:
how to complement the values of std::vector<bool> using range for loop taking element by reference
I need to complement the values of std::vector<bool>. So I thought of using range for loop taking elements by reference. But the compiler is giving me the below error

```<code>error: cannot bind non-const lvalue reference of type 'std::_Bit_reference&' to an rvalue of type 'std::_Bit_iterator::reference'
   13 |     for (auto& bit : rep)
</code>```

This is my sample code

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

int main() {
    std::vector<bool> rep;
    rep.push_back(true);
    rep.push_back(false);
    rep.push_back(true);
    rep.push_back(false);
    rep.push_back(true);
    rep.push_back(false);

    for (auto& bit : rep)
        bit = !bit;
}
</code>```

答:
you can bind them (the returned proxy object) to rvalue reference

```<code>for (auto&& bit : rep)
   bit = !bit;
</code>```

godbolt

Body:
I need to complement the values of std::vector<bool>. So I thought of using range for loop taking elements by reference. But the compiler is giving me the below error

error: cannot bind non-const lvalue reference of type 'std::_Bit_reference&' to an rvalue of type 'std::_Bit_iterator::reference'
   13 |     for (auto& bit : rep)

This is my sample code

#include <iostream>
#include <vector>

int main() {
    std::vector<bool> rep;
    rep.push_back(true);
    rep.push_back(false);
    rep.push_back(true);
    rep.push_back(false);
    rep.push_back(true);
    rep.push_back(false);

    for (auto& bit : rep)
        bit = !bit;
}

Body:
you can bind them (the returned proxy object) to rvalue reference

for (auto&& bit : rep)
   bit = !bit;

godbolt


问:
CoreData error: +entityForName: could not locate an NSManagedObjectModel for entity name
I've been struggling with CoreData for a few days, but I keep getting this error:

'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name.

I have checked the entity name and what I wrote on my code and they're the same. I also recreated the object data-model and even delete the app from the simulator but nothing seems to fix it.
Here's what I have:

method to save into CoreData:

```<code>-(IBAction)save:(id)sender {
    NSManagedObject * newNews = [NSEntityDescription insertNewObjectForEntityForName:@"NewsStand"
    inManagedObjectContext:coredata.managedObjectContext];
    [newNews setValue:news_title forKey:@"story_title"];
    [newNews setValue:news_desc forKey:@"story_desc"];
    [newNews setValue:news_image  forKey:@"story_image"];
    [newNews setValue:test  forKey:@"story_url"];
    [coredata commit];
    NSLog(@"data saved!!!!");
}
</code>```

I have implemented all methods of core data in a separated class:

```<code>applicationDocumentsDirectory,
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator,
- (NSManagedObjectModel *)managedObjectModel,
- (NSManagedObjectContext *)managedObjectContext
</code>```

答:
This is a fairly common error and it has three causes:

Misspelling the entity name e.g. NewsStand instead of NewsStands.

Having a nil managed object context

Having no or the wrong managed object model loaded.

(1) is the most common but (3) is more common than (2). You can check that you are loading the right model with the keypath:

```<code>aManagedObjectContext.persistentStoreCoordinator.managedObjectModel.entities
</code>```

then check the entity's names.

Body:
I've been struggling with CoreData for a few days, but I keep getting this error:

'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name.

I have checked the entity name and what I wrote on my code and they're the same. I also recreated the object data-model and even delete the app from the simulator but nothing seems to fix it.
Here's what I have:

method to save into CoreData:

-(IBAction)save:(id)sender {
    NSManagedObject * newNews = [NSEntityDescription insertNewObjectForEntityForName:@"NewsStand"
    inManagedObjectContext:coredata.managedObjectContext];
    [newNews setValue:news_title forKey:@"story_title"];
    [newNews setValue:news_desc forKey:@"story_desc"];
    [newNews setValue:news_image  forKey:@"story_image"];
    [newNews setValue:test  forKey:@"story_url"];
    [coredata commit];
    NSLog(@"data saved!!!!");
}

I have implemented all methods of core data in a separated class:

applicationDocumentsDirectory,
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator,
- (NSManagedObjectModel *)managedObjectModel,
- (NSManagedObjectContext *)managedObjectContext

Body:
This is a fairly common error and it has three causes:

Misspelling the entity name e.g. NewsStand instead of NewsStands.

Having a nil managed object context

Having no or the wrong managed object model loaded.

(1) is the most common but (3) is more common than (2). You can check that you are loading the right model with the keypath:

aManagedObjectContext.persistentStoreCoordinator.managedObjectModel.entities

then check the entity's names.


问:
Python List scraping
I have a txt file containing professors', names, ids, where they work, and titles, separated by a comma. I only want to get the names and discard the rest. Is it possible?

for example:

```<code>12717, PROFESÖR, ABDULLAH ERYAVUZ, AFYON KOCATEPE ÜNİVERSİTESİ/VETERİNER FAKÜLTESİ/VETERİNER HEKİMLİĞİ TEMEL BİLİMLERİ BÖLÜMÜ/VETERİNERLİK FİZYOLOJİSİ ANABİLİM DALI/, Sağlık Bilimleri Temel Alanı, Veterinerlik Fizyolojisi, 1E246277D3E01142
106459, PROFESÖR, ABDULLAH KESKİN, AFYON KOCATEPE ÜNİVERSİTESİ/İKTİSADİ VE İDARİ BİLİMLER FAKÜLTESİ/İKTİSAT BÖLÜMÜ/İKTİSAT TEORİSİ ANABİLİM DALI/, Sosyal-Beşeri ve İdari Bilimler Temel Alanı, Makro İktisat, Gelişme Ekonomisi - Makro ; Büyüme ; Para-Banka, akeskin[at]aku.edu.tr, C771324515A1023A
53410, PROFESÖR, ABDURRAHMAN KARABULUT, AFYON KOCATEPE ÜNİVERSİTESİ/TEKNOLOJİ FAKÜLTESİ/MAKİNE MÜHENDİSLİĞİ BÖLÜMÜ/MAKİNE MÜHENDİSLİĞİ ANABİLİM DALI/, Mühendislik Temel Alanı, Makine Mühendisliği, Makine Teorisi ve Dinamiği ; Makine Tasarımı ve Makine Elemanları ; Mekanik Titretişimler ve Gürültü, akarabulut[at]aku.edu.tr, C4DEB0A8828D1E78
57393, PROFESÖR, ABDURRAHMAN FATİH FİDAN, AFYON KOCATEPE ÜNİVERSİTESİ/VETERİNER FAKÜLTESİ/VETERİNER HEKİMLİĞİ TEMEL BİLİMLERİ BÖLÜMÜ/VETERİNERLİK BİYOKİMYASI ANABİLİM DALI/, Sağlık Bilimleri Temel Alanı, Veterinerlik Biyokimyası, ffidan[at]aku.edu.tr, FB9466184DC835D3
</code>```

答:
Yes, you can do something like this:</p>
```<code>with open('test.txt', 'r') as file:
    for item in file:
        print(item.split(',')[2])
</code>```

Title: Python List scraping

Body:
I have a txt file containing professors', names, ids, where they work, and titles, separated by a comma. I only want to get the names and discard the rest. Is it possible?

for example:

12717, PROFESÖR, ABDULLAH ERYAVUZ, AFYON KOCATEPE ÜNİVERSİTESİ/VETERİNER FAKÜLTESİ/VETERİNER HEKİMLİĞİ TEMEL BİLİMLERİ BÖLÜMÜ/VETERİNERLİK FİZYOLOJİSİ ANABİLİM DALI/, Sağlık Bilimleri Temel Alanı, Veterinerlik Fizyolojisi, 1E246277D3E01142
106459, PROFESÖR, ABDULLAH KESKİN, AFYON KOCATEPE ÜNİVERSİTESİ/İKTİSADİ VE İDARİ BİLİMLER FAKÜLTESİ/İKTİSAT BÖLÜMÜ/İKTİSAT TEORİSİ ANABİLİM DALI/, Sosyal-Beşeri ve İdari Bilimler Temel Alanı, Makro İktisat, Gelişme Ekonomisi - Makro ; Büyüme ; Para-Banka, akeskin[at]aku.edu.tr, C771324515A1023A
53410, PROFESÖR, ABDURRAHMAN KARABULUT, AFYON KOCATEPE ÜNİVERSİTESİ/TEKNOLOJİ FAKÜLTESİ/MAKİNE MÜHENDİSLİĞİ BÖLÜMÜ/MAKİNE MÜHENDİSLİĞİ ANABİLİM DALI/, Mühendislik Temel Alanı, Makine Mühendisliği, Makine Teorisi ve Dinamiği ; Makine Tasarımı ve Makine Elemanları ; Mekanik Titretişimler ve Gürültü, akarabulut[at]aku.edu.tr, C4DEB0A8828D1E78
57393, PROFESÖR, ABDURRAHMAN FATİH FİDAN, AFYON KOCATEPE ÜNİVERSİTESİ/VETERİNER FAKÜLTESİ/VETERİNER HEKİMLİĞİ TEMEL BİLİMLERİ BÖLÜMÜ/VETERİNERLİK BİYOKİMYASI ANABİLİM DALI/, Sağlık Bilimleri Temel Alanı, Veterinerlik Biyokimyası, ffidan[at]aku.edu.tr, FB9466184DC835D3

Body:
Yes, you can do something like this:

with open('test.txt', 'r') as file:
    for item in file:
        print(item.split(',')[2])


问:
Get the index of item in list based on value
The scenario is for a football league table. I can order the list by match win percentage and then by goals scored to determine their position in the league. I then use this ordering to get teams position in the league table using the IndexOf function.

```<code>this.results = this.results.OrderByDescending(x => x.WinPercentage).ThenByDescending(x => x.Goals);

this.results.Foreach(x => x.Position = this.results.IndexOf(x));
</code>```

The problem arises when two teams (should be joint #1) have the same match win percentage and goals scored but when getting the index one team will be assigned #1 and the other #2.

Is there a way to get the correct position?

答:
Here's my solution

Define a class：

```<code>public class ABC
{
    public int A { get; set; }
    public int B { get; set; }
    public int R { get; set; }
}
</code>```

Constructing numerical：

```<code>List<ABC> list = new List<ABC>();
for (var i = 0; i < 100; i++)
{
    list.Add(new ABC()
    {
        A = i,
        B = i > 50 && i < 70 ? i + 20 : i + 1
    });
}
</code>```

Ranking and print the values:

```<code>var result = list.OrderByDescending(d => d.B)
            .GroupBy(d => d.B)
            .SelectMany((g, `i`) => g.Select(e => new ABC()
            {
                A = e.A,
                B = e.B,
                R = i + 1
            })).ToList();

foreach (var t in result)
{
   Console.WriteLine(JsonConvert.SerializeObject(t));
}
Console.ReadLine();
</code>```

the result：

Body:
The scenario is for a football league table. I can order the list by match win percentage and then by goals scored to determine their position in the league. I then use this ordering to get teams position in the league table using the IndexOf function.

this.results = this.results.OrderByDescending(x => x.WinPercentage).ThenByDescending(x => x.Goals);

this.results.Foreach(x => x.Position = this.results.IndexOf(x));

The problem arises when two teams (should be joint #1) have the same match win percentage and goals scored but when getting the index one team will be assigned #1 and the other #2.

Is there a way to get the correct position?

Body:
Here's my solution

Define a class：

public class ABC
{
    public int A { get; set; }
    public int B { get; set; }
    public int R { get; set; }
}

Constructing numerical：

List<ABC> list = new List<ABC>();
for (var i = 0; i < 100; i++)
{
    list.Add(new ABC()
    {
        A = i,
        B = i > 50 && i < 70 ? i + 20 : i + 1
    });
}

Ranking and print the values:

var result = list.OrderByDescending(d => d.B)
            .GroupBy(d => d.B)
            .SelectMany((g, `i`) => g.Select(e => new ABC()
            {
                A = e.A,
                B = e.B,
                R = i + 1
            })).ToList();

foreach (var t in result)
{
   Console.WriteLine(JsonConvert.SerializeObject(t));
}
Console.ReadLine();

the result：


问:
Find subset with K elements that are closest to eachother
Given an array of integers size N, how can you efficiently find a subset of size K with elements that are closest to each other?

Let the closeness for a subset (x1,x2,x3,..xk) be defined as:

```<code>2 <= N <= 10^5

2 <= K <= N
</code>```

constraints: Array may contain duplicates and is not guaranteed to be sorted.

My brute force solution is very slow for large N, and it doesn't check if there's more than 1 solution:

```<code>N = input()
K = input()
assert 2 <= N <= 10**5
assert 2 <= K <= N
a = []
for i in xrange(0, N):
    a.append(input())
a.sort()

minimum = sys.maxint
startindex = 0

for i in xrange(0,N-K+1):
    last = i + K
    tmp = 0
    for j in xrange(i, last):
        for l in xrange(j+1, last):
            tmp += abs(a[j]-a[l])
            if(tmp > minimum):
                break

    if(tmp < minimum):
        minimum = tmp
        startindex = i #end index = startindex + K?
</code>```

Examples:

```<code>N = 7
K = 3
array = [10,100,300,200,1000,20,30]
result = [10,20,30]

N = 10
K = 4
array = [1,2,3,4,10,20,30,40,100,200]
result = [1,2,3,4]
</code>```

答:
You can do this is O(n log n) time with a sliding window approach (O(n) if the array is already sorted).

First, suppose we've precomputed, at every index i in our array, the sum of distances from A[i] to the previous k-1 elements. The formula for that would be

(A[i] - A[i-1]) + (A[i] - A[i-2]) + ... + (A[i] - A[i-k+1]).

If i is less than k-1, we just compute the sum to the array boundary.

Suppose we also precompute, at every index i in our array, the sum of distances from A[i] to the next k-1 elements. Then we could solve the whole problem with a single pass of a sliding window.

If our sliding window is on [L, L+k-1] with closeness sum S, then the closeness sum for the interval [L+1, L+k] is just S - dist_sum_to_next[L] + dist_sum_to_prev[L+k]. The only changes in the sum of pairwise distances are removing all terms involving A[L] when it leaves our window, and adding all terms involving A[L+k] as it enters our window.

The only remaining part is how to compute, at a position i, the sum of distances between A[i] and the previous k-1 elements (the other computation is totally symmetric). If we know the distance sum at i-1, this is easy: subtract the distance from A[i-1] to A[i-k], and add in the extra distance from A[i-1] to A[i] k-1 times

dist_sum_to_prev[i] =   (dist_sum_to_prev[i - 1] - (A[i - 1] - A[i - k])
                      + (A[i] - A[i - 1]) * (k - 1)
```
<p>Python code:</p>
<pre class="lang-py prettyprint-override"><code>def closest_subset(nums: List[int], k: int) -> List[int]:
    """Given a list of n (poss. unsorted and non-unique) integers nums,
     returns a (sorted) list of size k that minimizes the sum of pairwise
     distances between all elements in the list.

     Runs in O(n lg n) time, uses O(n) auxiliary space.
    """

    n = len(nums)
    assert len(nums) == n
    assert 2 <= k <= n

    nums.sort()

    # Sum of pairwise distances to the next (at most) k-1 elements
    dist_sum_to_next = [0] * n

    # Sum of pairwise distances to the last (at most) k-1 elements
    dist_sum_to_prev = [0] * n

    for i in range(1, n):
        if i >= k:
            dist_sum_to_prev[i] = ((dist_sum_to_prev[i - 1] -
                                    (nums[i - 1] - nums[i - k]))
                                   + (nums[i] - nums[i - 1]) * (k - 1))
        else:
            dist_sum_to_prev[i] = (dist_sum_to_prev[i - 1]
                                   + (nums[i] - nums[i - 1]) * i)

    for i in reversed(range(n - 1)):
        if i < n - k:
            dist_sum_to_next[i] = ((dist_sum_to_next[i + 1]
                                    - (nums[i + k] - nums[i + 1]))
                                   + (nums[i + 1] - nums[i]) * (k - 1))
        else:
            dist_sum_to_next[i] = (dist_sum_to_next[i + 1]
                                   + (nums[i + 1] - nums[i]) * (n-i-1))

    best_sum = math.inf
    curr_sum = 0
    answer_right_bound = 0

    for i in range(n):
        curr_sum += dist_sum_to_prev[i]
        if i >= k:
            curr_sum -= dist_sum_to_next[i - k]

        if curr_sum < best_sum and i >= k - 1:
            best_sum = curr_sum
            answer_right_bound = i

    return nums[answer_right_bound - k + 1:answer_right_bound + 1]
</code>```

Body:
Given an array of integers size N, how can you efficiently find a subset of size K with elements that are closest to each other?

Let the closeness for a subset (x1,x2,x3,..xk) be defined as:

2 <= N <= 10^5

2 <= K <= N

constraints: Array may contain duplicates and is not guaranteed to be sorted.

My brute force solution is very slow for large N, and it doesn't check if there's more than 1 solution:

N = input()
K = input()
assert 2 <= N <= 10**5
assert 2 <= K <= N
a = []
for i in xrange(0, N):
    a.append(input())
a.sort()

minimum = sys.maxint
startindex = 0

for i in xrange(0,N-K+1):
    last = i + K
    tmp = 0
    for j in xrange(i, last):
        for l in xrange(j+1, last):
            tmp += abs(a[j]-a[l])
            if(tmp > minimum):
                break

    if(tmp < minimum):
        minimum = tmp
        startindex = i #end index = startindex + K?

Examples:

N = 7
K = 3
array = [10,100,300,200,1000,20,30]
result = [10,20,30]

N = 10
K = 4
array = [1,2,3,4,10,20,30,40,100,200]
result = [1,2,3,4]

Body:
You can do this is O(n log n) time with a sliding window approach (O(n) if the array is already sorted).

First, suppose we've precomputed, at every index i in our array, the sum of distances from A[i] to the previous k-1 elements. The formula for that would be

(A[i] - A[i-1]) + (A[i] - A[i-2]) + ... + (A[i] - A[i-k+1]).

If i is less than k-1, we just compute the sum to the array boundary.

Suppose we also precompute, at every index i in our array, the sum of distances from A[i] to the next k-1 elements. Then we could solve the whole problem with a single pass of a sliding window.

If our sliding window is on [L, L+k-1] with closeness sum S, then the closeness sum for the interval [L+1, L+k] is just S - dist_sum_to_next[L] + dist_sum_to_prev[L+k]. The only changes in the sum of pairwise distances are removing all terms involving A[L] when it leaves our window, and adding all terms involving A[L+k] as it enters our window.

The only remaining part is how to compute, at a position i, the sum of distances between A[i] and the previous k-1 elements (the other computation is totally symmetric). If we know the distance sum at i-1, this is easy: subtract the distance from A[i-1] to A[i-k], and add in the extra distance from A[i-1] to A[i] k-1 times

dist_sum_to_prev[i] =   (dist_sum_to_prev[i - 1] - (A[i - 1] - A[i - k])
                      + (A[i] - A[i - 1]) * (k - 1)

Python code:

def closest_subset(nums: List[int], k: int) -> List[int]:
    """Given a list of n (poss. unsorted and non-unique) integers nums,
     returns a (sorted) list of size k that minimizes the sum of pairwise
     distances between all elements in the list.

     Runs in O(n lg n) time, uses O(n) auxiliary space.
    """

    n = len(nums)
    assert len(nums) == n
    assert 2 <= k <= n

    nums.sort()

    # Sum of pairwise distances to the next (at most) k-1 elements
    dist_sum_to_next = [0] * n

    # Sum of pairwise distances to the last (at most) k-1 elements
    dist_sum_to_prev = [0] * n

    for i in range(1, n):
        if i >= k:
            dist_sum_to_prev[i] = ((dist_sum_to_prev[i - 1] -
                                    (nums[i - 1] - nums[i - k]))
                                   + (nums[i] - nums[i - 1]) * (k - 1))
        else:
            dist_sum_to_prev[i] = (dist_sum_to_prev[i - 1]
                                   + (nums[i] - nums[i - 1]) * i)

    for i in reversed(range(n - 1)):
        if i < n - k:
            dist_sum_to_next[i] = ((dist_sum_to_next[i + 1]
                                    - (nums[i + k] - nums[i + 1]))
                                   + (nums[i + 1] - nums[i]) * (k - 1))
        else:
            dist_sum_to_next[i] = (dist_sum_to_next[i + 1]
                                   + (nums[i + 1] - nums[i]) * (n-i-1))

    best_sum = math.inf
    curr_sum = 0
    answer_right_bound = 0

    for i in range(n):
        curr_sum += dist_sum_to_prev[i]
        if i >= k:
            curr_sum -= dist_sum_to_next[i - k]

        if curr_sum < best_sum and i >= k - 1:
            best_sum = curr_sum
            answer_right_bound = i

    return nums[answer_right_bound - k + 1:answer_right_bound + 1]


问:
Selecting dynamic react dropdown in python selenium pytest
Hi i am trying to select a dynamic dropdown built in react while making a python selenium pytest framework. I am facing an issue in first sending keys in the dropdown so options are loaded and then selecting particular option. The dropdown database is very huge as it consists values for certain big organisations, hence 3 words are required so as to load specific values. Also if anyone can let me know how to let driver wait in page object model.</p>

答:
```<code>from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
url=........
ser = Service(seleniumpath)
driver=webdriver.Chrome(service = ser)
driver.get(url)
WebDriverWait(driver, 7).until(lambda x:x.find_element(By.CSS_SELECTOR,'title'))
    #By support XPATH CLASS_NAME CSS_SELECTOR ID........
    #7  within the second time finding the elements
driver.close()
</code>```


问:
Is this popular StackOverflow answer incorrect?
The post I am referring to is this. Not only does the first one run faster for me (563 MS compared to 630) when increasing the size to 100000000, but also in the past using properties in for loops has caused considerable speed slowdowns.

Once when writing a waveform viewer every frame took 23 milliseconds on average to process. The for loop that looped through the entire picture's pixels was the cause of the slowdown. Instead of storing the picture's width and height before the for loop I accessed it during each iteration. Upon changing it the time to process a single frame went from 23 milliseconds to a mere 3.

Also, I made this sample class:

```<code>class LOL
{
    private int x;

    public LOL(int x)
    {
        this.x = x;
    }

    public int X
    {
        get
        {
            return x;
        }
    }
}
</code>```

I then made a for loop that iterates 500000000 times. One test stored the X in an integer variable before the loop even started and one accessed the X property during each iteration. The former took approximately 1,500 milliseconds and the latter around 8,000.

Three tests and each concludes with the result that storing the limit before-hand being the optimal solution for performance gains. Am I missing something? Currently in my program optimization is required as large pictures are processed and in all performance-critical areas I always store the bounds of the loop before hand for performance gains and these tests seem to confirm that.

答:
Compiled in release mode, the cached length is faster. On debug it is the opposite.

Test method

```<code>public static class Performance
{
    public static void Test(string name, decimal times, bool precompile, Action fn)
    {
        if (precompile)
        {
            fn();
        }

        GC.Collect();
        Thread.Sleep(2000);

        var sw = new Stopwatch();

        sw.Start();

        for (decimal i = 0; i < times; ++i)
        {
            fn();
        }

        sw.Stop();

        Console.WriteLine("[{0,15}: {1,-15}]", name, new DateTime(sw.Elapsed.Ticks).ToString("HH:mm:ss.fff"));
        Debug.WriteLine("[{0,15}: {1,-15}]", name, new DateTime(sw.Elapsed.Ticks).ToString("HH:mm:ss.fff"));
    }
}
</code>```

Test code:

```<code>var testAmount = 100;

int[] a1 = new int[10000000];
int[] a2 = new int[10000000];

Performance.Test
(
    "Direct", testAmount, true,
    () =>
    {
        for (int i = 0; i < a1.Length; ++i)
        {
            a1[i] = i;
        }
    }
);

Performance.Test
(
    "Cache", testAmount, true,
    () =>
    {
        var l = a2.Length;
        for (int i = 0; i < l; ++i)
        {
            a2[i] = i;
        }
    }
);
</code>```

Debug results

```<code>[   Direct: 00:00:06.474   ]
[   Cache:  00:00:06.907   ]
</code>```

Release results

```<code>[   Direct: 00:00:05.382   ]
[   Cache:  00:00:04.714   ]
</code>```

Body:
The post I am referring to is this. Not only does the first one run faster for me (563 MS compared to 630) when increasing the size to 100000000, but also in the past using properties in for loops has caused considerable speed slowdowns.

Once when writing a waveform viewer every frame took 23 milliseconds on average to process. The for loop that looped through the entire picture's pixels was the cause of the slowdown. Instead of storing the picture's width and height before the for loop I accessed it during each iteration. Upon changing it the time to process a single frame went from 23 milliseconds to a mere 3.

Also, I made this sample class:

class LOL
{
    private int x;

    public LOL(int x)
    {
        this.x = x;
    }

    public int X
    {
        get
        {
            return x;
        }
    }
}

I then made a for loop that iterates 500000000 times. One test stored the X in an integer variable before the loop even started and one accessed the X property during each iteration. The former took approximately 1,500 milliseconds and the latter around 8,000.

Three tests and each concludes with the result that storing the limit before-hand being the optimal solution for performance gains. Am I missing something? Currently in my program optimization is required as large pictures are processed and in all performance-critical areas I always store the bounds of the loop before hand for performance gains and these tests seem to confirm that.

Body:
Compiled in release mode, the cached length is faster. On debug it is the opposite.

Test method

public static class Performance
{
    public static void Test(string name, decimal times, bool precompile, Action fn)
    {
        if (precompile)
        {
            fn();
        }

        GC.Collect();
        Thread.Sleep(2000);

        var sw = new Stopwatch();

        sw.Start();

        for (decimal i = 0; i < times; ++i)
        {
            fn();
        }

        sw.Stop();

        Console.WriteLine("[{0,15}: {1,-15}]", name, new DateTime(sw.Elapsed.Ticks).ToString("HH:mm:ss.fff"));
        Debug.WriteLine("[{0,15}: {1,-15}]", name, new DateTime(sw.Elapsed.Ticks).ToString("HH:mm:ss.fff"));
    }
}

Test code:

var testAmount = 100;

int[] a1 = new int[10000000];
int[] a2 = new int[10000000];

Performance.Test
(
    "Direct", testAmount, true,
    () =>
    {
        for (int i = 0; i < a1.Length; ++i)
        {
            a1[i] = i;
        }
    }
);

Performance.Test
(
    "Cache", testAmount, true,
    () =>
    {
        var l = a2.Length;
        for (int i = 0; i < l; ++i)
        {
            a2[i] = i;
        }
    }
);

Debug results

[   Direct: 00:00:06.474   ]
[   Cache:  00:00:06.907   ]

Release results

[   Direct: 00:00:05.382   ]
[   Cache:  00:00:04.714   ]


问:
Github actions: Creating releases for multiple branches in a single workflow
I am new to github actions, I have a good idea on how they work but I am having troubles creating releases for multiple branches. Is it possible to create multiple releases from multiple branches in a single workflow?

I currently having working workflow that generates and deploys releases for my main branch. I now want to create releases for a second branch that is slightly similar but has varying functionality.

My problem and my question is:

How does the github workflow differentiate between the main branch and the other branch to create the releases from the .yml file in the main branch? I know you can use if: github.ref but I am not sure how to go about doing it.

Should I create a seperate .yml in the second branch, with a separate workflow and create different tag?

Should I create another entry in my matrix that only relies on the second branch?

Below is my .yml in my main branch:

```<code>name: "CI/CD"

on:
  push:
    branches: [ main, example ]
  pull_request:
    branches: [ main, example ]

env:
  QT_VERSION: 5.15.2
  BUILD_TYPE: Release
  packageGlob: justAnExample-continuous-*.*

jobs:
  main_build:
    name: ${{ matrix.config.name }}
    runs-on: ${{ matrix.config.os }}
    strategy:
      fail-fast: false
      matrix:
        config:
        - {
           name: "Linux-amd64"
           , os: ubuntu-18.04
           , QT_INST_DIR: /opt
           , install_ninja: "sudo apt-get install -qq ninja-build"
           , install_pkgs: "sudo apt-get -qq install libgstreamer-plugins-base1.0-0"
           , bcInstallPrefix: /usr
           , build_justAnExample: "DESTDIR=./appdir ninja install; find ./appdir; mv default.png ./appdir/usr/share/"
           , rename_package: "mv justAnExample-*.tar.xz justAnExample-continuous-linux-x86_64.tar.xz"
          }
        - {
            name: "Windows-x64", WIN_ARCH: "x64"
            , os: windows-latest
            , QT_INST_DIR: "C:/", QTDIR: "C:/Qt/5.15.2/msvc2019_64", QT_ARCH: win64_msvc2019_64
            , install_ninja: "choco install ninja"
            , bcInstallPrefix: justAnExample-continuous
            , build_justAnExample: "ninja install"
            , rename_package: "mv justAnExample-*.zip justAnExample-continuous-win64.zip && mv justAnExample-*.exe justAnExample-continuous-win64-installer.exe"
          }
        - {
            name: "Windows-x86"
            , os: windows-latest, WIN_ARCH: "amd64_x86"
            , QT_INST_DIR: "C:/", QTDIR: "C:/Qt/5.15.2/msvc2019", QT_ARCH: win32_msvc2019
            , install_ninja: "choco install ninja"
            , bcInstallPrefix: justAnExample-continuous
            , build_justAnExample: "ninja install"
            , rename_package: "ls -R && mv justAnExample-*.zip justAnExample-continuous-win32.zip && mv justAnExample-*.exe justAnExample-continuous-win32-installer.exe"
          }
    steps:
    - uses: actions/checkout@v2

    - name: Env Script (Windows)
      uses: ilammy/msvc-dev-cmd@v1
      if: runner.os == 'Windows'
      with:
        arch: ${{matrix.config.WIN_ARCH}}

    - name: Install Ninja
      run: ${{matrix.config.install_ninja}}

    - name: Install Packages
      if: runner.os == 'Linux'
      run: ${{matrix.config.install_pkgs}}

    - name: Install Qt
      uses: jurplel/install-qt-action@v2.14.0
      with:
       dir: ${{matrix.config.QT_INST_DIR}}
       arch: ${{matrix.config.QT_ARCH}}
       version: ${{env.QT_VERSION}}

    - name: Build justAnExample
      id: main_build
      run: |
        cmake -S. -G Ninja -DCMAKE_INSTALL_PREFIX=${{matrix.config.bcInstallPrefix}} -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}}
        ${{matrix.config.build_justAnExample}}
    - name: CPack
      run: cpack

    - name: Build AppImage (Linux)
      if: runner.os == 'Linux'
      run: |
        wget -c "https://github.com/probonopd/linuxdeployqt/releases/download/continuous/linuxdeployqt-continuous-x86_64.AppImage"
        export VERSION=continuous
        chmod a+x linuxdeployqt*.AppImage
        unset QTDIR; unset QT_PLUGIN_PATH; unset LD_LIBRARY_PATH
        ./linuxdeployqt*.AppImage ./appdir/usr/share/applications/*.desktop -appimage -extra-plugins=iconengines,platformthemes/libqxdgdesktopportal.so

    - name: Prepare Upload
      shell: bash
      run: ${{matrix.config.rename_package}}

    - name: Upload
      uses: actions/upload-artifact@v2
      with:
        path: ${{ github.workspace }}/${{env.packageGlob}}

  release_assets:
    name: Release
    needs: main_Build
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    steps:
    - name: Download Files
      uses: actions/download-artifact@v2

    - name: Move Files
      run: |
        mv artifact/* ${{github.workspace}}
    - name: Deploy Package
      uses: "marvinpinto/action-automatic-releases@latest"
      with:
       repo_token: "${{ secrets.DEPLOYTOKEN }}"
       automatic_release_tag: "continuous-main"
       prerelease: false
       title: "Continuous Build"
       files: ${{env.packageGlob}}

</code>```

答:
I have used tags, and I can tag a commit (in any branch) to be used for the action. Below is a part of my workflow file (yml):

```<code>name: Azure Static Web Apps CI/CD

on:
  push:
    tags:
      - Publish*
</code>```

So, any commit tag starts with 'Publish' will be used for the action (e.g. Publish1).
You can see more details about using tags in: https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions

Body:
I am new to github actions, I have a good idea on how they work but I am having troubles creating releases for multiple branches. Is it possible to create multiple releases from multiple branches in a single workflow?

I currently having working workflow that generates and deploys releases for my main branch. I now want to create releases for a second branch that is slightly similar but has varying functionality.

My problem and my question is:

How does the github workflow differentiate between the main branch and the other branch to create the releases from the .yml file in the main branch? I know you can use if: github.ref but I am not sure how to go about doing it.

Should I create a seperate .yml in the second branch, with a separate workflow and create different tag?

Should I create another entry in my matrix that only relies on the second branch?

Below is my .yml in my main branch:

name: "CI/CD"

on:
  push:
    branches: [ main, example ]
  pull_request:
    branches: [ main, example ]

env:
  QT_VERSION: 5.15.2
  BUILD_TYPE: Release
  packageGlob: justAnExample-continuous-*.*

jobs:
  main_build:
    name: ${{ matrix.config.name }}
    runs-on: ${{ matrix.config.os }}
    strategy:
      fail-fast: false
      matrix:
        config:
        - {
           name: "Linux-amd64"
           , os: ubuntu-18.04
           , QT_INST_DIR: /opt
           , install_ninja: "sudo apt-get install -qq ninja-build"
           , install_pkgs: "sudo apt-get -qq install libgstreamer-plugins-base1.0-0"
           , bcInstallPrefix: /usr
           , build_justAnExample: "DESTDIR=./appdir ninja install; find ./appdir; mv default.png ./appdir/usr/share/"
           , rename_package: "mv justAnExample-*.tar.xz justAnExample-continuous-linux-x86_64.tar.xz"
          }
        - {
            name: "Windows-x64", WIN_ARCH: "x64"
            , os: windows-latest
            , QT_INST_DIR: "C:/", QTDIR: "C:/Qt/5.15.2/msvc2019_64", QT_ARCH: win64_msvc2019_64
            , install_ninja: "choco install ninja"
            , bcInstallPrefix: justAnExample-continuous
            , build_justAnExample: "ninja install"
            , rename_package: "mv justAnExample-*.zip justAnExample-continuous-win64.zip && mv justAnExample-*.exe justAnExample-continuous-win64-installer.exe"
          }
        - {
            name: "Windows-x86"
            , os: windows-latest, WIN_ARCH: "amd64_x86"
            , QT_INST_DIR: "C:/", QTDIR: "C:/Qt/5.15.2/msvc2019", QT_ARCH: win32_msvc2019
            , install_ninja: "choco install ninja"
            , bcInstallPrefix: justAnExample-continuous
            , build_justAnExample: "ninja install"
            , rename_package: "ls -R && mv justAnExample-*.zip justAnExample-continuous-win32.zip && mv justAnExample-*.exe justAnExample-continuous-win32-installer.exe"
          }
    steps:
    - uses: actions/checkout@v2

    - name: Env Script (Windows)
      uses: ilammy/msvc-dev-cmd@v1
      if: runner.os == 'Windows'
      with:
        arch: ${{matrix.config.WIN_ARCH}}

    - name: Install Ninja
      run: ${{matrix.config.install_ninja}}

    - name: Install Packages
      if: runner.os == 'Linux'
      run: ${{matrix.config.install_pkgs}}

    - name: Install Qt
      uses: jurplel/install-qt-action@v2.14.0
      with:
       dir: ${{matrix.config.QT_INST_DIR}}
       arch: ${{matrix.config.QT_ARCH}}
       version: ${{env.QT_VERSION}}

    - name: Build justAnExample
      id: main_build
      run: |
        cmake -S. -G Ninja -DCMAKE_INSTALL_PREFIX=${{matrix.config.bcInstallPrefix}} -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}}
        ${{matrix.config.build_justAnExample}}
    - name: CPack
      run: cpack

    - name: Build AppImage (Linux)
      if: runner.os == 'Linux'
      run: |
        wget -c "https://github.com/probonopd/linuxdeployqt/releases/download/continuous/linuxdeployqt-continuous-x86_64.AppImage"
        export VERSION=continuous
        chmod a+x linuxdeployqt*.AppImage
        unset QTDIR; unset QT_PLUGIN_PATH; unset LD_LIBRARY_PATH
        ./linuxdeployqt*.AppImage ./appdir/usr/share/applications/*.desktop -appimage -extra-plugins=iconengines,platformthemes/libqxdgdesktopportal.so

    - name: Prepare Upload
      shell: bash
      run: ${{matrix.config.rename_package}}

    - name: Upload
      uses: actions/upload-artifact@v2
      with:
        path: ${{ github.workspace }}/${{env.packageGlob}}

  release_assets:
    name: Release
    needs: main_Build
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    steps:
    - name: Download Files
      uses: actions/download-artifact@v2

    - name: Move Files
      run: |
        mv artifact/* ${{github.workspace}}
    - name: Deploy Package
      uses: "marvinpinto/action-automatic-releases@latest"
      with:
       repo_token: "${{ secrets.DEPLOYTOKEN }}"
       automatic_release_tag: "continuous-main"
       prerelease: false
       title: "Continuous Build"
       files: ${{env.packageGlob}}

Body:
I have used tags, and I can tag a commit (in any branch) to be used for the action. Below is a part of my workflow file (yml):

name: Azure Static Web Apps CI/CD

on:
  push:
    tags:
      - Publish*

So, any commit tag starts with 'Publish' will be used for the action (e.g. Publish1).
You can see more details about using tags in: https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions


问:
Find the cumulative average of the list [8,1,4,2,1] using accumulate() and lambda function in python
Hi I am new to python I want to find the cummulative average of the given list using accumulate() and lambda function i have written code till accumulate() but I can't find the cummulative average using lambda function. Can anyone help me with it ?</p>
```<code>enter code here
a= [8,1,4,2,6]
import itertools as it
l=[]
l = it.accumulate(a)
print(list(l))

My output should be like this [4.5,4.33,3.75,4.2]
</code>```

答:
```<code>from  itertools import accumulate
result=accumulate([8,1,4,2,6],lambda x,y:(x+y)/2)
for res in result :
    print(res)
</code>```

Body:
Hi I am new to python I want to find the cummulative average of the given list using accumulate() and lambda function i have written code till accumulate() but I can't find the cummulative average using lambda function. Can anyone help me with it ?

enter code here
a= [8,1,4,2,6]
import itertools as it
l=[]
l = it.accumulate(a)
print(list(l))

My output should be like this [4.5,4.33,3.75,4.2]


问:
How to use sx prop in react to change the color of a navbar?
I am attempting to create a black navbar in react. Here is my code so far:

```<code>import UploadIcon from "@mui/icons-material/Upload";
import CustomButton from "./CustomButton";
import AppBar from '@mui/material/AppBar';
import Toolbar from '@mui/material/Toolbar';
import {createMuiTheme} from '@material-ui/core/styles'

const Header = () => {
    return (
        <AppBar sx = {{color:'black'}}
            position="sticky">
            <Toolbar variant="dense">
                <CustomButton
                    text='Upload' endIcon={<UploadIcon/>}/>
            </Toolbar>
        </AppBar>

    )
}
export default Header;
</code>```

The techniques that I have tried so far to change the color of my appbar have been solutions proposed here: https://smartdevpreneur.com/setting-material-ui-appbar-color-and-styling/#Method_1_Styling_AppBar_With_Classes

All previous threads I've seen in stack overflow about this have also not helped me. How do I change the color of my navbar ?

答:
Styling the toolbar instead of styling the appbar worked. Here is my final code</p>
```<code>import UploadIcon from "@mui/icons-material/Upload";
import CustomButton from "./CustomButton";
import AppBar from '@mui/material/AppBar';
import Toolbar from '@mui/material/Toolbar';
import {createMuiTheme} from '@material-ui/core/styles'

const Header = () => {
    return (
        <AppBar
            position="sticky">
            <Toolbar
                sx = {{background:'black',}}
                variant="dense">
                    <CustomButton
                        text='Upload'
                        endIcon={<UploadIcon/>}/>
            </Toolbar>
        </AppBar>
    )
}
export default Header;
</code>```

Body:
I am attempting to create a black navbar in react. Here is my code so far:

import UploadIcon from "@mui/icons-material/Upload";
import CustomButton from "./CustomButton";
import AppBar from '@mui/material/AppBar';
import Toolbar from '@mui/material/Toolbar';
import {createMuiTheme} from '@material-ui/core/styles'

const Header = () => {
    return (
        <AppBar sx = {{color:'black'}}
            position="sticky">
            <Toolbar variant="dense">
                <CustomButton
                    text='Upload' endIcon={<UploadIcon/>}/>
            </Toolbar>
        </AppBar>

    )
}
export default Header;

The techniques that I have tried so far to change the color of my appbar have been solutions proposed here: https://smartdevpreneur.com/setting-material-ui-appbar-color-and-styling/#Method_1_Styling_AppBar_With_Classes

All previous threads I've seen in stack overflow about this have also not helped me. How do I change the color of my navbar ?

Body:
Styling the toolbar instead of styling the appbar worked. Here is my final code

import UploadIcon from "@mui/icons-material/Upload";
import CustomButton from "./CustomButton";
import AppBar from '@mui/material/AppBar';
import Toolbar from '@mui/material/Toolbar';
import {createMuiTheme} from '@material-ui/core/styles'

const Header = () => {
    return (
        <AppBar
            position="sticky">
            <Toolbar
                sx = {{background:'black',}}
                variant="dense">
                    <CustomButton
                        text='Upload'
                        endIcon={<UploadIcon/>}/>
            </Toolbar>
        </AppBar>
    )
}
export default Header;


问:
Gunicorn: 127.0.0.1 in use
I'm trying to use Django with virtualenv.  I actually got the Django hello world webpage to display with 127.0.0.1:8001.  Later I had to do some minor tweaks and now its giving me this error when I try to launch it again (I ctrl-Z from the previous working gunicorn session so I don't think it is because of that).

```<code>    user myenv # /opt/myenv/bin/gunicorn -c /opt/myenv/gunicorn_config.py myProject.wsgi
2013-11-02 08:26:37 [27880] [INFO] Starting gunicorn 18.0
2013-11-02 08:26:37 [27880] [ERROR] Connection in use: ('127.0.0.1', 8001)
2013-11-02 08:26:37 [27880] [ERROR] Retrying in 1 second.
2013-11-02 08:26:38 [27880] [ERROR] Connection in use: ('127.0.0.1', 8001)
2013-11-02 08:26:38 [27880] [ERROR] Retrying in 1 second.
2013-11-02 08:26:39 [27880] [ERROR] Connection in use: ('127.0.0.1', 8001)
2013-11-02 08:26:39 [27880] [ERROR] Retrying in 1 second.
^C2013-11-02 08:26:40 [27880] [ERROR] Connection in use: ('127.0.0.1', 8001)
2013-11-02 08:26:40 [27880] [ERROR] Retrying in 1 second.
2013-11-02 08:26:41 [27880] [ERROR] Connection in use: ('127.0.0.1', 8001)
2013-11-02 08:26:41 [27880] [ERROR] Retrying in 1 second.
2013-11-02 08:26:42 [27880] [ERROR] Can't connect to ('127.0.0.1', 8001)
user myenv #
</code>```

Other commands I recently used include:

```<code>python manage.py syncdb
python manage.py startapp polls
</code>```

I did 'killall python' to make sure they were not the cause.

gunicorn_config.py:

```<code>command = '/opt/myenv/bin/gunicorn'
pythonpath = '/opt/myenv/myProject
workers = 1
user = 'tim'
</code>```

myProject.wsgi:

```<code>import os

# os.environ["DJANGO_SETTINGS_MODULE"] = "myProject.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myProject.settings")

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
</code>```

答:
The error Connection in use: ... basically means that the port is still in use even though you exited the server. You need to find who is currently using the port and turn them off. This command can help you find who is there:

$ sudo netstat -nlp | grep :80
```
<p>Then you can sudo kill that process:</p>
<pre class="lang-py prettyprint-override"><code>sudo fuser -k 8000/tcp
</code>```

You should be able to restart gunicorn.

Title: Gunicorn: 127.0.0.1 in use

Body:
I'm trying to use Django with virtualenv.  I actually got the Django hello world webpage to display with 127.0.0.1:8001.  Later I had to do some minor tweaks and now its giving me this error when I try to launch it again (I ctrl-Z from the previous working gunicorn session so I don't think it is because of that).

    user myenv # /opt/myenv/bin/gunicorn -c /opt/myenv/gunicorn_config.py myProject.wsgi
2013-11-02 08:26:37 [27880] [INFO] Starting gunicorn 18.0
2013-11-02 08:26:37 [27880] [ERROR] Connection in use: ('127.0.0.1', 8001)
2013-11-02 08:26:37 [27880] [ERROR] Retrying in 1 second.
2013-11-02 08:26:38 [27880] [ERROR] Connection in use: ('127.0.0.1', 8001)
2013-11-02 08:26:38 [27880] [ERROR] Retrying in 1 second.
2013-11-02 08:26:39 [27880] [ERROR] Connection in use: ('127.0.0.1', 8001)
2013-11-02 08:26:39 [27880] [ERROR] Retrying in 1 second.
^C2013-11-02 08:26:40 [27880] [ERROR] Connection in use: ('127.0.0.1', 8001)
2013-11-02 08:26:40 [27880] [ERROR] Retrying in 1 second.
2013-11-02 08:26:41 [27880] [ERROR] Connection in use: ('127.0.0.1', 8001)
2013-11-02 08:26:41 [27880] [ERROR] Retrying in 1 second.
2013-11-02 08:26:42 [27880] [ERROR] Can't connect to ('127.0.0.1', 8001)
user myenv #

Other commands I recently used include:

python manage.py syncdb
python manage.py startapp polls

I did 'killall python' to make sure they were not the cause.

gunicorn_config.py:

command = '/opt/myenv/bin/gunicorn'
pythonpath = '/opt/myenv/myProject
workers = 1
user = 'tim'

myProject.wsgi:

import os

# os.environ["DJANGO_SETTINGS_MODULE"] = "myProject.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myProject.settings")

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

Body:
The error Connection in use: ... basically means that the port is still in use even though you exited the server. You need to find who is currently using the port and turn them off. This command can help you find who is there:

$ sudo netstat -nlp | grep :80

Then you can sudo kill that process:

sudo fuser -k 8000/tcp

You should be able to restart gunicorn.


问:
Questions about while loop and def function
I have a question regarding the loop. When I run the loop, my "count" is equal to two while it seems like it runs through it for three-time (the properties_list located in the shell appears three times). My goal is to make the code for example the first containers meet the criteria of the if-statement, then print "success" and repeat the process, until false in the if-statement. Can you give me some tips on that? Thanks!

```<code>def get_mass(container_list)
    current_mass=0
    current_mass=container_list[-1][1]
    return current_massenter
def detect_container():
    properties_list=[]
    count=0
    total_mass=0
    added_mass=0
    while count<3:
        container=random.randint(1,6)
        current_container=table.dispense_container(container,True)
        print ("current container:", current_container)
        properties_list.append(current_container)
        print("properties_list", properties_list)
        added_mass=get_mass(properties_list)
        total_mass=total_mass+added_mass
        print("added_mass:",added_mass)
        print("total mass:", total_mass)

        if total_mass<90 and properties_list[0][2]==properties_list[-1][2]:
            #load_container(count)
            print("success")
            count=count+1
        else:
            print ("end")
            break
    return count
</code>```

Here is the python shell looks like:

```<code>>>> detect_container()
current container: ('paper', 48.23733148585649, 'Bin04')
properties_list: [('paper', 48.23733148585649, 'Bin04')]
added_mass: 48.23733148585649
total mass: 48.23733148585649
current container: ('plastic', 31.348778344676226, 'Bin04')
properties_list: [('paper', 48.23733148585649, 'Bin04'), ('plastic', 31.348778344676
226, 'Bin04')]
added_mass: 31.348778344676226
total mass: 79.5861098305327
current container: ('paper', 25.449467465258202, 'Bin04')
properties_list: [('paper', 48.23733148585649, 'Bin04'), ('plastic', 31.348778344676
226, 'Bin04'), ('paper', 25.449467465258202, 'Bin04')]
added_mass: 25.449467465258202
total mass: 105.03557729579092
end
2
</code>```

In case you wondering what is table.dispense_container(randint, True) is:

When this function is called, a container is spawned onto the table depending on the value
variable  inputted.  A  valid  value  is  a  number  between  1  and  6  (inclusive)  and  each  value
coincides to a container with distinct properties. 1, 2 & 3 corresponds to plastic, metal, and
paper  containers,  respectively,  that  are  non-contaminated,  and  4,  5  &  6  corresponds  to
plastic, metal, and paper containers, respectively, that are contaminated.
Setting properties to the Boolean True will also return the container material, mass (in grams)
of  the  container,  as  well  as  the  bin  ID  (where  the  container  needs  to  be  dropped  off).  By
default, the function returns no properties.

For example: When I type number 6 in the function --> table.dispense_container(6, True)
The output is: ('paper','59.32860054161556','Bin04')

答:
Make sure that the condition is met, and it will help you to print "success" and repeat the process, until false in the if-statement. Let me know if it doesn't help.</p>
```<code>if total_mass<90 and properties_list[0][2]==properties_list[-1][2]:
</code>```

Body:
I have a question regarding the loop. When I run the loop, my "count" is equal to two while it seems like it runs through it for three-time (the properties_list located in the shell appears three times). My goal is to make the code for example the first containers meet the criteria of the if-statement, then print "success" and repeat the process, until false in the if-statement. Can you give me some tips on that? Thanks!

def get_mass(container_list)
    current_mass=0
    current_mass=container_list[-1][1]
    return current_massenter
def detect_container():
    properties_list=[]
    count=0
    total_mass=0
    added_mass=0
    while count<3:
        container=random.randint(1,6)
        current_container=table.dispense_container(container,True)
        print ("current container:", current_container)
        properties_list.append(current_container)
        print("properties_list", properties_list)
        added_mass=get_mass(properties_list)
        total_mass=total_mass+added_mass
        print("added_mass:",added_mass)
        print("total mass:", total_mass)

        if total_mass<90 and properties_list[0][2]==properties_list[-1][2]:
            #load_container(count)
            print("success")
            count=count+1
        else:
            print ("end")
            break
    return count

Here is the python shell looks like:

>>> detect_container()
current container: ('paper', 48.23733148585649, 'Bin04')
properties_list: [('paper', 48.23733148585649, 'Bin04')]
added_mass: 48.23733148585649
total mass: 48.23733148585649
current container: ('plastic', 31.348778344676226, 'Bin04')
properties_list: [('paper', 48.23733148585649, 'Bin04'), ('plastic', 31.348778344676
226, 'Bin04')]
added_mass: 31.348778344676226
total mass: 79.5861098305327
current container: ('paper', 25.449467465258202, 'Bin04')
properties_list: [('paper', 48.23733148585649, 'Bin04'), ('plastic', 31.348778344676
226, 'Bin04'), ('paper', 25.449467465258202, 'Bin04')]
added_mass: 25.449467465258202
total mass: 105.03557729579092
end
2

In case you wondering what is table.dispense_container(randint, True) is:

When this function is called, a container is spawned onto the table depending on the value
variable  inputted.  A  valid  value  is  a  number  between  1  and  6  (inclusive)  and  each  value
coincides to a container with distinct properties. 1, 2 & 3 corresponds to plastic, metal, and
paper  containers,  respectively,  that  are  non-contaminated,  and  4,  5  &  6  corresponds  to
plastic, metal, and paper containers, respectively, that are contaminated.
Setting properties to the Boolean True will also return the container material, mass (in grams)
of  the  container,  as  well  as  the  bin  ID  (where  the  container  needs  to  be  dropped  off).  By
default, the function returns no properties.

For example: When I type number 6 in the function --> table.dispense_container(6, True)
The output is: ('paper','59.32860054161556','Bin04')

Body:
Make sure that the condition is met, and it will help you to print "success" and repeat the process, until false in the if-statement. Let me know if it doesn't help.

if total_mass<90 and properties_list[0][2]==properties_list[-1][2]:


问:
How to make an arraylist with multiple enums in Java?
I am trying to get an enum ArrayList to be able to accept a different enum.

```<code>enum foo {f,o,o}
enum bar {b,a,r}

ArrayList<Foo> foo = new Arraylist<>();
foo.add(bar.b); // Doesn't work
</code>```

Sorry, if this is a bit weird.

答:
First of all, I'm going to assume that you have a sound reason for building a list that contains multiple types.  (See below for reasons why it may not be a good idea.)

Here's your example ... tidied up a bit

```<code>enum Foo {A, B, C}
enum Bar {D, E, F}

ArrayList<Foo> list = new ArrayList<>();
list.add(Bar.D);    // Doesn't work
</code>```

In simple terms, the reason that that statement doesn't work is that Foo and Bar are distinct types.  A Bar instance is not a Foo instance.

What is the work-around?

One possible workaround is this:

```<code>ArrayList<Enum<?>> list = new ArrayList<>();
list.add(Foo.A);
list.add(Bar.D);
</code>```

This works because all enum classes are subtypes of Enum.

But the downside is that you can put any enum value into the list.

A second workaround is to declare Foo and Bar as implementing some custom interface; e.g.

```<code>interface Thing {}
enum Foo implements Thing {A, B, C}
enum Bar implements Thing {D, E, F}

ArrayList<Thing> list = new ArrayList<>();
list.add(Foo.A);
list.add(Bar.D);
</code>```

A final workaround is to combine Foo and Bar into a single enum.

Note that solutions 2 and 3 are essentially changing the enum types; i.e. changing the problem.  This may not be an option for you.

Unfortunately, there is (currently) no way to declare a "union" type in Java.  For example:

```<code>ArrayList<Foo | Bar> list = new ArrayList<>();  // Doesn't work!!!
</code>```

So why did I say this may not be a good idea?  Well the problem is that when you put instances of multiple types into a collection your code typically has to discriminate the different cases when you perform operations on the collection; e.g.

```<code>ArrayList<Enum<?>> list = new ArrayList<>();
list.add(Foo.A);
list.add(Bar.D);

for (Enum<?> e: list) {
   if (e instanceof Foo) {
       doSomething((Foo) e);
   } else if (e instanceof Bar) {
       doSomethingElse((Bar) e);
   } else {
       throw new SomethingUnexpectedException("...");
   }
}
</code>```

It is better if you use the 2nd workaround, but:

you still need to discriminate and cast if you want to access methods or attributes that are specific to one or other enum, and

the Thing type is not a subtype of Enum so you can't call Enum methods on a value whose (static) type is Thing.

Body:
I am trying to get an enum ArrayList to be able to accept a different enum.

enum foo {f,o,o}
enum bar {b,a,r}

ArrayList<Foo> foo = new Arraylist<>();
foo.add(bar.b); // Doesn't work

Sorry, if this is a bit weird.

Body:
First of all, I'm going to assume that you have a sound reason for building a list that contains multiple types.  (See below for reasons why it may not be a good idea.)

Here's your example ... tidied up a bit

enum Foo {A, B, C}
enum Bar {D, E, F}

ArrayList<Foo> list = new ArrayList<>();
list.add(Bar.D);    // Doesn't work

In simple terms, the reason that that statement doesn't work is that Foo and Bar are distinct types.  A Bar instance is not a Foo instance.

What is the work-around?

One possible workaround is this:

ArrayList<Enum<?>> list = new ArrayList<>();
list.add(Foo.A);
list.add(Bar.D);

This works because all enum classes are subtypes of Enum.

But the downside is that you can put any enum value into the list.

A second workaround is to declare Foo and Bar as implementing some custom interface; e.g.

interface Thing {}
enum Foo implements Thing {A, B, C}
enum Bar implements Thing {D, E, F}

ArrayList<Thing> list = new ArrayList<>();
list.add(Foo.A);
list.add(Bar.D);

A final workaround is to combine Foo and Bar into a single enum.

Note that solutions 2 and 3 are essentially changing the enum types; i.e. changing the problem.  This may not be an option for you.

Unfortunately, there is (currently) no way to declare a "union" type in Java.  For example:

ArrayList<Foo | Bar> list = new ArrayList<>();  // Doesn't work!!!

So why did I say this may not be a good idea?  Well the problem is that when you put instances of multiple types into a collection your code typically has to discriminate the different cases when you perform operations on the collection; e.g.

ArrayList<Enum<?>> list = new ArrayList<>();
list.add(Foo.A);
list.add(Bar.D);

for (Enum<?> e: list) {
   if (e instanceof Foo) {
       doSomething((Foo) e);
   } else if (e instanceof Bar) {
       doSomethingElse((Bar) e);
   } else {
       throw new SomethingUnexpectedException("...");
   }
}

It is better if you use the 2nd workaround, but:

you still need to discriminate and cast if you want to access methods or attributes that are specific to one or other enum, and

the Thing type is not a subtype of Enum so you can't call Enum methods on a value whose (static) type is Thing.


答:
First try to understand the case where both arrays are 2d.

```<code>"the last axis of a and the second-to-last axis of b"
</code>```

How where you taught to do the matrix product by-hand?  I remember tracing my finger across the columns of one array (the last dimension) and down the the rows of the other (first, or 2nd to the last for 2d).

I like the equivalent einsum notation, np.einsum('ij,jk->ik',a,b).  Note where the j is.

Most articles about matrix multiplication will illustrate this across/down calculation, e.g. https://en.wikipedia.org/wiki/Matrix_multiplication#Illustration

Once we understand the handling of the last 2 dimension, we can address the initial ones. Note that linear-algebra does not define matrix product for "3d" arrays. MATLAB doesn't either.  But numpy has extended it to handle the larger number of dimensions.

np.dot has been defined to effectively do an 'outer' product on the non-shared dimensions.

```<code>dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
np.einsum('ijo,kom->ijkm', a, b)
</code>```

o is the sum-of-products dimension, last of a, 2nd to the last of b.  The other dimensions are joined in order, ij from a, km from b.  Reducing that to 2d

```<code>np.einsum('jo,om->jm', a, b)
</code>```

That hasn't been too useful, so more recent versions implement np.matmul/@ which treats the leading dimensions (before the last 2) as batch dimensions, with the added rule that they obey numpy's broadcasting rules.

```<code>a@b   # for 3d arrays, with common leading dimension
np.einsum('ijo,iom->ikm', a, b)     # i is repeated
</code>```

Both np.dot and matmul have special cases to handle 1d arrays - they are important, but I won't go into those now.

Title: numpy.dot for dimensions > 2

Body:
I am trying to understand how dot product works for dimensions more than 2.

The documentation says:

If a is an N-D array and b is an M-D array (where M>=2), it is a sum product over the last # axis of a and the second-to-last axis of b:

dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])

I don't understand this rule -- where does it come from? Why is it the last axis of a and the second-to-last axis of b?

Body:
First try to understand the case where both arrays are 2d.

"the last axis of a and the second-to-last axis of b"

How where you taught to do the matrix product by-hand?  I remember tracing my finger across the columns of one array (the last dimension) and down the the rows of the other (first, or 2nd to the last for 2d).

I like the equivalent einsum notation, np.einsum('ij,jk->ik',a,b).  Note where the j is.

Most articles about matrix multiplication will illustrate this across/down calculation, e.g. https://en.wikipedia.org/wiki/Matrix_multiplication#Illustration

Once we understand the handling of the last 2 dimension, we can address the initial ones. Note that linear-algebra does not define matrix product for "3d" arrays. MATLAB doesn't either.  But numpy has extended it to handle the larger number of dimensions.

np.dot has been defined to effectively do an 'outer' product on the non-shared dimensions.

dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
np.einsum('ijo,kom->ijkm', a, b)

o is the sum-of-products dimension, last of a, 2nd to the last of b.  The other dimensions are joined in order, ij from a, km from b.  Reducing that to 2d

np.einsum('jo,om->jm', a, b)

That hasn't been too useful, so more recent versions implement np.matmul/@ which treats the leading dimensions (before the last 2) as batch dimensions, with the added rule that they obey numpy's broadcasting rules.

a@b   # for 3d arrays, with common leading dimension
np.einsum('ijo,iom->ikm', a, b)     # i is repeated

Both np.dot and matmul have special cases to handle 1d arrays - they are important, but I won't go into those now.