问:
How to assert $next in Laravel Middleware
Lavarvel application running 7.10

I have a middleware that gets called on several routes.  It check the user has the right relationships in place to get to the desired destination (that's not important).

I want a test that simply asserts that the user gets to the $next($request) in the middleware.  I could of course just hit one of the end points, and assert something about that which would in turn validate the middleware, but all the routes hit external apis to get some other data which I could mock in my tests, which all seem pretty ugly just to test a middleware class.

I my test I can factory up the relevant relations etc, so whenever the middleware is called it should allow me straight in.

If I do this...

```<code>/** @test */
public function middleware_successful_test()
{
    $user = factory(User::class)->create();
    // some other factoried user relations here

    $this->actingAs($user);

    $request = new Request;

    $middleware = app(MiddlewareClass::class);

    $result = $middleware->handle($request, function ($req) {});
    // don't know what assert here.  $result is basically empty
}
</code>```

Any tips, advise welcome.

答:
Normally i would not unit test middlewares, but test it as a feature.

For your case i would utilize that you provide the next closure and you get the result. Return true and assert it is what is returned and therefor the closure has been called.

```<code>$result = $middleware->handle($request, function ($req) { return true;});

$this->assertSame(true, $result);
</code>```

Body:
Lavarvel application running 7.10

I have a middleware that gets called on several routes.  It check the user has the right relationships in place to get to the desired destination (that's not important).

I want a test that simply asserts that the user gets to the $next($request) in the middleware.  I could of course just hit one of the end points, and assert something about that which would in turn validate the middleware, but all the routes hit external apis to get some other data which I could mock in my tests, which all seem pretty ugly just to test a middleware class.

I my test I can factory up the relevant relations etc, so whenever the middleware is called it should allow me straight in.

If I do this...

/** @test */
public function middleware_successful_test()
{
    $user = factory(User::class)->create();
    // some other factoried user relations here

    $this->actingAs($user);

    $request = new Request;

    $middleware = app(MiddlewareClass::class);

    $result = $middleware->handle($request, function ($req) {});
    // don't know what assert here.  $result is basically empty
}

Any tips, advise welcome.

Body:
Normally i would not unit test middlewares, but test it as a feature.

For your case i would utilize that you provide the next closure and you get the result. Return true and assert it is what is returned and therefor the closure has been called.

$result = $middleware->handle($request, function ($req) { return true;});

$this->assertSame(true, $result);


来源: stackexchange

问:
percentage of download in ( SWIFT )
I want to get percentage of download in label. I use this code

```<code>self.percentageLabel.text = "\(Int(percentage * 100))%"
</code>```

But the problem is the number showing like this ( -90043% )

Any idea ?

This my full code

```<code>import UIKit

class ViewController: UIViewController, URLSessionDownloadDelegate {

    let shapeLayer = CAShapeLayer()

    let percentageLabel: UILabel = {

        let label = UILabel()
        label.text = ""
        label.textAlignment = .center
        label.font = UIFont.boldSystemFont(ofSize: 32)
        return label
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

        view.addSubview(percentageLabel)
        percentageLabel.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
        percentageLabel.center = view.center

        let trackLayer = CAShapeLayer()
        let circularPath = UIBezierPath(arcCenter: .zero, radius: 100, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: true)

        trackLayer.path = circularPath.cgPath
        trackLayer.strokeColor = UIColor.white.cgColor
        trackLayer.lineWidth = 0.2
        trackLayer.fillColor = UIColor.clear.cgColor
        trackLayer.lineCap = CAShapeLayerLineCap.round
        trackLayer.position = view.center

        view.layer.addSublayer(trackLayer)

        shapeLayer.path = circularPath.cgPath
        shapeLayer.strokeColor = UIColor.yellow.cgColor
        shapeLayer.lineWidth = 10
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.lineCap = CAShapeLayerLineCap.round
        shapeLayer.position = view.center

        shapeLayer.transform = CATransform3DMakeRotation(-CGFloat.pi/2, 0, 0, 1)

        shapeLayer.strokeEnd = 0

        view.layer.addSublayer(shapeLayer)

        view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap)))
    }

    let urlString = UIPasteboard.general

    private func beginDownloadingFile()
    {
        print("Downloading Started ... ")
        self.shapeLayer.strokeEnd = 0
        let configuration = URLSessionConfiguration.default
        let operationQueue = OperationQueue()
        let urlSession = URLSession(configuration: configuration, delegate: self, delegateQueue: operationQueue)
        if let urlString = urlString.string {
            print(urlString)
            guard let url = URL(string: urlString) else {
                      print("URL Not valid")
                      return

                  }

            let downloadTask = urlSession.downloadTask(with: url)
                  downloadTask.resume()
        }

         }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        print("Finshed Downloading Files")
    }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        print("TotalBytes:- ", totalBytesWritten, "and toBytesWrittenExpected:- ", totalBytesExpectedToWrite)

        let percentage = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
        print("percentage : ", percentage)

        DispatchQueue.main.async {
            self.shapeLayer.strokeEnd = CGFloat(percentage)
            self.percentageLabel.text = "\(Int(percentage * 100))%"
            self.percentageLabel.font = UIFont.boldSystemFont(ofSize: 20)
            self.percentageLabel.textColor = UIColor.white

        }

        print("Percentage Downloaded:- ", percentage)

    }

    fileprivate func animateCircle() {
        let basicAnimation = CABasicAnimation(keyPath: "strokeEnd")

        basicAnimation.toValue = 1

        basicAnimation.duration = 2

        basicAnimation.fillMode = CAMediaTimingFillMode.forwards
        basicAnimation.isRemovedOnCompletion = false

        shapeLayer.add(basicAnimation, forKey: "urSoBasic")
    }

    @objc private func handleTap(){
        print("Do Animation")

        beginDownloadingFile()

    }

}
</code>```

答:
Your code looks correct. So the problem is with the values of totalBytesWritten andtotalBytesExpectedToWrite.

If totalBytesWritten = 9453 and totalBytesExpectedToWrite = -1 then you can't calculate the percentage.

Basically you have to make sure the value passed in the totalBytesExpectedToWrite is correct.

From Apple documentation for URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:

The expected length of the file, as provided by the Content-Length
  header. If this header was not provided, the value is
  NSURLSessionTransferSizeUnknown (-1).

As suggested in the comments you can try this explanation to try solve totalBytesExpectedToWrite = -1

ContentLicense: CC BY-SA 4.0

Title: percentage of download in ( SWIFT )

Body:
I want to get percentage of download in label. I use this code

self.percentageLabel.text = "\(Int(percentage * 100))%"

But the problem is the number showing like this ( -90043% )

Any idea ?

This my full code

import UIKit

class ViewController: UIViewController, URLSessionDownloadDelegate {

    let shapeLayer = CAShapeLayer()

    let percentageLabel: UILabel = {

        let label = UILabel()
        label.text = ""
        label.textAlignment = .center
        label.font = UIFont.boldSystemFont(ofSize: 32)
        return label
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

        view.addSubview(percentageLabel)
        percentageLabel.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
        percentageLabel.center = view.center

        let trackLayer = CAShapeLayer()
        let circularPath = UIBezierPath(arcCenter: .zero, radius: 100, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: true)

        trackLayer.path = circularPath.cgPath
        trackLayer.strokeColor = UIColor.white.cgColor
        trackLayer.lineWidth = 0.2
        trackLayer.fillColor = UIColor.clear.cgColor
        trackLayer.lineCap = CAShapeLayerLineCap.round
        trackLayer.position = view.center

        view.layer.addSublayer(trackLayer)

        shapeLayer.path = circularPath.cgPath
        shapeLayer.strokeColor = UIColor.yellow.cgColor
        shapeLayer.lineWidth = 10
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.lineCap = CAShapeLayerLineCap.round
        shapeLayer.position = view.center

        shapeLayer.transform = CATransform3DMakeRotation(-CGFloat.pi/2, 0, 0, 1)

        shapeLayer.strokeEnd = 0

        view.layer.addSublayer(shapeLayer)

        view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap)))
    }

    let urlString = UIPasteboard.general

    private func beginDownloadingFile()
    {
        print("Downloading Started ... ")
        self.shapeLayer.strokeEnd = 0
        let configuration = URLSessionConfiguration.default
        let operationQueue = OperationQueue()
        let urlSession = URLSession(configuration: configuration, delegate: self, delegateQueue: operationQueue)
        if let urlString = urlString.string {
            print(urlString)
            guard let url = URL(string: urlString) else {
                      print("URL Not valid")
                      return

                  }

            let downloadTask = urlSession.downloadTask(with: url)
                  downloadTask.resume()
        }

         }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        print("Finshed Downloading Files")
    }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        print("TotalBytes:- ", totalBytesWritten, "and toBytesWrittenExpected:- ", totalBytesExpectedToWrite)

        let percentage = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
        print("percentage : ", percentage)

        DispatchQueue.main.async {
            self.shapeLayer.strokeEnd = CGFloat(percentage)
            self.percentageLabel.text = "\(Int(percentage * 100))%"
            self.percentageLabel.font = UIFont.boldSystemFont(ofSize: 20)
            self.percentageLabel.textColor = UIColor.white

        }

        print("Percentage Downloaded:- ", percentage)

    }

    fileprivate func animateCircle() {
        let basicAnimation = CABasicAnimation(keyPath: "strokeEnd")

        basicAnimation.toValue = 1

        basicAnimation.duration = 2

        basicAnimation.fillMode = CAMediaTimingFillMode.forwards
        basicAnimation.isRemovedOnCompletion = false

        shapeLayer.add(basicAnimation, forKey: "urSoBasic")
    }

    @objc private func handleTap(){
        print("Do Animation")

        beginDownloadingFile()

    }

}


问:
Env. Variables not set while running Minimal Flask application
I am trying to follow the flask documentation on my windows machine given at the following link:
http://flask.pocoo.org/docs/0.11/quickstart/#debug-mode

Firstly I wrote the code below in a python script:

```<code>from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run(debug=True)
</code>```

I saved this in a file called run.py

Then wrote this command in the command window:

```<code>set FLASK_APP = run.py
flask run
</code>```

Upon running this, I am getting the following error:

"Error: Could not locate flask application. You did not provide the FLASK_APP environment variable"

I was expecting to get this instead:

```<code>Running on http://127.0.0.1:5000/
</code>```

Can somebody tell me how to fix this?

答:
Here is what worked for me:

Step 1: Open your CMD Command prompt

Step 2: Go on the same directory in which my python file was on.

Step 3: in the CMD command prompt run the command setx FLASK_APP sqlAlchemy.py

Step 4: close terminal

Step 5: In the CMD command prompt run the command python - m flask run

I have an Alienware laptop and am using Windows 10.

Not sure it worked but it was a combination of trial and ever.
Depending on the OS you have the solution will vary it seems.
IT could be an environmental variable issue but again not sure.

-
Here are other possible solutions that didn't work for me but I gathered them up as possibilities.

OPTION 2

set FLASK_APP=sqlalchemy.py

flask run

OPTION 3

set FLASK_APP=app

set FLASK_ENV=development

flask run
Hope this helps.

Body:
I am trying to follow the flask documentation on my windows machine given at the following link:
http://flask.pocoo.org/docs/0.11/quickstart/#debug-mode

Firstly I wrote the code below in a python script:

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run(debug=True)

I saved this in a file called run.py

Then wrote this command in the command window:

set FLASK_APP = run.py
flask run

Upon running this, I am getting the following error:

"Error: Could not locate flask application. You did not provide the FLASK_APP environment variable"

I was expecting to get this instead:

Running on http://127.0.0.1:5000/

Can somebody tell me how to fix this?


问:
How to use laravel as proxy files between systems?
I need you help to find a way to be a 'proxy' between the frontend and a third-party software component using Laravel.

The third-party software it is in my company's network and it generate the files on-demand.
For sample, If i hit against http://mycompany-third-party.com/12/csv, It will read the data from their database and delivery it to download as response (in this case a csv file).

But I can't allow the users reach out the third-party endpoint directly, so I want to use laravel(guzzle) to ask the file to the third-party and then redirectly to the specific client without store it in my local disk.

How can i do something like this using laravel/guzzle or other library?

Here is my best guess:

 $response = Http::withOptions(['stream' => true])->withHeaders([
            'X-Metabase-Session' => $this->token,
       ])->post('http://mycompany-third-party.com/12/csv');

        $headers = $response->headers();

        return response($response->getBody())->withHeaders($headers);
```

答:
Hey Guys I study more and I have found a solution. To to this we need to use the Streamed Downloads.

Here is my answer:

        $response = Http::withOptions(['stream' => true])->withHeaders([
            'X-Metabase-Session' => $this->token,
        ])->post(your-3th-url);

        return response()->streamDownload(function () use ($response) {
            echo $response->getBody()->getContents();
        }, 'fileName.extType');

```

see you.

Body:
Hey Guys I study more and I have found a solution. To to this we need to use the Streamed Downloads.

Here is my answer:

        $response = Http::withOptions(['stream' => true])->withHeaders([
            'X-Metabase-Session' => $this->token,
        ])->post(your-3th-url);

        return response()->streamDownload(function () use ($response) {
            echo $response->getBody()->getContents();
        }, 'fileName.extType');

see you.


问:
php api Unauthorized request json rpc 2.0
I want to access api with my api key that is correct but still geting back error 401 unauthorized.
Api using json rpc 2.0.

This is example request from api docs.

```<code>Request:
{
  "jsonrpc": "2.0",
  "method": "getBoards",
  "params": {
       "clientId": "apikey"
 },
 "id": 1
}
</code>```

And this is my php code.

```<code>$apiKey = 'apikey';
$apiUrl = 'apiUrl';

$data =  array(
        "jsonrpc" => "2.0",
        "method" => "getBoards",
        "params" => array(
            "clientId" => $apiKey
        ),
        "id" => "1"
);

$data_string = json_encode($data);
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);

$response = curl_exec($ch);
curl_close($ch);

print_r($response);
</code>```

答: Okey my client made a mistake and api key was wrong so at least this is the correct way how to use php with protocol jsonrpc 2.0 </p>

Body:
I want to access api with my api key that is correct but still geting back error 401 unauthorized.
Api using json rpc 2.0.

This is example request from api docs.

Request:
{
  "jsonrpc": "2.0",
  "method": "getBoards",
  "params": {
       "clientId": "apikey"
 },
 "id": 1
}

And this is my php code.

$apiKey = 'apikey';
$apiUrl = 'apiUrl';

$data =  array(
        "jsonrpc" => "2.0",
        "method" => "getBoards",
        "params" => array(
            "clientId" => $apiKey
        ),
        "id" => "1"
);

$data_string = json_encode($data);
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);

$response = curl_exec($ch);
curl_close($ch);

print_r($response);


问:
Typing getter of a property in a Typescript union
I have theses Typescript types :

```<code>type A = {
  a: string
}

type B = {
  b: number,
}

type C = number;

type U = A | B | C;
</code>```

I'm trying to write the function that, given a property of one of U types, return the property value or undefined.

In Javascript, it would be something like that:

```<code>function getProp(prop: P) {
  return (thing) => {
    if (typeof thing === 'object' && prop in thing) {
      return thing[prop]
    }

    return undefined;
  }
}
</code>```

Example:

```<code>const u: U = ...;

const a: string | undefined = getProp('a')(u);
</code>```

I've tried this:

```<code>type KeysOfUnion<T> = T extends any ? keyof T : never; // because `keyof U` return `never`

function getProp<P extends KeysOfUnion<U>>(prop: P) {
    return (thing: U): U[P] => { // error: `Type 'P' cannot be used to index type 'U'.`
        if (typeof thing === 'object' && prop in thing) {
          return thing[prop]; // error: Type 'P' cannot be used to index type 'A | B'
        }

        return undefined; // error: Type 'undefined' is not assignable to type 'U[P]'.
    }
}

const a: string | undefined = getProp('a')(u);
</code>```

But this is not valid. I think I have to find an alternative for U[P] if I want to type this strange function properly but I don't see what. Any idea ?

答:
From the caller's side of view, you probably want getProp() to return a function which returns IdxUnion, where IdxUnion is defined like this:

```<code>type IdxUnion<T, K extends PropertyKey> =
  T extends any ? K extends keyof T ? T[K] : undefined : never;
</code>```

This will do the lookup for each member of a union T and return either T[K] or undefined depending on whether or not K is a key of that member of T.  This should fix things from the call side, mostly:

```<code>const a = getProp('a')(u); // string | undefined
</code>```

I say "mostly" because the function implementation doesn't quite do what you're saying it will do given the signature: if u is a number and not an object, you are always returning undefined at runtime, but number has keys such as toFixed, so you'd expect getProp('toFixed')(123) to be a function.  This is mostly not a problem for your particular U, since A and B will give you the undefined that actually comes out, but it's weird.  So be careful:

```<code>const hmm = getProp('toFixed')(123);
// ((fractionDigits?: number | undefined) => string) | undefined
</code>```

Inside the implemementation of getProp(), things are tougher.  The compiler generally has a hard time evaluating the type safety of operations that occur on unspecified generic types, especially conditional types.  Your best bet here is probably to use type assertions to tell the compiler that you know what you're doing:

```<code>if (typeof thing === "object" && prop in thing) {
  return thing[prop as keyof typeof thing]; // assert
}
return undefined as IdxUnion<U, P>; // assert
</code>```

Anyway, hope that helps; good luck!

Playground link to code

Body:
I have theses Typescript types :

type A = {
  a: string
}

type B = {
  b: number,
}

type C = number;

type U = A | B | C;

I'm trying to write the function that, given a property of one of U types, return the property value or undefined.

In Javascript, it would be something like that:

function getProp(prop: P) {
  return (thing) => {
    if (typeof thing === 'object' && prop in thing) {
      return thing[prop]
    }

    return undefined;
  }
}

Example:

const u: U = ...;

const a: string | undefined = getProp('a')(u);

I've tried this:

type KeysOfUnion<T> = T extends any ? keyof T : never; // because `keyof U` return `never`

function getProp<P extends KeysOfUnion>(prop: P) {
    return (thing: U): U[P] => { // error: `Type 'P' cannot be used to index type 'U'.`
        if (typeof thing === 'object' && prop in thing) {
          return thing[prop]; // error: Type 'P' cannot be used to index type 'A | B'
        }

        return undefined; // error: Type 'undefined' is not assignable to type 'U[P]'.
    }
}

const a: string | undefined = getProp('a')(u);

But this is not valid. I think I have to find an alternative for U[P] if I want to type this strange function properly but I don't see what. Any idea ?

Body:
From the caller's side of view, you probably want getProp() to return a function which returns IdxUnion<U, P>, where IdxUnion is defined like this:

type IdxUnion<T, K extends PropertyKey> =
  T extends any ? K extends keyof T ? T[K] : undefined : never;

This will do the lookup for each member of a union T and return either T[K] or undefined depending on whether or not K is a key of that member of T.  This should fix things from the call side, mostly:

const a = getProp('a')(u); // string | undefined

I say "mostly" because the function implementation doesn't quite do what you're saying it will do given the signature: if u is a number and not an object, you are always returning undefined at runtime, but number has keys such as toFixed, so you'd expect getProp('toFixed')(123) to be a function.  This is mostly not a problem for your particular U, since A and B will give you the undefined that actually comes out, but it's weird.  So be careful:

const hmm = getProp('toFixed')(123);
// ((fractionDigits?: number | undefined) => string) | undefined

Inside the implemementation of getProp(), things are tougher.  The compiler generally has a hard time evaluating the type safety of operations that occur on unspecified generic types, especially conditional types.  Your best bet here is probably to use type assertions to tell the compiler that you know what you're doing:

if (typeof thing === "object" && prop in thing) {
  return thing[prop as keyof typeof thing]; // assert
}
return undefined as IdxUnion<U, P>; // assert

Anyway, hope that helps; good luck!

<a href="https://www.typescriptlang.org/play/#code/C4TwDgpgBAglC8UDeAoKUCGAuKBnYATgJYB2A5igL4oqiRQBCCyaUARjiQK4C2bEBADRQqNOtADCzbnwEBuMeGgBVZnAA+jKJokLaSqAGkIIXAHkAZspJEA9iQA8AFQB8zJ1AgAPYBBIATXEwSECgAfigAaxNbCygPTggAN3koAHo09ggAYwwuXGgAA2iQWKhlQqgCCGAuAhIoQpJkgULFegBJfy9rO0cnYUNPHz9AqAAFAltIAlBjEDd4Vg9vXwCgjBDwo2G1sZKyjwinAG1DAF0oHC4AiAtSCH8rqGaUgj0aCxvs4D6oMhqk2mDnGu1GQXm5isNnsDmULhcAAowFMwDhxgBKFjoaq1epQRHAAAWpDIOGUGJwXR6MMcymE40WblQ6HQRDihKUZWJpIQ8EQACJbGwAFY5YACqAAMilUBR0ygpCgPPIWJZrJxNTqDRVZBO8rAmCCBzi4m5JPI5wUGuoGtx2qgN38dweTwwQWpvVh9ImLmtUGo1BQzuyABsMNUoNl7PhHeSFNGSLGMMwAcAgWBEQByDBZjGIrgYuTpTL4YjkGiJ2NEng8VOA1HZ4C2ABiRC8jzziIAjAAmADMRZQGQJiIsBAwPz6ABEiGQiMBcGFOLx+ARtI7bvdmv4sfA3GXSVjNE6XTugA" rel="nofollow noreferrer">Playground link to code


问:
Getting 'unable to build chain to self-signed root for signer "".' when installing into physical device
When I run my app into my iPhone I get this Warning:

```<code>unable to build chain to self-signed root for signer "".
</code>```

My application Installed in iphone but it closed suddenly.

答:
I saw other answers and attempted to delete my intermediate keychains and root certificate. But Apple doesn't allow to remove Root certs unless you're in recovery mode and I didn't want to try that. Likely you don't have to delete anything either as this solution works without it.

I just thought I'd add an image to clarify things. I ran into this issue when I was poking around in my Keychain and accidentally changed the default settings.

Identifying the bad certificate:

From you Keychains select Login

From Category select Certificates

Find any Apple Certificate that has the blue + like

Double click on the certificate. You'll see it look like this

Expand the Trust. You'd see something like this:

If it's messed up then the "When using this certificate" is set to "Always Trust" along with the blue

Fixing the bad certificate:

Just set it to "Use System Defaults" and close it.

You'll get a pop up. Type in your password to update settings.

Close KeyChain. Go back to your project, clean and run. Problem should have gone away.

If that didn't work then go back to Keychain and just double check and see if there are any other Apple certificates that are set to Always Trust and repeat the process.

Explanation

I'm not 100% sure, but I think when you set an Apple certificate to "Always Trust", it can cause app signing problems because it allows the certificate to bypass the standard chain of trust.

In the context of app signing, a chain of trust refers to a series of interconnected certificates that form a secure path from the app's signature to a trusted root certificate.

IIUC only root certificates can be set to 'Always Trust'. But even then it's better to let the system resolve it for you i.e. for all certificate types, you just want it to be set to "Use System Defaults"

Keychain will tell you which ones are Root certificates.

Body:
When I run my app into my iPhone I get this Warning:

unable to build chain to self-signed root for signer "".

My application Installed in iphone but it closed suddenly.


问:
How to parallelise blocking code with asyncio
I know that asyncio features heavily in StackOverflow, but despite the many questions answered here, I still don't understand how to do something as simple as parallelise 2 tasks that execute blocking code.

For example, this works beautifully:

```<code>import asyncio

async def slow_thing():
    await asyncio.sleep(2)

async def try_alpha():
    print("Alpha start")
    await slow_thing()
    print("Alpha stop")
    return "Alpha"

async def try_bravo():
    print("Bravo start")
    await slow_thing()
    print("Bravo stop")
    return "Bravo"

async def main():
    futures = [
        try_alpha(),
        try_bravo(),
    ]
    for response in await asyncio.gather(*futures):
        print(response)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
</code>```

The output is exactly what I'm looking for:

```<code>Alpha start
Bravo start
*2 second wait*
Alpha stop
Bravo stop
Alpha
Bravo
</code>```

However, if I swap out await syncio.sleep(2) with time.sleep(2), the output is as if there's nothing async about my code:

```<code>Alpha start
*2 second wait*
Alpha stop
Bravo start
*2 second wait*
Bravo stop
Alpha
Bravo
</code>```

The thing is, in my real-world example, I don't control that slow code so I can't change it to use coroutines.  In some cases, it's just a bunch of uses of requests.get() and in others I'm using the kodijson library which does a bunch of things I don't have access to.

So I'm left wondering if asyncio is even the right tool here.  Is it possible to use blocking code inside async code when you're trying to parallelise with .gather()?

Also note that I'm (unfortunately) stuck with Python 3.6 on this one.  I'm writing a Mycroft extension, and that's the environment they're stuck on at the moment.

答:
Coroutines can do stuff in "parallel" only when there's stuff to wait on. For example in your code above what makes it work with asyncio.sleep is the fact you can await it on it. And you can await only on specific functions that have been designed for that purpose. That's why the standard time.sleep doesn't work because you can't use the keyword await with it. Same thing for the requests library.

Luckily you can use the wonderful aiohttp library: https://docs.aiohttp.org
that will provide to you exactly what you need to make multiple requests simultaneously.

Body:
I know that asyncio features heavily in StackOverflow, but despite the many questions answered here, I still don't understand how to do something as simple as parallelise 2 tasks that execute blocking code.

For example, this works beautifully:

import asyncio

async def slow_thing():
    await asyncio.sleep(2)

async def try_alpha():
    print("Alpha start")
    await slow_thing()
    print("Alpha stop")
    return "Alpha"

async def try_bravo():
    print("Bravo start")
    await slow_thing()
    print("Bravo stop")
    return "Bravo"

async def main():
    futures = [
        try_alpha(),
        try_bravo(),
    ]
    for response in await asyncio.gather(*futures):
        print(response)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

The output is exactly what I'm looking for:

Alpha start
Bravo start
*2 second wait*
Alpha stop
Bravo stop
Alpha
Bravo

However, if I swap out await syncio.sleep(2) with time.sleep(2), the output is as if there's nothing async about my code:

Alpha start
*2 second wait*
Alpha stop
Bravo start
*2 second wait*
Bravo stop
Alpha
Bravo

The thing is, in my real-world example, I don't control that slow code so I can't change it to use coroutines.  In some cases, it's just a bunch of uses of requests.get() and in others I'm using the kodijson library which does a bunch of things I don't have access to.

So I'm left wondering if asyncio is even the right tool here.  Is it possible to use blocking code inside async code when you're trying to parallelise with .gather()?

Also note that I'm (unfortunately) stuck with Python 3.6 on this one.  I'm writing a Mycroft extension, and that's the environment they're stuck on at the moment.


问:
How do I authenticate using a service account in the Google Cloud Platform REST API
I want to make a REST API call to Google Cloud Platform using a service account key, but I am unable to figure out how to authenticate the call. Normally, I would use the provided client library and pass the key to it, but in this instance the client library does not support this particular endpoint.

This is the rest endpoint I am trying to call:
https://cloud.google.com/datastore/docs/reference/admin/rest/v1/projects/export

I need to make the call from a nodejs application, so this is the corresponding client library:
https://github.com/googleapis/nodejs-datastore

The documentation is heavy on general concepts, but I can't find anything concrete on how to actually make the REST call with the correct credentials.

答:
I discovered that Google has the library google-auth-library for nodejs which handles the required OAuth flow internally. I was able to use that to successfully make the authenticated call.

This is the code:

```<code>const auth = await new GoogleAuth({
    keyFilename: pathToKey,
    scopes: 'https://www.googleapis.com/auth/cloud-platform',
}).getClient()

const result = await auth.request({
    url: `https://datastore.googleapis.com/v1/projects/${projectId}:export`,
    method: 'POST',
    body: JSON.stringify(payload),
})
</code>```

Note, this handled the authentication part. I still have to grant the right privileges to the service account to get the authorization part working.

EDIT

Apparently there is also a googleapis nodejs library that provides a thin wrapper around the whole REST API. I prefer this to making the rest call directly because the library has Typescript typings that check that the payload has the right shape, etc., and I don't have to manually specify URLs. You still need the google-auth-library to handle auth.

```<code>import {google as googleapis} from 'googleapis'

const auth = await new GoogleAuth({
    keyFilename: pathToKey,
    scopes: 'https://www.googleapis.com/auth/cloud-platform',
}).getClient()

const datastore = googleapis.datastore('v1')
await datastore.projects.export({
    auth,
    projectId: theProjectid,
    requestBody: payload,
})
</code>```

Body:
I discovered that Google has the library google-auth-library for nodejs which handles the required OAuth flow internally. I was able to use that to successfully make the authenticated call.

This is the code:

const auth = await new GoogleAuth({
    keyFilename: pathToKey,
    scopes: 'https://www.googleapis.com/auth/cloud-platform',
}).getClient()

const result = await auth.request({
    url: `https://datastore.googleapis.com/v1/projects/${projectId}:export`,
    method: 'POST',
    body: JSON.stringify(payload),
})

Note, this handled the authentication part. I still have to grant the right privileges to the service account to get the authorization part working.

EDIT

Apparently there is also a googleapis nodejs library that provides a thin wrapper around the whole REST API. I prefer this to making the rest call directly because the library has Typescript typings that check that the payload has the right shape, etc., and I don't have to manually specify URLs. You still need the google-auth-library to handle auth.

import {google as googleapis} from 'googleapis'

const auth = await new GoogleAuth({
    keyFilename: pathToKey,
    scopes: 'https://www.googleapis.com/auth/cloud-platform',
}).getClient()

const datastore = googleapis.datastore('v1')
await datastore.projects.export({
    auth,
    projectId: theProjectid,
    requestBody: payload,
})


问:
Simple WPF App Splash Screen "Jumps" at startup
My WPF app shows a PNG image as a splash screen at startup using the standard MS recommended method.  That is, I chose an existing image file and set its build action to "Splash Screen"  I like this because it's simple. No code to write, just a property.

But it's got a problem: It "jumps".

When my app is starting and the splash screen first appears it is large and centered on the screen as I want.  But then, almost immediately, it jumps up to the left and gets smaller.  As if its window goes from being maximized to only taking up part of the screen.

This "jump" happens even before the constructor of my Application object is reached so certainly long before my MainWindow is in mix.   And I'm certainly not resizing anything.

So what could be causing this?  I can't even see that I can set a breakpoint anywhere to detect this.  Is there some property I can set somewhere to prevent this from happening?  Like maybe in my App.xaml?

I should say that this is a Prism 7.2 application using .NET core 3.1, if any of that matters

答:
If you override the:

```<code>protected virtual void OnStartup (System.Windows.StartupEventArgs e);
</code>```

what you probably already do. Then you can control the splash screen a little bit more in there by:

```<code>SplashScreen splashScreen = new SplashScreen(YourImageFileName);
splashScreen.Show(false, true); // Auto-close: NO, On top: YES
</code>```

And then later when you main window is ready to be shown, then:

```<code>splashScreen.Close(FadeTimeout); // FadeTimeout is of type TimeSpan
</code>```

I know you liked the way, where you do not have anything in your code on the splash screen, but this little extra code you can control the splash screen much more. And it is probably what you need

Body:
If you override the:

protected virtual void OnStartup (System.Windows.StartupEventArgs e);

what you probably already do. Then you can control the splash screen a little bit more in there by:

SplashScreen splashScreen = new SplashScreen(YourImageFileName);
splashScreen.Show(false, true); // Auto-close: NO, On top: YES

And then later when you main window is ready to be shown, then:

splashScreen.Close(FadeTimeout); // FadeTimeout is of type TimeSpan

I know you liked the way, where you do not have anything in your code on the splash screen, but this little extra code you can control the splash screen much more. And it is probably what you need


问:
Clang-tidy not finding header file
Note: This is done in RHEL 7.2 with clang 8.0.1.

I'm running the command

```<code>clang-tidy test.C -- -I/path/to/header.h
</code>```

and I get the following error:

```<code>1 error generated.
Error while processing test.C.
test.C:28:10: error: 'header.h' file not found [clang-diagnostic-error]
#include "header.h"
         ^
Found compiler error(s).
</code>```

When I build using g++, it works fine. The above include is the first include statement of the file, and there's some more after it. The file structure is complicated, so it'd be difficult to show where the files are located. I thought the -I argument would find the header, but it doesn't. So, how do I get clang-tidy to find those headers?

答:
Clang tools usually need a compilation database : the compile_commands.json.
It provides information required to build your cpp units (g.e the include directories).

You can generate this file from Make, CMake, etc. by using some external tools.

https://github.com/rizsotto/Bear is one of them.

Title: Clang-tidy not finding header file

Body:
Note: This is done in RHEL 7.2 with clang 8.0.1.

I'm running the command

clang-tidy test.C -- -I/path/to/header.h

and I get the following error:

1 error generated.
Error while processing test.C.
test.C:28:10: error: 'header.h' file not found [clang-diagnostic-error]
#include "header.h"
         ^
Found compiler error(s).

When I build using g++, it works fine. The above include is the first include statement of the file, and there's some more after it. The file structure is complicated, so it'd be difficult to show where the files are located. I thought the -I argument would find the header, but it doesn't. So, how do I get clang-tidy to find those headers?


问:
Maven mysql-connector dependency doesnt work

This is my pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>id</groupId>
    <artifactId>jbdc_project</artifactId>
    <version>1.0-SNAPSHOT</version>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                </configuration>
            </plugin>
        </plugins>

    </build>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.20</version>
        </dependency>
    </dependencies>
</project>
</code>```

I tried to connect to MySQL database:

```<code>public class Main {
    public static void main(String[] args) {
        String url = "jbdc:mysql://localhost:3306/mydb?autoReconnect=true&useSSL=false";
        String user = "root";
        String password = "root";

        try{
            Connection myConn = DriverManager.getConnection(url,user,password);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
</code>```

And i get this error:

java.sql.SQLException: No suitable driver found for jbdc:mysql://localhost:3306/mydb?autoReconnect=true&useSSL=false

Any ideas on how to fix it?

答:
Got it.

There's a typo in your JDBC URL. It should be 'jdbc' instead of 'jbdc'.

```<code>String url = "jdbc:mysql://localhost:3306/mydb?autoReconnect=true&useSSL=false";
</code>```

Body:
This is my pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>id</groupId>
    <artifactId>jbdc_project</artifactId>
    <version>1.0-SNAPSHOT</version>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                </configuration>
            </plugin>
        </plugins>

    </build>

    <dependencies>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.20</version>
        </dependency>
    </dependencies>
</project>

I tried to connect to MySQL database:

public class Main {
    public static void main(String[] args) {
        String url = "jbdc:mysql://localhost:3306/mydb?autoReconnect=true&useSSL=false";
        String user = "root";
        String password = "root";

        try{
            Connection myConn = DriverManager.getConnection(url,user,password);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

And i get this error:

java.sql.SQLException: No suitable driver found for jbdc:mysql://localhost:3306/mydb?autoReconnect=true&useSSL=false

Any ideas on how to fix it?

Body:
Got it.

There's a typo in your JDBC URL. It should be 'jdbc' instead of 'jbdc'.

String url = "jdbc:mysql://localhost:3306/mydb?autoReconnect=true&useSSL=false";


问:
How to get NSDate day, month and year in integer format?
I want to get the day, month and year components of NSDate in integer form i.e. if the date is 1/2/1988 then I should get 1, 2 and 1988 separately as an integer. How can I do this in iOS? I found the similar question but the method descriptionWithCalendarFormat: gives a warning and seems to be deprecated by now.

答:
Yes by the use of NSCalendar, though, i think this will make your work.</p>

```<code>NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Yes by the use of NSCalendar, though, i think this will make your work.

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];


问:
Date Error in Pandas looking to resolve 1970 error
I am using the following code in python to convert an object to date format:
df['MATURITY_DATE'] = pd.to_datetime(df['MATURITY_DATE'])

However, it keeps making the dates turn to 1970. The raw data looks like "20270601".

Any suggestions would be great, the data is coming in from a CSV and the CSV itself has 1M rows of data.

The Item is an object as you can see with df.info
MATURITY_DATE        198485 non-null  object

Thanks,

答:
Does "20270601" is a unix time format?
if yes, use:

```<code>pd.to_datetime(df['MATURITY_DATE'],unit='s')
</code>```

or

```<code>pd.to_datetime(df['MATURITY_DATE'],unit='ns')
</code>```

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html

Body:
Does "20270601" is a unix time format?
if yes, use:

pd.to_datetime(df['MATURITY_DATE'],unit='s')

or

pd.to_datetime(df['MATURITY_DATE'],unit='ns')

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html


问:
how to make a table with unique count and count + percentage information
I am a r beginner. Please pardon me if this question sounds silly.

If I have a data set like this:

df <- data.frame(ID=c(21,17,21,19,22,21,26,22,18, 15),
                sick=c(T,T, F, T,T,F, T,T, T, F),
                recover=c(T,T,T,F,F,T,T,T,F,F))
```

and I want to make a table out of it, something looks like:

Note unique count ID is 7, event count is 10. what should I do in order to make such table? Is it possible to make it with kable so I can format it nicely?

答:
We can reshape into 'long' format with pivot_longer, grouped by 'name' get the sum of 'value' ('EventCount'), and number of distinct elements of 'ID' where the 'value' is TRUE ('PatientCount'), then grouped by those columns, get the 'Total_number_of_all_patients_measured' as the number of 'sick' elements, and number of unique rows

```<code>library(dplyr)
library(tidyr)
x %>%
   mutate(rn = row_number()) %>%
   pivot_longer(cols = -c(rn, ID))%>%
   group_by(name) %>%
   group_by(EventCount = sum(value), PatientCount = n_distinct(ID[value]), .add = TRUE) %>%
   summarise(Total_number_of_all_patients_measured = sum(name == 'sick' & value),
         Total_number_of_all_question_asked = n_distinct(rn))
</code>```

Body:
I am a r beginner. Please pardon me if this question sounds silly.

If I have a data set like this:

df <- data.frame(ID=c(21,17,21,19,22,21,26,22,18, 15),
                sick=c(T,T, F, T,T,F, T,T, T, F),
                recover=c(T,T,T,F,F,T,T,T,F,F))

and I want to make a table out of it, something looks like:

Note unique count ID is 7, event count is 10. what should I do in order to make such table? Is it possible to make it with kable so I can format it nicely?

Body:
We can reshape into 'long' format with pivot_longer, grouped by 'name' get the sum of 'value' ('EventCount'), and number of distinct elements of 'ID' where the 'value' is TRUE ('PatientCount'), then grouped by those columns, get the 'Total_number_of_all_patients_measured' as the number of 'sick' elements, and number of unique rows

library(dplyr)
library(tidyr)
x %>%
   mutate(rn = row_number()) %>%
   pivot_longer(cols = -c(rn, ID))%>%
   group_by(name) %>%
   group_by(EventCount = sum(value), PatientCount = n_distinct(ID[value]), .add = TRUE) %>%
   summarise(Total_number_of_all_patients_measured = sum(name == 'sick' & value),
         Total_number_of_all_question_asked = n_distinct(rn))


问:
Voila for Jupyter raises error: raise NotImplementedError
I am using Python 3.8 and this is the printout of jupyter --version:

```<code>jupyter core     : 4.6.3
jupyter-notebook : 6.0.3
qtconsole        : not installed
ipython          : 7.13.0
ipykernel        : 5.1.4
jupyter client   : 6.0.0
jupyter lab      : 2.0.0
nbconvert        : 5.6.1
ipywidgets       : 7.5.1
nbformat         : 5.0.4
traitlets        : 4.3.3
</code>```

I have literally done nothing but the following (straight from the docs):

```<code>pip install voila
git clone https://github.com/QuantStack/voila
cd voila
voila notebooks/bqplot.ipynb
</code>```

Which prints this:

```<code>Traceback (most recent call last):
  File "c:\program files\python38\lib\runpy.py", line 192, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "c:\program files\python38\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Program Files\Python38\Scripts\voila.exe\__main__.py", line 7, in <module>
  File "c:\program files\python38\lib\site-packages\traitlets\config\application.py", line 664, in launch_instance
    app.start()
  File "c:\program files\python38\lib\site-packages\voila\app.py", line 509, in start
    self.listen()
  File "c:\program files\python38\lib\site-packages\voila\app.py", line 529, in listen
    self.app.listen(port)
  File "c:\program files\python38\lib\site-packages\tornado\web.py", line 2116, in listen
    server.listen(port, address)
  File "c:\program files\python38\lib\site-packages\tornado\tcpserver.py", line 152, in listen
    self.add_sockets(sockets)
  File "c:\program files\python38\lib\site-packages\tornado\tcpserver.py", line 165, in add_sockets
    self._handlers[sock.fileno()] = add_accept_handler(
  File "c:\program files\python38\lib\site-packages\tornado\netutil.py", line 279, in add_accept_handler
    io_loop.add_handler(sock, accept_handler, IOLoop.READ)
  File "c:\program files\python38\lib\site-packages\tornado\platform\asyncio.py", line 100, in add_handler
    self.asyncio_loop.add_reader(fd, self._handle_events, fd, IOLoop.READ)
  File "c:\program files\python38\lib\asyncio\events.py", line 501, in add_reader
    raise NotImplementedError
NotImplementedError
</code>```

I am a total beginner to Jupyter Notebooks/Lab. How can I fix this?

答:
It worked for me now 4 times.
Maybe bcs I use only pip, and some wheels.
And on win10 this may get you into dep. trouble esp geo-wise.  But I still persist and manage.
I think mostly windows users will get this error, as "not implemented"...
and I think the win10 line is still a bit under the radar in this context.
But it should not be so hard to combine win10 and pip.<br>
That's why I gave this solution. </p>

Body:
I am using Python 3.8 and this is the printout of jupyter --version:

jupyter core     : 4.6.3
jupyter-notebook : 6.0.3
qtconsole        : not installed
ipython          : 7.13.0
ipykernel        : 5.1.4
jupyter client   : 6.0.0
jupyter lab      : 2.0.0
nbconvert        : 5.6.1
ipywidgets       : 7.5.1
nbformat         : 5.0.4
traitlets        : 4.3.3

I have literally done nothing but the following (straight from the docs):

pip install voila
git clone https://github.com/QuantStack/voila
cd voila
voila notebooks/bqplot.ipynb

Which prints this:

Traceback (most recent call last):
  File "c:\program files\python38\lib\runpy.py", line 192, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "c:\program files\python38\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Program Files\Python38\Scripts\voila.exe\__main__.py", line 7, in <module>
  File "c:\program files\python38\lib\site-packages\traitlets\config\application.py", line 664, in launch_instance
    app.start()
  File "c:\program files\python38\lib\site-packages\voila\app.py", line 509, in start
    self.listen()
  File "c:\program files\python38\lib\site-packages\voila\app.py", line 529, in listen
    self.app.listen(port)
  File "c:\program files\python38\lib\site-packages\tornado\web.py", line 2116, in listen
    server.listen(port, address)
  File "c:\program files\python38\lib\site-packages\tornado\tcpserver.py", line 152, in listen
    self.add_sockets(sockets)
  File "c:\program files\python38\lib\site-packages\tornado\tcpserver.py", line 165, in add_sockets
    self._handlers[sock.fileno()] = add_accept_handler(
  File "c:\program files\python38\lib\site-packages\tornado\netutil.py", line 279, in add_accept_handler
    io_loop.add_handler(sock, accept_handler, IOLoop.READ)
  File "c:\program files\python38\lib\site-packages\tornado\platform\asyncio.py", line 100, in add_handler
    self.asyncio_loop.add_reader(fd, self._handle_events, fd, IOLoop.READ)
  File "c:\program files\python38\lib\asyncio\events.py", line 501, in add_reader
    raise NotImplementedError
NotImplementedError

I am a total beginner to Jupyter Notebooks/Lab. How can I fix this?

Body:
It worked for me now 4 times.
Maybe bcs I use only pip, and some wheels.
And on win10 this may get you into dep. trouble esp geo-wise.  But I still persist and manage.
I think mostly windows users will get this error, as "not implemented"...
and I think the win10 line is still a bit under the radar in this context.
But it should not be so hard to combine win10 and pip.

That's why I gave this solution.


问:
Adding multiple values to a unique key in dictionary - Python
The following is a sample dataset obtained from the CSV file.

```<code>7493928 O88643  P60953
7493922 O88643  P60954
749392e O88643  P65657
7493923 O88643  P65656
5845930 YPL094C YPR086W
</code>```

I'm trying to create a dictionary in python using the sample1 column as the key and sample2 as it's values. I want some guidance over here to create a dictionary in the following format where it doesn't repeat the keys (sample1) and concatenates multiple values (sample2) to the same key.

```<code>'O88643': ['P60953', 'P60954', 'P65657', 'P65656'], 'YPL094C': ['YPR086W']
</code>```

Any input on this will be a great help.

答:
You will probably want to use a defaultdict. I don't know exactly how you're processing your data, but you would use it something like this:

from collections import defaultdict

samples = defaultdict(list)
for row in csv_rows:
    row_id, sample1, sample2 = row
    samples[sample1].append(sample2)
```

A defaultdict will create a new item if one isn't found when you go to look up a key. So when you encounter the first item (O88643), the samples defaultdict will create a new list for that key. Then you can immediately append the sample2 value to that list.

Body:
The following is a sample dataset obtained from the CSV file.

7493928 O88643  P60953
7493922 O88643  P60954
749392e O88643  P65657
7493923 O88643  P65656
5845930 YPL094C YPR086W

I'm trying to create a dictionary in python using the sample1 column as the key and sample2 as it's values. I want some guidance over here to create a dictionary in the following format where it doesn't repeat the keys (sample1) and concatenates multiple values (sample2) to the same key.

'O88643': ['P60953', 'P60954', 'P65657', 'P65656'], 'YPL094C': ['YPR086W']

Any input on this will be a great help.

Body:
You will probably want to use a defaultdict. I don't know exactly how you're processing your data, but you would use it something like this:

from collections import defaultdict

samples = defaultdict(list)
for row in csv_rows:
    row_id, sample1, sample2 = row
    samples[sample1].append(sample2)

A defaultdict will create a new item if one isn't found when you go to look up a key. So when you encounter the first item (O88643), the samples defaultdict will create a new list for that key. Then you can immediately append the sample2 value to that list.


问:
Changing database table based on one column
I am new to database design, but not to computers and terminology. I need some help in my database design. I am collecting data from a Global Navigation Satellite System (GNSS) receiver and each packet is differing in sizes depending on which constellation it sees (GPS, GALILEO, GLONASS, etc). There are some common fields across them all, but the way I currently have it set up is all the possible fields are columns, and any field that is unrelated to the new packet is just NULL. This is very inefficient, I just don't know how to go about designing a better way. Thoughts? The main point is as it is now, every time I do a query, I either specify all the fields that are relevant to that specific packet type, or I get a bunch of useless data.

I was thinking of one option, where I have all the common fields in one table, and another table for the unique fields for each packet type. Then have a column that tells what type of packet it is, so when I do a SELECT query I can do a JOIN and only get the data that is relevant to said packet.

答:
Thousands of rows of a hundred columns, many of which are NULL?  Sounds fine.

It might help if you provided a CREATE TABLE; there could be tips on datatypes, etc.

It is usually a good idea to "cleanse" data that comes in from external sources.  Especially if, say, two consellations provide the same value in a different format.  In this example, have one column and convert one (or both) from the given format to the table's datatype.  Sometimes that is 'automatic'.  For example, for a FLOAT or DECIMAL(6,3) column, "123.456" and "1.23456e2" look different, but go into FLOAT the same.  (OK, there could be a rounding difference.)  You may choose to use DOUBLE.

NULLs don't cost much.  Perhaps the main concern is your programming effort.

Your title "changing database based on column" -- that is messy; don't do it.


问:
Definining user libraries in Eclipse as part of a project and not a workspace
I saw that in Eclipse I can define User Libraries - to make setting the classpath easier (and probably for other reasons as well).

The problem is, that these libraries are only available in the workspace, and if I want other people using the same project to use them - I need to export my user library and they need to import it.

Is there any functionality like this on the project level? I basically need to have a 'classpath group' - can it be done?

If not, is there an automatic way to auto import the user library to the workspace when importing the project?

I'm using Eclipse 3.6.

答:
The way I have used user libraries is for something like Ant. Define a user library "ant" for all the jars in ANT_HOME/lib. If including this in your Eclipse .classpath and then sharing with other users, they will get a build problem report until they create that "ant" user library themselves. It's useful, but you need to share knowledge on how to create the library. If you're using it for simple cases like above, then instructions for adding the right jars to the library are straightforward.

Another approach I've used is to build classpaths pointing into a folder (or folders) defined as a variable in Eclipse. See File -> New Folder -> Advanced -> Link to folder in the file system -> Variables. This lets you setup (again at workspace level) variable references to one or more folders. You can then build your Eclipse classpath/s with reference to the folder/s.

So say in your development environment, everyone needs to have a directory called "thirdparty" containing all the external jars dependencies (probably in hierarchy within that dir: thirdparty/apache; thirdparty/sun; ...). You define "thirdparty" as a variable pointing to wherever that dir is on your current system, you create a folder in your project/s using the variable. You can then setup (and share) classpath using paths into that folder.

It's similar to User Library and with similar limitations. The limitation is that the other users you share your project with must create variable folder/s as you have. But it's more flexible in that they don't have to add the jars explicitly as they do with a library; rather, your classpath/s in Eclipse point into the folder, as required for each project.

Note that although the folder variable is defined at workspace level, it can be reused in multiple projects, each of which builds their classpaths (.classpath files) with different references into the folder).

This is maybe something easier to show than to describe with words, but I hope it makes sense.


问:
Cannot use import statement outside a module error after export ZIP from CodeSandbox
I've downloaded this Phaser/MatterJS example from Codesandbox (->File ->Export to ZIP).
Running it locally returns this error:

Uncaught SyntaxError: Cannot use import statement outside a module - index.js:1

How to fix this?

What I tried so far:

I've installed all dependencies

Updated to latest NodeJS

Running it with a local server

答:
index.html:

```<code><script type = "module" src = "./js/index.js">
</code>```

You have to tell the browser that this js file is a module, then it will change some things on the backside for you to use this. This article is very helpful for getting started with modules.

Body:
index.html:

<script type = "module" src = "./js/index.js">

You have to tell the browser that this js file is a module, then it will change some things on the backside for you to use this. This article is very helpful for getting started with modules.


问:
Using a piano keyboard as a computer keyboard
I have RSI problems and have tried 30 different computer keyboards which all caused me pain. Playing piano does not cause me pain. I have played piano for around 20 years without any pain issues. I would like to know if there is a way to capture MIDI from a MIDI keyboard and output keyboard strokes. I know nothing at all about MIDI but I would like some guidance on how to convert this signal into a keystroke.</p>

答:
In Java, you can use JMF (Java Media framework) to convert MIDI signals.
Basic of keyboard design is easy to use, that is, the user interface; and place frequently used charcter/symbol handy.

The sample code and API in Java Sound Resources: Examples: Digital Signal Processing (DSP) help to understand how to process the signal.

Some more references:

Processing Audio with Controls

Digital Audio Signal Processing, 2nd Edition


问:
What is the difference between self and not self objects particularly in Tkinter class?
I have this simple code with self.btn1

```<code>from tkinter import Tk, ttk, messagebox
import tkinter as tk

class Main(tk.Frame):
    def __init__(self, root):
        super().__init__(root)
        self.btn1 = ttk.Button(self, text="test")
        self.btn1.pack()

if __name__ == "__main__":
    root = tk.Tk()
    app = Main(root)
    app.pack()
    root.mainloop()
</code>```

and this code without self button

```<code>from tkinter import Tk, ttk, messagebox
import tkinter as tk

class Main(tk.Frame):
    def __init__(self, root):
        super().__init__(root)
        btn1 = ttk.Button(self, text="test")
        btn1.pack()

if __name__ == "__main__":
    root = tk.Tk()
    app = Main(root)
    app.pack()
    root.mainloop()
</code>```

Both of them work similarly, but what's the difference, which one should I use?

答: The difference is that btn1 is a local variable that is only available in the function in which it is used. self.btn1 is an instance variable that is available in every function within the class.

Body:
I have this simple code with self.btn1

from tkinter import Tk, ttk, messagebox
import tkinter as tk

class Main(tk.Frame):
    def __init__(self, root):
        super().__init__(root)
        self.btn1 = ttk.Button(self, text="test")
        self.btn1.pack()

if __name__ == "__main__":
    root = tk.Tk()
    app = Main(root)
    app.pack()
    root.mainloop()

and this code without self button

from tkinter import Tk, ttk, messagebox
import tkinter as tk

class Main(tk.Frame):
    def __init__(self, root):
        super().__init__(root)
        btn1 = ttk.Button(self, text="test")
        btn1.pack()

if __name__ == "__main__":
    root = tk.Tk()
    app = Main(root)
    app.pack()
    root.mainloop()

Both of them work similarly, but what's the difference, which one should I use?


问:
Laravel 5.1 refresh and seed a single table
I'm looking to refresh and seed a single table in Laravel 5.1. Is this even possible?

I have tried the below, but it gives an error (incorrect syntax).

```<code>php artisan migrate:refresh --path=database/migrations/CreateTableTimesheet
</code>```

If I use: php artisan migrate:refresh it just says:

Nothing to migrate

答:
You can do it in two steps:

Refresh your specific table:

```<code>php artisan migrate:refresh --path=database/migrations/00_create_foo_table.php
</code>```

Seed tables set in database/seeds/DatabaseSeeder.php:

```<code>composer dump-autoload
php artisan db:seed
</code>```

=== Extra information ===

You can comment the seeders you don't want to use in DatabaseSeeder.php:

```<code><?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $this->call([
            FooSeeder::class,
            // BarSeeder::class,
            // UserSeeder::class,
        ]);
    }
}
</code>```

In this example, only database/seeds/FooSeeder.php will be passed.

Body:
I'm looking to refresh and seed a single table in Laravel 5.1. Is this even possible?

I have tried the below, but it gives an error (incorrect syntax).

php artisan migrate:refresh --path=database/migrations/CreateTableTimesheet

If I use: php artisan migrate:refresh it just says:

Nothing to migrate

Body:
You can do it in two steps:

Refresh your specific table:

php artisan migrate:refresh --path=database/migrations/00_create_foo_table.php

Seed tables set in database/seeds/DatabaseSeeder.php:

composer dump-autoload
php artisan db:seed

=== Extra information ===

You can comment the seeders you don't want to use in DatabaseSeeder.php:

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $this->call([
            FooSeeder::class,
            // BarSeeder::class,
            // UserSeeder::class,
        ]);
    }
}

In this example, only database/seeds/FooSeeder.php will be passed.


问:
How to know local report path in rdlc report in c#
I want to check which Report is calling in the application.
Means I want to know the local report path of the rdlc.

I am using now:

```<code>reportViewer.LocalReport.ReportPath = reportpath;
</code>```

But I'mm getting Error like:

An Error Occur during Local Report Processing

Body:
I want to check which Report is calling in the application.
Means I want to know the local report path of the rdlc.

I am using now:

reportViewer.LocalReport.ReportPath = reportpath;

But I'mm getting Error like:

An Error Occur during Local Report Processing

Body: reportViewer1.LocalReport.ReportEmbeddedResource = "YourWindowsFormsCSharpProject.ReportsFolder.Report1.rdlc";


答:
Never modify the (length of the) list you are looping over. Instead, use for example a temporary list:

dates = [('12','10','1987'),('13','09','2010'), ('34','02','2002'), ('02','15','2005'),('37','10','2016'),('39','11','2001')]
print(dates)

out = []
for date in dates :
    day = int(date[0])
    month = int(date[1])
    year = int(date[2])

    if day > 31 or month > 12:
        continue
    out.append(date)

dates = out

print(dates)
```

<p>The <code>continue</code> statement jumps back to the first line of the loop, so the unwanted dates will be skipped.</p>

<h3>Better alternative conserning dates</h3>

<p>Commenting on the "date checking" functionality of the program: It might be really hard to determine by your own rules what dates are acceptable and what are not. Consider for example the Feb 29th, which is only valid on every fourth year.</p>

<p>What you could do instead is to use the <code>datetime</code> library to try to parse the strings to datetime objects, and if the parsing fails, you know the date is illegal.</p>

<pre class="lang-py prettyprint-override"><code>import datetime as dt

dates = [('12','10','1987'),('13','09','2010'), ('34','02','2002'), ('02','15','2005'),('37','10','2016'),('39','11','2001')]

def filter_bad_dates(dates):
    out = []
    for date in dates:

        try:
            dt.datetime.strptime('-'.join(date), '%d-%m-%Y')
        except ValueError:
            continue

        out.append(date)

    return out

dates = filter_bad_dates(dates)
print(dates)
</code>```

This try - except pattern is also called "Duck Typing":

If it looks like a date and gets parsed like a proper date, then it is probably a proper date.

Title: Looping through a list of tuples and removing them

Body:
Im having some difficulty understanding why my loop is not deleting invalid dates from a list of date tuples in the format of dd/mm/yyyy . heres what i have so far :

dates = [('12','10','1987'),('13','09','2010'), ('34','02','2002'), ('02','15','2005'),('37','10','2016'),('39','11','2001')]
print(dates)

for date in dates :
    day = int(date[0])
    month = int(date[1])
    year = int(date[2])

    if day > 31 :
        dates.remove(date)

    if month > 12 :
        dates.remove(date)

print(dates)

and heres the result :

[('12', '10', '1987'), ('13', '09', '2010'), ('34', '02', '2002'), ('02', '15', '2005'), ('37', '10', '2016'), ('39', '11', '2001')]

[('12', '10', '1987'), ('13', '09', '2010'), ('02', '15', '2005'), ('39', '11', '2001')]

I'm a total beginner and any help would be much appreciated.

Body:
Never modify the (length of the) list you are looping over. Instead, use for example a temporary list:

dates = [('12','10','1987'),('13','09','2010'), ('34','02','2002'), ('02','15','2005'),('37','10','2016'),('39','11','2001')]
print(dates)

out = []
for date in dates :
    day = int(date[0])
    month = int(date[1])
    year = int(date[2])

    if day > 31 or month > 12:
        continue
    out.append(date)

dates = out

print(dates)

The continue statement jumps back to the first line of the loop, so the unwanted dates will be skipped.

Better alternative conserning dates

Commenting on the "date checking" functionality of the program: It might be really hard to determine by your own rules what dates are acceptable and what are not. Consider for example the Feb 29th, which is only valid on every fourth year.

What you could do instead is to use the datetime library to try to parse the strings to datetime objects, and if the parsing fails, you know the date is illegal.

import datetime as dt

dates = [('12','10','1987'),('13','09','2010'), ('34','02','2002'), ('02','15','2005'),('37','10','2016'),('39','11','2001')]

def filter_bad_dates(dates):
    out = []
    for date in dates:

        try:
            dt.datetime.strptime('-'.join(date), '%d-%m-%Y')
        except ValueError:
            continue

        out.append(date)

    return out

dates = filter_bad_dates(dates)
print(dates)

This try - except pattern is also called "Duck Typing":

If it looks like a date and gets parsed like a proper date, then it is probably a proper date.


问:
Inline CSS with Pandoc
I apologize if a simple way to this programmatically (not by copying/pasting in a browser field and clicking a button to convert) is documented somewhere. In my searches and reading I cannot find it.

I would like to programmatically turn a Markdown and CSS file into what sounds like may be called "inline" CSS.For example:

This Markdown file (file.md)

```<code># Install
Install instructions

## Update
Update instructions
</code>```

This CSS file (style.css)

```<code>h1 {
    font-size: 100px;
}

h2 {
    color: red;
}
</code>```

Becomes this (file.html)

```<code><h1 style="font-size: 100px;"><a id="install"></a>Install</h1>
<p>Install instructions</p>
<h2 style="color: red;"><a id="update"><a>Update</h2>
<p>Update instructions</p>
</code>```

I am transforming the Markdown to HTML with Pandoc

```<code>pandoc -f markdown -t html file.md -o file.html
</code>```

When I use

```<code>pandoc -f markdown -t html file.md -o file.html --css=style.css --self-contained
</code>```

(or --standalone)

It returns

```<code>    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml" lang xml:lang>
    <head>
      <meta charset="utf-8" />
      <meta name="generator" content="pandoc" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
      <title>file</title>
      <style type="text/css">
          code{white-space: pre-wrap;}
          span.smallcaps{font-variant: small-caps;}
          span.underline{text-decoration: underline;}
          div.column{display: inline-block; vertical-align: top; width: 50%;}
      </style>
      <style type="text/css">h1 {font-size: 100px;}h2 {color: red;}</style>
      <!--[if lt IE 9]>
        <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script>
      <![endif]-->
    </head>
    <body>
      <h1><a id="install"></a>Install</h1>
      <p>Install instructions</p>
      <h2><a id="update"><a>Update</h2>
      <p>Update instructions</p>
    </body>
    </html>
</code>```

As mentioned above this is not my goal. I would like the CSS to be strictly "inline":

```<code><h1 style="font-size: 100px;"><a id="install"></a>Install</h1>
</code>```

Is anyone aware of a tool or script already written than can programmatically achieve this? I have searched and come up empty. Ideally I could use Pandoc for this, but I cannot discover a way.

I do not care if the  and

答:
Another solution I happened to come across since posting this question is the Juice npm package, which also provides a CLI.

It provides the ability to place CSS inline, using a style sheet, with a script like this:

juice --css style.css original.html final.html

Title: Inline CSS with Pandoc

Body:
I apologize if a simple way to this programmatically (not by copying/pasting in a browser field and clicking a button to convert) is documented somewhere. In my searches and reading I cannot find it.

I would like to programmatically turn a Markdown and CSS file into what sounds like may be called "inline" CSS.For example:

This Markdown file (file.md)

# Install
Install instructions

## Update
Update instructions

This CSS file (style.css)

h1 {
    font-size: 100px;
}

h2 {
    color: red;
}

Becomes this (file.html)

Install

Install instructions

Update

Update instructions

I am transforming the Markdown to HTML with Pandoc

pandoc -f markdown -t html file.md -o file.html

When I use

pandoc -f markdown -t html file.md -o file.html --css=style.css --self-contained

(or --standalone)

It returns

    <!DOCTYPE html>

      <meta charset="utf-8" />
      <meta name="generator" content="pandoc" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
      <title>file</title>

Install

Install instructions

Update

Update instructions

As mentioned above this is not my goal. I would like the CSS to be strictly "inline":

Install

Is anyone aware of a tool or script already written than can programmatically achieve this? I have searched and come up empty. Ideally I could use Pandoc for this, but I cannot discover a way.

I do not care if the  and


问:
How to fit the end of line labels when using ax.annotate?
I have this chart which I'm quite happy with except that I cannot fit 4 labels at the end of the lines and it does not look good when I am saving it as a pdf.

I have already tried changing figsize to figsize=(9,6), and xy=(0.984,y) in ax.annotate and this is as good as I can get.

what else can I tweak to make the labels on the right more visible?

My code.

```<code>import matplotlib.pyplot as plt
import matplotlib.transforms as mtrans
from matplotlib.ticker import FixedLocator, FormatStrFormatter
#%matplotlib notebook
plt.style.use('seaborn-poster')

fig,ax = plt.subplots(figsize=(8,6), facecolor='w', edgecolor='blue')

my_colors=['orangered','seagreen', 'goldenrod', 'darkviolet',  'sienna']

ax.set_ylim(merged.min().min(), merged.max().max())
ax.set_ylim(-0.7, 31)

ax=merged.plot(y=['Kinver', 'Nomads', 'Plough', 'Alveley Royals', 'Alveley Oaks'],marker='o',figsize=(9,6),legend=None, color=my_colors, ax=ax)

selectcols=merged[['Kinver', 'Nomads', 'Plough', 'Alveley Royals', 'Alveley Oaks']]

for line, name in zip(ax.lines, selectcols.columns):

    y = line.get_ydata()[-1]
    ax.annotate(name, xy=(0.984,y), xytext=(6,0), color=line.get_color(),
                xycoords = ax.get_yaxis_transform(), textcoords="offset points",
                size=14, va="center")

merged.plot(y='Footloose', marker='o', figsize=(9,6), legend=None, color= 'steelblue', ax=ax, alpha=1,
                    transform=mtrans.offset_copy(ax.transData, fig=fig, x=0.0, y=4, units='points'))

y = 12
ax.annotate('Footloose', xy=(0.984,y), xytext=(6,0), color='steelblue',
                xycoords = ax.get_yaxis_transform(), textcoords="offset points",
                size=14, va="center")

merged.plot(y=['Top Pub'], marker='o', figsize=(9,6), legend=None, color= 'darkred', ax=ax, alpha=1,
                    transform=mtrans.offset_copy(ax.transData, fig=fig, x=0.0, y=3*(1), units='points'))
y = 22
ax.annotate('Top Pub', xy=(0.984,y), xytext=(6,0), color='darkred',
                xycoords = ax.get_yaxis_transform(), textcoords="offset points",
                size=14, va="center")

y = 2
merged.plot(y='Gaters', marker='o', figsize=(9,6), legend=None, color= 'springgreen', ax=ax, alpha=1,
                    transform=mtrans.offset_copy(ax.transData, fig=fig, x=0.0, y=-1.8, units='points'))
ax.annotate('Gaters', xy=(0.984,y), xytext=(6,0), color='springgreen',
                xycoords = ax.get_yaxis_transform(), textcoords="offset points",
                size=14, va="center")

ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)

fig.text(0.25, 0.95, "Clubs  of", ha="center", va="bottom", size=17,color="black")
fig.text(0.34, 0.95, "S", ha="center", va="bottom", size=21,color="blue")
fig.text(0.37, 0.95, "V", ha="center", va="bottom", size=21,color="red")
fig.text(0.40, 0.95, "P", ha="center", va="bottom", size=21,color="gold")
fig.text(0.43, 0.95, "L", ha="center", va="bottom", size=21,color="darkgreen")
fig.text(0.59, 0.95,"in years 2014-2019", ha="center", va="bottom", size=17,color="black")

x_axis = ax.axes.get_xaxis()
x_label = x_axis.get_label()
x_label.set_visible(False)
ax.set_ylabel('Points won', color='darkblue',  fontdict={'fontsize': 14, 'fontweight': 'medium'})

years=[2014,2015, 2016,2017,2018, 2019]
plt.xticks(range(len(years)),(years))
plt.margins(x=0.012,y=0.2)

ax.get_xaxis().tick_bottom()
#ax.get_yaxis().tick_left()

ax.tick_params(axis='y', which='major', labelsize=12,bottom=False, top=False, labelbottom=True,
               left=False, right=False, labelright=False)
ax.tick_params(axis='x', which='major', labelsize=14,bottom=False, top=False, labelbottom=True,
               left=False, right=False, labelright=False)
#fig.subplots_adjust(left=.06, right=.75, bottom=0, top=.94)
ax.yaxis.set_major_formatter(plt.FuncFormatter('{:.0f}'.format))
ax.grid(True, 'major', 'y', ls='--', lw=.6, c='darkgray', alpha=.5)

plt.show()

plt.savefig('SVPLclubs1.pdf')
</code>```

Thank you!

答:
fig.subplots_adjust(left=.075, right=.65, bottom=0, top=.94)
helped me!</p>

Body:
I have this chart which I'm quite happy with except that I cannot fit 4 labels at the end of the lines and it does not look good when I am saving it as a pdf.

I have already tried changing figsize to figsize=(9,6), and xy=(0.984,y) in ax.annotate and this is as good as I can get.

what else can I tweak to make the labels on the right more visible?

My code.

import matplotlib.pyplot as plt
import matplotlib.transforms as mtrans
from matplotlib.ticker import FixedLocator, FormatStrFormatter
#%matplotlib notebook
plt.style.use('seaborn-poster')

fig,ax = plt.subplots(figsize=(8,6), facecolor='w', edgecolor='blue')

my_colors=['orangered','seagreen', 'goldenrod', 'darkviolet',  'sienna']

ax.set_ylim(merged.min().min(), merged.max().max())
ax.set_ylim(-0.7, 31)

ax=merged.plot(y=['Kinver', 'Nomads', 'Plough', 'Alveley Royals', 'Alveley Oaks'],marker='o',figsize=(9,6),legend=None, color=my_colors, ax=ax)

selectcols=merged[['Kinver', 'Nomads', 'Plough', 'Alveley Royals', 'Alveley Oaks']]

for line, name in zip(ax.lines, selectcols.columns):

    y = line.get_ydata()[-1]
    ax.annotate(name, xy=(0.984,y), xytext=(6,0), color=line.get_color(),
                xycoords = ax.get_yaxis_transform(), textcoords="offset points",
                size=14, va="center")

merged.plot(y='Footloose', marker='o', figsize=(9,6), legend=None, color= 'steelblue', ax=ax, alpha=1,
                    transform=mtrans.offset_copy(ax.transData, fig=fig, x=0.0, y=4, units='points'))

y = 12
ax.annotate('Footloose', xy=(0.984,y), xytext=(6,0), color='steelblue',
                xycoords = ax.get_yaxis_transform(), textcoords="offset points",
                size=14, va="center")

merged.plot(y=['Top Pub'], marker='o', figsize=(9,6), legend=None, color= 'darkred', ax=ax, alpha=1,
                    transform=mtrans.offset_copy(ax.transData, fig=fig, x=0.0, y=3*(1), units='points'))
y = 22
ax.annotate('Top Pub', xy=(0.984,y), xytext=(6,0), color='darkred',
                xycoords = ax.get_yaxis_transform(), textcoords="offset points",
                size=14, va="center")

y = 2
merged.plot(y='Gaters', marker='o', figsize=(9,6), legend=None, color= 'springgreen', ax=ax, alpha=1,
                    transform=mtrans.offset_copy(ax.transData, fig=fig, x=0.0, y=-1.8, units='points'))
ax.annotate('Gaters', xy=(0.984,y), xytext=(6,0), color='springgreen',
                xycoords = ax.get_yaxis_transform(), textcoords="offset points",
                size=14, va="center")

ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)

fig.text(0.25, 0.95, "Clubs  of", ha="center", va="bottom", size=17,color="black")
fig.text(0.34, 0.95, "S", ha="center", va="bottom", size=21,color="blue")
fig.text(0.37, 0.95, "V", ha="center", va="bottom", size=21,color="red")
fig.text(0.40, 0.95, "P", ha="center", va="bottom", size=21,color="gold")
fig.text(0.43, 0.95, "L", ha="center", va="bottom", size=21,color="darkgreen")
fig.text(0.59, 0.95,"in years 2014-2019", ha="center", va="bottom", size=17,color="black")

x_axis = ax.axes.get_xaxis()
x_label = x_axis.get_label()
x_label.set_visible(False)
ax.set_ylabel('Points won', color='darkblue',  fontdict={'fontsize': 14, 'fontweight': 'medium'})

years=[2014,2015, 2016,2017,2018, 2019]
plt.xticks(range(len(years)),(years))
plt.margins(x=0.012,y=0.2)

ax.get_xaxis().tick_bottom()
#ax.get_yaxis().tick_left()

ax.tick_params(axis='y', which='major', labelsize=12,bottom=False, top=False, labelbottom=True,
               left=False, right=False, labelright=False)
ax.tick_params(axis='x', which='major', labelsize=14,bottom=False, top=False, labelbottom=True,
               left=False, right=False, labelright=False)
#fig.subplots_adjust(left=.06, right=.75, bottom=0, top=.94)
ax.yaxis.set_major_formatter(plt.FuncFormatter('{:.0f}'.format))
ax.grid(True, 'major', 'y', ls='--', lw=.6, c='darkgray', alpha=.5)

plt.show()

plt.savefig('SVPLclubs1.pdf')

Thank you!


问:
we have to free up the memory while deleting a node in a linked list in c but we do not have to do the same in java,Why?
in case of c we have to do free(data) while deleting a node to free up the memory space occupied by the node manually but in case of java we do not have to do the same.Why and what happens??</p>

答: Java is a garbage collected language. This means freeing of these references is taken care of for you by the language itself. There are other forms of leaks, but for cases where the references to this node are no more, the memory is reclaimed on the next garbage collection.</p>


问:
Reversing a MultiLabelBinarizer to create a list within a column
In Python3, I have a starting dataframe in the format of a multilabel binary data:

```<code>df1:

"a" "b" "c" "d" "e"

 1   1   0   0   1
 0   0   1   0   1
 1   0   0   0   0
 0   1   1   0   1
</code>```

What I need to achieve is this:

```<code>df2:

"a" "b" "c" "d" "e" "labels"

 1   1   0   0   1   ["a", "b", "e"]
 0   0   1   0   1   ["c", "e"]
 1   0   0   0   0   ["a"]
 0   1   1   0   1   ["b", "c", "e"]
</code>```

To start, I tried using the inverse_transform() function from MultiLabelBinarizer from sklearn based on this previous stack question.

```<code>from sklearn.preprocessing import MultiLabelBinarizer
mlb = MultiLabelBinarizer()
mlb.fit(df1.columns)
mlb.inverse_transform(df1.values)

ValueError: Expected indicator for 15 classes, but got 5
</code>```

I tried following the exact documentation from sklearn, but I am not sure where I went wrong. I tried tweaking a few of the parameters, but I do not understand what the issue is.

答:
A Numpy approach

```<code>i, j = np.where(df)
a = df.columns.to_numpy()[j]
b = np.flatnonzero(np.diff(i)) + 1
df.assign(labels=np.split(a, b))

   a  b  c  d  e     labels
0  1  1  0  0  1  [a, b, e]
1  0  0  1  0  1     [c, e]
2  1  0  0  0  0        [a]
3  0  1  1  0  1  [b, c, e]
</code>```

Body:
In Python3, I have a starting dataframe in the format of a multilabel binary data:

df1:

"a" "b" "c" "d" "e"

 1   1   0   0   1
 0   0   1   0   1
 1   0   0   0   0
 0   1   1   0   1

What I need to achieve is this:

df2:

"a" "b" "c" "d" "e" "labels"

 1   1   0   0   1   ["a", "b", "e"]
 0   0   1   0   1   ["c", "e"]
 1   0   0   0   0   ["a"]
 0   1   1   0   1   ["b", "c", "e"]

To start, I tried using the inverse_transform() function from MultiLabelBinarizer from sklearn based on this previous stack question.

from sklearn.preprocessing import MultiLabelBinarizer
mlb = MultiLabelBinarizer()
mlb.fit(df1.columns)
mlb.inverse_transform(df1.values)

ValueError: Expected indicator for 15 classes, but got 5

I tried following the exact documentation from sklearn, but I am not sure where I went wrong. I tried tweaking a few of the parameters, but I do not understand what the issue is.

Body:
A Numpy approach

i, j = np.where(df)
a = df.columns.to_numpy()[j]
b = np.flatnonzero(np.diff(i)) + 1
df.assign(labels=np.split(a, b))

   a  b  c  d  e     labels
0  1  1  0  0  1  [a, b, e]
1  0  0  1  0  1     [c, e]
2  1  0  0  0  0        [a]
3  0  1  1  0  1  [b, c, e]


问:
How to hidden Expand after clicking on the content? XAML
Need some help, is anyone know how to make it so that when you click on the contents of Expand - does it hidden?

```<code>        <Expander Header="First Expand">
            <ListBox>
                <ListBox.Items>
                    <CheckBox Content="First"/>
                    <CheckBox Content="Second"/>
                    <CheckBox Content="Third"/>
                </ListBox.Items>
            </ListBox>
        </Expander>
</code>```

Is it possible to use bindings?

答:
Here's an example I wrote using bindings. If you "check" the 3rd checkbox, the Expander closes.  Note that the Expander doesn't close if you uncheck it (this is by my design only, your needs might be different).</p>

```<code>        <Expander x:Name="firstExpand" Header="First Expand" IsExpanded="{Binding IsExpanded}">
            <ListBox>
                <ListBox.Items>
                    <CheckBox x:Name="firstCheckbox" Content="First" IsChecked="{Binding FirstChecked}"/>
                    <CheckBox x:Name="secondCheckbox" Content="Second"  IsChecked="{Binding SecondChecked}"/>
                    <CheckBox x:Name="thirdCheckbox" Content="Third"  IsChecked="{Binding ThirdChecked}"/>
                </ListBox.Items>
            </ListBox>
        </Expander>
</code>```

```<code>    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        private bool firstChecked;
        private bool secondChecked;
        private bool thirdChecked;
        private bool isExpanded;

        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;
            this.PropertyChanged += MainWindow_PropertyChanged;
            this.IsExpanded = true;
        }

        private void MainWindow_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            // If the third item was checked...close the expansion
            if (e.PropertyName == nameof(ThirdChecked) && ThirdChecked)
            {
                this.IsExpanded = false;
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public bool FirstChecked { get => this.firstChecked; set { this.firstChecked = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(FirstChecked))); } }
        public bool SecondChecked { get => this.secondChecked; set { this.secondChecked = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SecondChecked))); } }
        public bool ThirdChecked { get => this.thirdChecked; set { this.thirdChecked = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ThirdChecked))); } }
        public bool IsExpanded { get => this.isExpanded; set { this.isExpanded = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsExpanded))); } }
    }

</code>```

Body:
Need some help, is anyone know how to make it so that when you click on the contents of Expand - does it hidden?

        <Expander Header="First Expand">
            <ListBox>
                <ListBox.Items>
                    <CheckBox Content="First"/>
                    <CheckBox Content="Second"/>
                    <CheckBox Content="Third"/>
                </ListBox.Items>
            </ListBox>
        </Expander>

Is it possible to use bindings?

Body:
Here's an example I wrote using bindings. If you "check" the 3rd checkbox, the Expander closes.  Note that the Expander doesn't close if you uncheck it (this is by my design only, your needs might be different).

        <Expander x:Name="firstExpand" Header="First Expand" IsExpanded="{Binding IsExpanded}">
            <ListBox>
                <ListBox.Items>
                    <CheckBox x:Name="firstCheckbox" Content="First" IsChecked="{Binding FirstChecked}"/>
                    <CheckBox x:Name="secondCheckbox" Content="Second"  IsChecked="{Binding SecondChecked}"/>
                    <CheckBox x:Name="thirdCheckbox" Content="Third"  IsChecked="{Binding ThirdChecked}"/>
                </ListBox.Items>
            </ListBox>
        </Expander>

    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        private bool firstChecked;
        private bool secondChecked;
        private bool thirdChecked;
        private bool isExpanded;

        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;
            this.PropertyChanged += MainWindow_PropertyChanged;
            this.IsExpanded = true;
        }

        private void MainWindow_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            // If the third item was checked...close the expansion
            if (e.PropertyName == nameof(ThirdChecked) && ThirdChecked)
            {
                this.IsExpanded = false;
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public bool FirstChecked { get => this.firstChecked; set { this.firstChecked = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(FirstChecked))); } }
        public bool SecondChecked { get => this.secondChecked; set { this.secondChecked = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SecondChecked))); } }
        public bool ThirdChecked { get => this.thirdChecked; set { this.thirdChecked = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ThirdChecked))); } }
        public bool IsExpanded { get => this.isExpanded; set { this.isExpanded = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsExpanded))); } }
    }


问:
Move Directory to Google Bucket
How can we move entire folder(within folder have many sub directory too) to Bucket of google cloud? Can anyone help on this.</p>

答:
The Cloud Storage Client for C # library does not support uploading folders, you must create a function (sync / asynchronous) that gets all the files/subfolders inside your folder and uploads each file.

I found a folder iterator code in this Microsoft Link In my code example I added the GCS library to upload the files, it is not necessary to create a folder structure.

For example

```<code>// GCS dependencies
using Google.Apis.Storage.v1;
using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using Storage;
// GCS dependencies

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;

static void WalkDirectoryTree(System.IO.DirectoryInfo root)
   {
       System.IO.FileInfo[] files = null;
       System.IO.DirectoryInfo[] subDirs = null;

       // initialize the GCS client library
       var storage = StorageClient.Create();
       // use this variable to define the upload bucket, please use your bucket name
       var bucketName= Myawesomebucket
       try
       {
           files = root.GetFiles("*.*");
       }

       catch (UnauthorizedAccessException e)
       {

       }

       catch (System.IO.DirectoryNotFoundException e)
       {
           Console.WriteLine(e.Message);
       }

       if (files != null)
       {
           foreach (System.IO.FileInfo fi in files)
           {
               // If we
               // want to open, delete or modify the file, then
               // a try-catch block is required here to handle the case
               // where the file has been deleted since the call to TraverseTree().
               Console.WriteLine(fi.FullName);

               // this section is used to upload files to GCS
               // the object name includ folder/subfolder structure
               objectName = objectName ?? Path.GetFileName(fi.FullPath);

               // upload the object to the bucket
               storage.UploadObject(bucketName, objectName, null, f);
               Console.WriteLine($"Uploaded {objectName}.");

           }

           // Now find all the subdirectories under this directory.
           subDirs = root.GetDirectories();

           foreach (System.IO.DirectoryInfo dirInfo in subDirs)
           {
               // Resursive call for each subdirectory.
               WalkDirectoryTree(dirInfo);
           }
       }
   }
</code>```

Title: Move Directory to Google Bucket

Body:
The Cloud Storage Client for C # library does not support uploading folders, you must create a function (sync / asynchronous) that gets all the files/subfolders inside your folder and uploads each file.

I found a folder iterator code in this Microsoft Link In my code example I added the GCS library to upload the files, it is not necessary to create a folder structure.

For example

// GCS dependencies
using Google.Apis.Storage.v1;
using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using Storage;
// GCS dependencies

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;

static void WalkDirectoryTree(System.IO.DirectoryInfo root)
   {
       System.IO.FileInfo[] files = null;
       System.IO.DirectoryInfo[] subDirs = null;

       // initialize the GCS client library
       var storage = StorageClient.Create();
       // use this variable to define the upload bucket, please use your bucket name
       var bucketName= Myawesomebucket
       try
       {
           files = root.GetFiles("*.*");
       }

       catch (UnauthorizedAccessException e)
       {

       }

       catch (System.IO.DirectoryNotFoundException e)
       {
           Console.WriteLine(e.Message);
       }

       if (files != null)
       {
           foreach (System.IO.FileInfo fi in files)
           {
               // If we
               // want to open, delete or modify the file, then
               // a try-catch block is required here to handle the case
               // where the file has been deleted since the call to TraverseTree().
               Console.WriteLine(fi.FullName);

               // this section is used to upload files to GCS
               // the object name includ folder/subfolder structure
               objectName = objectName ?? Path.GetFileName(fi.FullPath);

               // upload the object to the bucket
               storage.UploadObject(bucketName, objectName, null, f);
               Console.WriteLine($"Uploaded {objectName}.");

           }

           // Now find all the subdirectories under this directory.
           subDirs = root.GetDirectories();

           foreach (System.IO.DirectoryInfo dirInfo in subDirs)
           {
               // Resursive call for each subdirectory.
               WalkDirectoryTree(dirInfo);
           }
       }
   }