问:
How to reproduce an object's translation,rotation,scaling? (possibly language agnostic)
All,

I've got a rather frustrating problem that I think is simple, but my brain is just not working. In short, the problem is: given a sprite/image/thingy, you know that someone has rotated/translated/scaled the sprite, but you don't know the order in which these happen, how can you reproduce the exact image?

For illustration purposes -- Given an image like this:

Someone has the ability to rotate/translate/scale it so that it looks like this (What it looks like after manipulation --- there's two of them in this case...)

I know that the order of operations matter, that is if someone first rotates, then scales, then translates, you get a different image than if you were to do the reverse. The problem is that since I don't know the order beforehand, I am having a tough time reproducing the image. Here is what I get:

And here is what it looks like overlaid to give you an idea of how far off I am:

http://infinitetaco.com/pics/merged.png

I am setting the anchorPoints of the sprites to be at the center, so that isn't the issue. I am also taking into account the width/height of the scaled change, but for some reason it's always just a bit off. It seems that the more dramatic the amount of rotation, the further off my results are. In the right image you can see the result is perfect, but the left one, since there is significant rotation, it is way off.

I know this is probably an easy one, but I'd appreciate some help.

答:
If you are limited to affine transformations (rotation, translation, scaling), then some linear algebra can give you transformation matrix.

You'll need the original bounding box of the sprite (x,y) and the transformed bounding box of the sprite (u,v).  First remove the any translation by shifting the center of transformed coordinates to the center of the original coordinates. Now solve the equation below -- you have 4 unknowns and 4 equations, so just do some algebra to find a, b, c, and d.

[x1 x2 x3 x4; y1 y2 y3 y4] = [a b; c d]*[u1 u2 u3 u4; v1 v2 v3 v4]

For affine transformations, a, b, c, d follow this structure:

[sx*cos(theta) sy*sin(theta); -sx*sin(theta) sy*cos(theta)]

So you can reduce this down to scaling (sx, sy), rotation (theta), and you already computed the transformation.

There are probably faster ways to do this, but this method follows from first principles.


来源: stackexchange

问:
Web API Performance Tracking
I'm trying to find a tool which helps in performance testing for an action methods in Web API Controller (Basically for a post call from angular code to API). Is it possible to track the performance of code inside the method of API? If so, Can you please help me to do so with any example.

Thanks in Advance.

Thanks & Regards,
Raghu S.

答:
There are following options:

Use microbenchmarking library for C#

Use C# code profiler

Use a 3rd-party load testing tool like Apache JMeter to put the load onto your API endpoint simulating hundreds/thousands of users simultaneously accessing the endpoint, check out REST API Testing - How to Do it Right article for more details

Any combination of all above

ContentLicense: CC BY-SA 4.0

Title: Web API Performance Tracking


问:
How do I get my c# console application to run with an app.config?
This is peculiar to me although I'm sure I'm missing something simple and basic. I have a console application that reads a SQL connection from an app.config. It works fine in Visual Studio.  When I move three items to a directory to test, the .exe, the app.config, and the crystal report that it needs to function, it won't read from the app.config.

```<code>Console.WriteLine("about to get connection string...");
var connectionString = ConfigurationManager.ConnectionStrings["InformConnectionString"].ConnectionString;
</code>```

It bombs on the var connectionString line with an unhandled exception Object reference not set to an instance of an object. Again, works fine in the development environment, just not in the production directory.

答: It is because the app.config is renamed to YourAppName.exe.config when it is compiled. Look in your bin/debug folder or bin/release folder. There you find the used config-files</p>

Body:
This is peculiar to me although I'm sure I'm missing something simple and basic. I have a console application that reads a SQL connection from an app.config. It works fine in Visual Studio.  When I move three items to a directory to test, the .exe, the app.config, and the crystal report that it needs to function, it won't read from the app.config.

Console.WriteLine("about to get connection string...");
var connectionString = ConfigurationManager.ConnectionStrings["InformConnectionString"].ConnectionString;

It bombs on the var connectionString line with an unhandled exception Object reference not set to an instance of an object. Again, works fine in the development environment, just not in the production directory.


问:
How to Increase /decrease the font size In PyQt5 QLabel (Fixed Size)?
In my code, use one QLabel with fixed dimension/size. At beginning, I assign text  "Hello,Python" to that QLablel. Now I want to change the text of the QLablel to "Hai, Welcome to Python".

How to decrease the font size of the QLabel, and display full text  with that particular area/size (without any cut off / hidde /hidden) ?

```<code>import sys
from PyQt5.QtWidgets import *

class Labelexample(QWidget):
    def __init__(self):
        super().__init__()
        self.labl = QLabel("Hello,Python",self)
        self.tbox = QLineEdit(self)
        self.labl.setFixedSize(150,30)
        self.tbox.setFixedSize(200,30)
        self.labl.move(50,50)
        self.tbox.move(140,50)
        self.labl.setText("Hai, welcome to Python")
        # self.labl.adjustsize()

app = QApplication(sys.argv)
mywin = Labelexample()
mywin.show()
sys.exit(app.exec_())
</code>```

答:
use .setFont()

eg.:

```<code>self.labl.setFont(QFont('Arial', 10))
</code>```

Body:
In my code, use one QLabel with fixed dimension/size. At beginning, I assign text  "Hello,Python" to that QLablel. Now I want to change the text of the QLablel to "Hai, Welcome to Python".

How to decrease the font size of the QLabel, and display full text  with that particular area/size (without any cut off / hidde /hidden) ?

import sys
from PyQt5.QtWidgets import *

class Labelexample(QWidget):
    def __init__(self):
        super().__init__()
        self.labl = QLabel("Hello,Python",self)
        self.tbox = QLineEdit(self)
        self.labl.setFixedSize(150,30)
        self.tbox.setFixedSize(200,30)
        self.labl.move(50,50)
        self.tbox.move(140,50)
        self.labl.setText("Hai, welcome to Python")
        # self.labl.adjustsize()

app = QApplication(sys.argv)
mywin = Labelexample()
mywin.show()
sys.exit(app.exec_())

Body:
use .setFont()

eg.:

self.labl.setFont(QFont('Arial', 10))


问:
How can I add a jpg saved on my computer to the code that i have written
It is a java program that is designed to look like a Windows 10 Blue Screen Of Death, but I can not figure out how to add an image to it.<br>
I have tried many different methods, but they did not work out for me, maybe I was doing them wrong. The Image is the QR code that is going to be on the lower left hand corner. </p>

```<code>import javax.swing.JFrame;
import javax.swing.*;
import java.awt.*;

public class BSODJava {
 public static void main(String[] args) {
  JFrame frame = new JFrame("Lab00");
  frame.setSize(1366, 768);
  frame.setLocation(0, 0);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setContentPane(new Panel1());
  frame.setVisible(true);
  frame.setBackground(Color.black);
 }
}
class Panel1 extends JPanel {
 public void paintComponent(Graphics g) {
  g.setColor(new Color(6, 117, 170));
  g.fillRect(1, 1, 1366, 768);

  g.setColor(new Color(255, 255, 255));
  g.setFont(new Font("Segoe UI", Font.PLAIN, 200));
  g.drawString(";)", 50, 165);

  g.setColor(new Color(255, 255, 255));
  g.setFont(new Font("Segoe UI", Font.PLAIN, 52));
  g.drawString("Your PC ran into a problem and needs to restart.  We'll", 50, 270);

  g.setColor(new Color(255, 255, 255));
  g.setFont(new Font("Segoe UI", Font.PLAIN, 52));
  g.drawString("restart for you.", 50, 330);
 }
}
</code>```

答:
In your main (or if you are using the Swing solution from camickr somewhere when you initialise your frame) you load your image. Somewhat like this:

```<code> BufferedImage image;

 // somewhere in your constructor for example
 this.image = ImageIO.read(new File("/Path/To/My/Picture/some-picture.jpg"));
</code>```

if you want to have the picture within your application in the resources folder, you should copy it to your application (like I showed in this answer).

Now when you have loaded you image and your paintComponent method is called, you can supply it with the information how and where to paint it:

```<code>public void paintComponent(Graphics g)
{
  // ... your code
  g.setColor(new Color(255, 255, 255));
  g.setFont(new Font("Segoe UI",Font.PLAIN, 52));
  g.drawString("restart for you.", 50, 330);

  g.drawImage(this.image, 0,0,null);  // this will draw the image in the top left corner (keeping it's aspect ration, width and height)

  g.drawImage(                        // to draw the image in the bottom right corner
     this.image,                      // your image instance
     getWidth() - image.getWidth(),   // the frame's width minus the image's width
     getHeight() - image.getHeight(), // and the frame's height minus the image's height
     null                             // no need for an image observer
  );
}
</code>```

Of course you can do a lot more with images and manipulate them as you want. Maybe this tutorials from MKyong can help you in reading and writing images.

Body:
It is a java program that is designed to look like a Windows 10 Blue Screen Of Death, but I can not figure out how to add an image to it.

I have tried many different methods, but they did not work out for me, maybe I was doing them wrong. The Image is the QR code that is going to be on the lower left hand corner.

import javax.swing.JFrame;
import javax.swing.*;
import java.awt.*;

public class BSODJava {
 public static void main(String[] args) {
  JFrame frame = new JFrame("Lab00");
  frame.setSize(1366, 768);
  frame.setLocation(0, 0);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setContentPane(new Panel1());
  frame.setVisible(true);
  frame.setBackground(Color.black);
 }
}
class Panel1 extends JPanel {
 public void paintComponent(Graphics g) {
  g.setColor(new Color(6, 117, 170));
  g.fillRect(1, 1, 1366, 768);

  g.setColor(new Color(255, 255, 255));
  g.setFont(new Font("Segoe UI", Font.PLAIN, 200));
  g.drawString(";)", 50, 165);

  g.setColor(new Color(255, 255, 255));
  g.setFont(new Font("Segoe UI", Font.PLAIN, 52));
  g.drawString("Your PC ran into a problem and needs to restart.  We'll", 50, 270);

  g.setColor(new Color(255, 255, 255));
  g.setFont(new Font("Segoe UI", Font.PLAIN, 52));
  g.drawString("restart for you.", 50, 330);
 }
}

Body:
In your main (or if you are using the Swing solution from camickr somewhere when you initialise your frame) you load your image. Somewhat like this:

 BufferedImage image;

 // somewhere in your constructor for example
 this.image = ImageIO.read(new File("/Path/To/My/Picture/some-picture.jpg"));

if you want to have the picture within your application in the resources folder, you should copy it to your application (like I showed in this answer).

Now when you have loaded you image and your paintComponent method is called, you can supply it with the information how and where to paint it:

public void paintComponent(Graphics g)
{
  // ... your code
  g.setColor(new Color(255, 255, 255));
  g.setFont(new Font("Segoe UI",Font.PLAIN, 52));
  g.drawString("restart for you.", 50, 330);

  g.drawImage(this.image, 0,0,null);  // this will draw the image in the top left corner (keeping it's aspect ration, width and height)

  g.drawImage(                        // to draw the image in the bottom right corner
     this.image,                      // your image instance
     getWidth() - image.getWidth(),   // the frame's width minus the image's width
     getHeight() - image.getHeight(), // and the frame's height minus the image's height
     null                             // no need for an image observer
  );
}

Of course you can do a lot more with images and manipulate them as you want. Maybe this tutorials from MKyong can help you in reading and writing images.


问:
How do i make thos work on any windows pc
So i wanted to make a program it grabs images from a certain path but it doesn twork on any other device than mine i dont wanna change the paths everytime so is there anyway to make

```<code>teti= open('C:/Users/hyper/OneDrive/Desktop/Database/Gpus/Nvidia/Nvidia-2080ti.txt', 'r')
</code>```

global accross all windows platforms

答:
You can't make it global for every computer, unless all the computers have same path like this on:

C:/Users/hyper/OneDrive/Desktop/Database/Gpus/Nvidia/Nvidia-2080ti.txt

What you can do, is to place the file that you want to read in the same directory as your python program. For example your input file Nvidia-2080ti.txt is located in folder called Nvidia, place your python program in the same folder and replace this open() with this one simply:

teti = open('Nvidia-2080ti.txt', `r`)
```

Body:
So i wanted to make a program it grabs images from a certain path but it doesn twork on any other device than mine i dont wanna change the paths everytime so is there anyway to make

teti= open('C:/Users/hyper/OneDrive/Desktop/Database/Gpus/Nvidia/Nvidia-2080ti.txt', 'r')

global accross all windows platforms


问:
How can I check whether an application has already been installed or is being installed for the first time
What will be the best way to check that application is already installed or being installed for the first time.</p>

答:
Bundle version and saving it in user defaults.

EDIT:

There are three things to note here.

Bundle version: This is the version of the your application that you want to release.

Old version: This will indicate previous version of your application. We will store this in user defaults so that we will know what was the old version when updating our application. This will obviously  be nil if your bundle version is 1.0.

Target version: This indicates the version the user is targeting. We will discuss this later.

So, condition such as

bundleVersion > oldVersion or

```<code>if(isVersionBetter:myBundleVersion thanVersion:oldVersion)
</code>```

would either mean we want to create our database (in this case bundle version would be 1.0 and old version will be nil) or update our database (in this case bundle version would be something greater than 1.0 and hence old version would not be nil).

Thus, as we can see, creation of database means user is installing app for the first time. Updating database means user has already installed the app and is updating the database.

But, there might also be a case when you want to update your app and want to keep the database as it is. That is, only UI updating.

Here, target version comes into picture.

As mentioned above, target version is the version the user is targeting. All would work same as above if user is targeting the bundle version. But if user is targeting some other version than bundle version, we would skip database updating part, thus allowing only the UI to change.

So, the final statement would be something like this:

```<code>if( bundleVersion == targetVersion AND bundleVersion > oldVersion ) {
// Either create or update the database.
}else {
// Do nothing. Skips database updating and allows UI update.
}
</code>```

Thus, your database function would look something like this

```<code>-(void) initWithTargetVersion:(NSString *) targetVersion {

    NSString *oldDatabaseVersion = [[NSUserDefaults standardUserDefaults] stringForKey:@"OldDatabaseVersion"];
    NSString *bundleDatabaseVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];

    if([bundleDatabaseVersion isEqualToString:targetVersion] && [self isVersionBetter:oldDatabaseVersion new:targetVersion]) {
        // Create or update the database.
    }else {
        // Do nothing.
    }
}
</code>```

where user would pass the target version as follows:

```<code>[[DatabaseManager sharedManager] initWithTargetVersion:@"1.0"];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Bundle version and saving it in user defaults.

EDIT:

There are three things to note here.

Bundle version: This is the version of the your application that you want to release.

Old version: This will indicate previous version of your application. We will store this in user defaults so that we will know what was the old version when updating our application. This will obviously  be nil if your bundle version is 1.0.

Target version: This indicates the version the user is targeting. We will discuss this later.

So, condition such as

bundleVersion > oldVersion or

if(isVersionBetter:myBundleVersion thanVersion:oldVersion)

would either mean we want to create our database (in this case bundle version would be 1.0 and old version will be nil) or update our database (in this case bundle version would be something greater than 1.0 and hence old version would not be nil).

Thus, as we can see, creation of database means user is installing app for the first time. Updating database means user has already installed the app and is updating the database.

But, there might also be a case when you want to update your app and want to keep the database as it is. That is, only UI updating.

Here, target version comes into picture.

As mentioned above, target version is the version the user is targeting. All would work same as above if user is targeting the bundle version. But if user is targeting some other version than bundle version, we would skip database updating part, thus allowing only the UI to change.

So, the final statement would be something like this:

if( bundleVersion == targetVersion AND bundleVersion > oldVersion ) {
// Either create or update the database.
}else {
// Do nothing. Skips database updating and allows UI update.
}

Thus, your database function would look something like this

-(void) initWithTargetVersion:(NSString *) targetVersion {

    NSString *oldDatabaseVersion = [[NSUserDefaults standardUserDefaults] stringForKey:@"OldDatabaseVersion"];
    NSString *bundleDatabaseVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];

    if([bundleDatabaseVersion isEqualToString:targetVersion] && [self isVersionBetter:oldDatabaseVersion new:targetVersion]) {
        // Create or update the database.
    }else {
        // Do nothing.
    }
}

where user would pass the target version as follows:

[[DatabaseManager sharedManager] initWithTargetVersion:@"1.0"];


问:
How can I create an object that contains instances of a class in Python?
I want to create an object that contains some instances of a class. That object should be some kind of list-generalization of the instances. E.g. I have the following class:

```<code>class car:
    def __init__(self, prize, color)
        self.prize = prize
        self.color = color
</code>```

Now I want to have an object cars that contains many instances of the class car but that I can work with like an instance of car, i.e. cars.prize should return a list of the prizes for all the instances I collected in that object cars.

答:
You could create a new class car_list() that holds a list of cars (to which you can append, remove etc). In that class, add aget_prizes() method that returns a list of prizes by iterating over the list. For example:

```<code>class car_list():
   def __init__(self, cars):
      self.cars = cars # This is a list

   def get_prizes(self):
      return [car.prize for car in self.cars]
</code>```

Body:
I want to create an object that contains some instances of a class. That object should be some kind of list-generalization of the instances. E.g. I have the following class:

class car:
    def __init__(self, prize, color)
        self.prize = prize
        self.color = color

Now I want to have an object cars that contains many instances of the class car but that I can work with like an instance of car, i.e. cars.prize should return a list of the prizes for all the instances I collected in that object cars.

Body:
You could create a new class car_list() that holds a list of cars (to which you can append, remove etc). In that class, add aget_prizes() method that returns a list of prizes by iterating over the list. For example:

class car_list():
   def __init__(self, cars):
      self.cars = cars # This is a list

   def get_prizes(self):
      return [car.prize for car in self.cars]


问:
Change username if you have a specific rank/role
I want to make the bot constantly looking if any user has a rank and in case of finding a user with that role add an emoticon in front of the name</p>

```<code>    client.on('ready', () => {

        if(!member.roles.cache.find(r => r.name === "Prueba")){
            //Set the nickname
            member.setNickname(` ${nickname}`)
         }
    });
</code>```

答:
If I got it right you want to change member nickname. In that case you must do member not client. And if you are using v12 you need to add cache before find

//Check if member doesn't have the role
if(!member.roles.cache.find(r => r.name === "Prueba")){
   //Set the nickname
   member.setNickname(` ${nickname}`)
}else{
  console.log(`${member.tag} has the role`)
}
```

Body:
I want to make the bot constantly looking if any user has a rank and in case of finding a user with that role add an emoticon in front of the name

    client.on('ready', () => {

        if(!member.roles.cache.find(r => r.name === "Prueba")){
            //Set the nickname
            member.setNickname(` ${nickname}`)
         }
    });


问:
How to trigger blazor layout method from a page?
I have simplest razor-server app which is created by default when you create a new solution.
I am looking for solution to set a parameter in my layout from my page without using a JS.
And here is the MainLayout:

```<code>@nherits LayoutComponentBase
    <div class="page @deviceCssClass">
      <div><h3><@Title</h3></div>
      <div class="content px-4">
                @Body
       </div>
     </div>

    @code
    {
        [Parameter]
         public string Title { get; set; }
    }
</code>```

This is my App.razor which implements routing for my pages:

App.razor:

```<code><CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <RouteView  RouteData="@routeData"  DefaultLayout="@typeof(MainLayout)" />
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>
</code>```

And here is my page using MainLayout:

Login.razor:

```<code>@inject AuthenticationStateProvider AuthenticationStateProvider
@inject NavigationManager Navigation
@inherits LayoutComponentBase

<AuthorizeView>
    <Authorized>
        <a href="Identity/Account/Manage">Hello, @context.User.Identity.Name!</a>
        <a href="" vclass="nav-link btn btn-link" @onclick="(() => Logout())">Log out</a>
    </Authorized>
    <NotAuthorized>
        <a href="/Account/Register">Register</a>
        <a href="/Account/Login">Log in</a>
    </NotAuthorized>
</AuthorizeView>
</code>```

Question:
In my MainLayout I have @Title property. This layout is used by many pages.
How do I set @Title of my layout from a page? Let's sey from Login.razor page.

答:
I think I solved it using this answer:
Call method in MainLayout from a page component in Blazor

MainLayout:

```<code>    <CascadingValue Value=SetTitleEvent>
                        @Body
       </CascadingValue>
 ...
 ...
        @code {
             public EventCallback<string> SetTitleEvent => EventCallback.Factory.Create<string>(this, SetTitle);

             public void SetTitle(string t)
             {
                 Title = t;
              }
        }
</code>```

And razor page:

```<code>[CascadingParameter]
        protected EventCallback<string> SetTitleEvent { get; set; }

        protected override Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
                SetTitleEvent.InvokeAsync("Login");

            return base.OnAfterRenderAsync(firstRender);
        }
</code>```

Body:
I have simplest razor-server app which is created by default when you create a new solution.
I am looking for solution to set a parameter in my layout from my page without using a JS.
And here is the MainLayout:

@nherits LayoutComponentBase

<@Title

                @Body

    @code
    {
        [Parameter]
         public string Title { get; set; }
    }

This is my App.razor which implements routing for my pages:

App.razor:

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <RouteView  RouteData="@routeData"  DefaultLayout="@typeof(MainLayout)" />
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">

Sorry, there's nothing at this address.

            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

And here is my page using MainLayout:

Login.razor:

@inject AuthenticationStateProvider AuthenticationStateProvider
@inject NavigationManager Navigation
@inherits LayoutComponentBase

<AuthorizeView>
    <Authorized>
        Hello, @context.User.Identity.Name!
         Logout())">Log out
    </Authorized>
    <NotAuthorized>
        Register
        Log in
    </NotAuthorized>
</AuthorizeView>

Question:
In my MainLayout I have @Title property. This layout is used by many pages.
How do I set @Title of my layout from a page? Let's sey from Login.razor page.

Body:
I think I solved it using this answer:
Call method in MainLayout from a page component in Blazor

MainLayout:

    <CascadingValue Value=SetTitleEvent>
                        @Body
       </CascadingValue>
 ...
 ...
        @code {
             public EventCallback<string> SetTitleEvent => EventCallback.Factory.Create<string>(this, SetTitle);

             public void SetTitle(string t)
             {
                 Title = t;
              }
        }

And razor page:

[CascadingParameter]
        protected EventCallback<string> SetTitleEvent { get; set; }

        protected override Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
                SetTitleEvent.InvokeAsync("Login");

            return base.OnAfterRenderAsync(firstRender);
        }


问:
Dynamically Change text based on String in Canvas
I'm not sure if this is possible, and I'm fairly new to canvas in general, but my goal is to read a string and if the string contains a specific word, then change that specific words specific color while leaving the rest of the string normal.  So for example is text == degraded-performance change that text to Purple, but leave the rest of the text normal. But if text == degraded-performance and operational, change degraded-performance to Purple, and operational to Green

```<code>    // == Color Rules ==
    // Partial Outage = Orange
    // Major Outage = Red
    // Degraded Performance = Purple
    // Under Maintenance = Grey
    // Operational = Green

    function degraded() {
        ctx.fillStyle = "Purple";
        ctx.fill();
        ctx.fillText("Partial Outage", 75, 50);
    }
    function operational() {
        ctx.fillStyle = "Green";
        ctx.fill();
        ctx.fillText("Operational", 75, 50);
    }

    // JSON
    result = {"PF":"operational","PU":"degraded-performance","EA":"operational"}

    const json = JSON.stringify(result, null, 1);
    const removeBracket = json.replace(/{/g, '').replace(/}/g, '');
    const unquoted = removeBracket.replace(/\"/g, "");

            // load bg
            ctx = canvas.getContext("2d");
            img = document.getElementById("bg");
            ctx.drawImage(img, 0, 0);

            // Add to String and Split Lines
            var x = 10;
            var y = 50;
            var lineheight = 30;
            splitlines = ("PF" + ' ' + result.PF.replace(new RegExp(' ', 'g'), '\n') +
            "\n" + "PU" + ' ' + result.PU + "\n" + "EA" + ' ' + result.EA)

            // Split Lines
            var lines = splitlines.split('\n');
            for (var i = 0; i<lines.length; i++){
            ctx.fillText(lines[i], x, y + (i*lineheight) );
            }

            // If string contains a text swap out THAT specific text. How can i do that?
            if (lines.includes('Operational') == true) {
                operational();
            } else {

            }
</code>```

答:
Here is what I would do:

You need the if statement inside the loop setting the right color

json = {
  "PF": "operational",
  "PU": "degraded-performance",
  "EA": "partial-outage"
}

canvas = document.getElementById("c")
ctx = canvas.getContext("2d");
var x = 10;
var y = 10;

for (var prop in json) {
  if (json[prop].includes("degraded-performance")) {
    ctx.fillStyle = "Purple";
  } else if (json[prop].includes("partial-outage")) {
    ctx.fillStyle = "Orange";
  } else {
    ctx.fillStyle = "Green";
  }
  ctx.fillText(prop + ' ' + json[prop], x, y);
  y += 20
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="c"></canvas></code>```

If your text will be in one line look into measureText   https://www.w3schools.com/tags/canvas_measuretext.asp

You can use that to "concatenate" text of different color in one line.

Body:
I'm not sure if this is possible, and I'm fairly new to canvas in general, but my goal is to read a string and if the string contains a specific word, then change that specific words specific color while leaving the rest of the string normal.  So for example is text == degraded-performance change that text to Purple, but leave the rest of the text normal. But if text == degraded-performance and operational, change degraded-performance to Purple, and operational to Green

    // == Color Rules ==
    // Partial Outage = Orange
    // Major Outage = Red
    // Degraded Performance = Purple
    // Under Maintenance = Grey
    // Operational = Green

    function degraded() {
        ctx.fillStyle = "Purple";
        ctx.fill();
        ctx.fillText("Partial Outage", 75, 50);
    }
    function operational() {
        ctx.fillStyle = "Green";
        ctx.fill();
        ctx.fillText("Operational", 75, 50);
    }

    // JSON
    result = {"PF":"operational","PU":"degraded-performance","EA":"operational"}

    const json = JSON.stringify(result, null, 1);
    const removeBracket = json.replace(/{/g, '').replace(/}/g, '');
    const unquoted = removeBracket.replace(/\"/g, "");

            // load bg
            ctx = canvas.getContext("2d");
            img = document.getElementById("bg");
            ctx.drawImage(img, 0, 0);

            // Add to String and Split Lines
            var x = 10;
            var y = 50;
            var lineheight = 30;
            splitlines = ("PF" + ' ' + result.PF.replace(new RegExp(' ', 'g'), '\n') +
            "\n" + "PU" + ' ' + result.PU + "\n" + "EA" + ' ' + result.EA)

            // Split Lines
            var lines = splitlines.split('\n');
            for (var i = 0; i<lines.length; i++){
            ctx.fillText(lines[i], x, y + (i*lineheight) );
            }

            // If string contains a text swap out THAT specific text. How can i do that?
            if (lines.includes('Operational') == true) {
                operational();
            } else {

            }

Body:
Here is what I would do:

You need the if statement inside the loop setting the right color

json = {
  "PF": "operational",
  "PU": "degraded-performance",
  "EA": "partial-outage"
}

canvas = document.getElementById("c")
ctx = canvas.getContext("2d");
var x = 10;
var y = 10;

for (var prop in json) {
  if (json[prop].includes("degraded-performance")) {
    ctx.fillStyle = "Purple";
  } else if (json[prop].includes("partial-outage")) {
    ctx.fillStyle = "Orange";
  } else {
    ctx.fillStyle = "Green";
  }
  ctx.fillText(prop + ' ' + json[prop], x, y);
  y += 20
}

<canvas id="c"></canvas>

If your text will be in one line look into measureText   https://www.w3schools.com/tags/canvas_measuretext.asp

You can use that to "concatenate" text of different color in one line.


问:
Pandas: how to treat strange time format
I have the following Pandas dataframe, where the time (duration) is given in a very strange format:

```<code>Person   Activity   Duration
1        A          1 00:00
2        A          1 00:00
3        B          0 21:17
4        C          0 17:11
</code>```

Where 1 00:00 means 24 hours, and 0 21:17 means 0 days and 21:17 hours, which is to say just 21:17 hours. A quick look at the dtypes returns:

```<code>In[1]: df.dtypes
Out[1]:
Person         object
Activity       object
Duration       object
dtype: object
</code>```

How can I consistently treat the Duration column to return 24 if the value is 1 00:00, and the decimal value of the duration if I have 0 21:17? The decimal value of 0 21:17 would be 21.283.

The outcome should be:

```<code>Person   Activity   Duration
1        A          24
2        A          24
3        B          21.283
4        C          17.183
</code>```

答:
In addition to the other helpful answers, I wanted to post my own solution, which uses a custom function and applies it to a dataframe using df.apply:

```<code>def custom_time_to_decimals(value):
    if value.split()[0]=='1':
        return 24
    else:
        custom = value.split()[1]
        hours = int(custom[0:2])
        minutes = int(custom[3:5])
        decimal = hours + (minutes/60)
        return round(decimal,3)

df['decimalHours'] = df['<insertYourTimeColumnHere>'].apply(custom_time_to_decimals)
</code>```

Body:
I have the following Pandas dataframe, where the time (duration) is given in a very strange format:

Person   Activity   Duration
1        A          1 00:00
2        A          1 00:00
3        B          0 21:17
4        C          0 17:11

Where 1 00:00 means 24 hours, and 0 21:17 means 0 days and 21:17 hours, which is to say just 21:17 hours. A quick look at the dtypes returns:

In[1]: df.dtypes
Out[1]:
Person         object
Activity       object
Duration       object
dtype: object

How can I consistently treat the Duration column to return 24 if the value is 1 00:00, and the decimal value of the duration if I have 0 21:17? The decimal value of 0 21:17 would be 21.283.

The outcome should be:

Person   Activity   Duration
1        A          24
2        A          24
3        B          21.283
4        C          17.183

Body:
In addition to the other helpful answers, I wanted to post my own solution, which uses a custom function and applies it to a dataframe using df.apply:

def custom_time_to_decimals(value):
    if value.split()[0]=='1':
        return 24
    else:
        custom = value.split()[1]
        hours = int(custom[0:2])
        minutes = int(custom[3:5])
        decimal = hours + (minutes/60)
        return round(decimal,3)

df['decimalHours'] = df['<insertYourTimeColumnHere>'].apply(custom_time_to_decimals)


问:
Compare two columns with one coalesce function
I tried this query but it doesn't work, ORA-00904 error.

SELECT
 C.BUSINESS_UNIT
 ,COALESCE(L.CHILD_CONTR_ID
 ,L.PARENT_CONTR_ID) AS CONTRAT
 , C.BILL_TO_CUST_ID
  FROM C_LIE_VW L
  ,CONTR_HDR C
 WHERE 1=1
   AND CONTRAT=C.CONTRACT_NUM
   AND (L.PARENT_CONTR_ID <> ' '
    OR L.CHILD_CONTR_ID IS NOT NULL)
```

It seems I can't do this: AND CONTRAT=C.CONTRACT_NUM

How can I compare the coalesce column with another column?

答:
Please use below query, you cannot use alias to join a value, instead you have to use complete expression. And you no need to use 1=1 condition as well.

```<code>SELECT
 C.BUSINESS_UNIT
,COALESCE(L.CHILD_CONTR_ID
,L.PARENT_CONTR_ID) AS CONTRAT
, C.BILL_TO_CUST_ID
FROM C_LIE_VW L
,CONTR_HDR C
WHERE COALESCE(L.CHILD_CONTR_ID,L.PARENT_CONTR_ID)=C.CONTRACT_NUM
AND (L.PARENT_CONTR_ID <> '' OR L.CHILD_CONTR_ID IS NOT NULL);
</code>```

Below is the join query if required,

```<code>SELECT
 C.BUSINESS_UNIT
,COALESCE(L.CHILD_CONTR_ID
,L.PARENT_CONTR_ID) AS CONTRAT
, C.BILL_TO_CUST_ID
FROM C_LIE_VW L inner join
CONTR_HDR C
on (COALESCE(L.CHILD_CONTR_ID,L.PARENT_CONTR_ID)=C.CONTRACT_NUM )
WHERE (L.PARENT_CONTR_ID <> ' '
OR L.CHILD_CONTR_ID IS NOT NULL);
</code>```

Body:
I tried this query but it doesn't work, ORA-00904 error.

SELECT
 C.BUSINESS_UNIT
 ,COALESCE(L.CHILD_CONTR_ID
 ,L.PARENT_CONTR_ID) AS CONTRAT
 , C.BILL_TO_CUST_ID
  FROM C_LIE_VW L
  ,CONTR_HDR C
 WHERE 1=1
   AND CONTRAT=C.CONTRACT_NUM
   AND (L.PARENT_CONTR_ID <> ' '
    OR L.CHILD_CONTR_ID IS NOT NULL)

It seems I can't do this: AND CONTRAT=C.CONTRACT_NUM

How can I compare the coalesce column with another column?

Body:
Please use below query, you cannot use alias to join a value, instead you have to use complete expression. And you no need to use 1=1 condition as well.

SELECT
 C.BUSINESS_UNIT
,COALESCE(L.CHILD_CONTR_ID
,L.PARENT_CONTR_ID) AS CONTRAT
, C.BILL_TO_CUST_ID
FROM C_LIE_VW L
,CONTR_HDR C
WHERE COALESCE(L.CHILD_CONTR_ID,L.PARENT_CONTR_ID)=C.CONTRACT_NUM
AND (L.PARENT_CONTR_ID <> '' OR L.CHILD_CONTR_ID IS NOT NULL);

Below is the join query if required,

SELECT
 C.BUSINESS_UNIT
,COALESCE(L.CHILD_CONTR_ID
,L.PARENT_CONTR_ID) AS CONTRAT
, C.BILL_TO_CUST_ID
FROM C_LIE_VW L inner join
CONTR_HDR C
on (COALESCE(L.CHILD_CONTR_ID,L.PARENT_CONTR_ID)=C.CONTRACT_NUM )
WHERE (L.PARENT_CONTR_ID <> ' '
OR L.CHILD_CONTR_ID IS NOT NULL);


问:
update widget with set state function
I need some clarifications on setState() function.
I divided the questions to 3, but they're all about setState().

When calling setState does all the widget on the app or in the
context(?) are re-rendered / updated?

What is the importantance of the code inside the setState(() {/* MY
CODE  */}); against /* myCode;*/ setState(() {});

In case I am updating some variables inside the setState function
like:  setState(() { myText='dfg';}) and this variable
updates a widget, Text(myText), how does setState will know to update
the Text widget?

For example, in the following classic code:

```<code>    return Scaffold(
      appBar: AppBar(
        title: Text('Sample Code'),
      ),
      body: Center(
        child: Text('You have pressed the button $_count times.'),
      ),
      bottomNavigationBar: BottomAppBar(
        shape: const CircularNotchedRectangle(),
        child: Container(
          height: 50.0,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => setState(() {
          _count++;
        }),
        tooltip: 'Increment Counter',
        child: Icon(Icons.add),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
    );
  }
}
</code>```

the setState() is called in the bottomNavigationBar widget (so this widget is marked as dirty), so why we can see the update in the Text widget that relate to child...body

答:
1- when you call the setState() method only that widget get re-build.

i don't want to make things complicated but there is one exception to this rule, and that when using a Lifiting state up technique which will lead to multiple widgets being re-drawn every time the Consumer widget do a callback to the ancestor for re-building state. i will show a diagram below which i hope it make it clearer, but you don't need to worry about it if it seems complicated because you wouldn't be using that technique anyway as there are others that are way simpler and easier.

2- there is no difference it's just more meaningful to put the code that changes inside the setState() method indicating these are variables that change.

3- when you call setState() like in your example like this
setState(() => _count++); not the widget that the setState method get called in will be marked as dirty rather than the widgets that depend on that state(here the state is the _count variable), so on the next call to build method the framework see the Text widget that uses the _counter variable as dirty thus re-draw it, the diagram below show your widget tree and explain how it's done

Title: update widget with set state function

Body:
I need some clarifications on setState() function.
I divided the questions to 3, but they're all about setState().

When calling setState does all the widget on the app or in the
context(?) are re-rendered / updated?

What is the importantance of the code inside the setState(() {/* MY
CODE  */}); against /* myCode;*/ setState(() {});

In case I am updating some variables inside the setState function
like:  setState(() { myText='dfg';}) and this variable
updates a widget, Text(myText), how does setState will know to update
the Text widget?

For example, in the following classic code:

    return Scaffold(
      appBar: AppBar(
        title: Text('Sample Code'),
      ),
      body: Center(
        child: Text('You have pressed the button $_count times.'),
      ),
      bottomNavigationBar: BottomAppBar(
        shape: const CircularNotchedRectangle(),
        child: Container(
          height: 50.0,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => setState(() {
          _count++;
        }),
        tooltip: 'Increment Counter',
        child: Icon(Icons.add),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
    );
  }
}

the setState() is called in the bottomNavigationBar widget (so this widget is marked as dirty), so why we can see the update in the Text widget that relate to child...body


问:
Line being occulted by surface plot with matplotlib
I am trying to plot a trajectory around the Earth and I am using plot_surface to plot the Earth and plot to add the trajectory to the same figure. The result looks like this:

When I turn the figure to check a different perspective, I see this:

One of the legs of the trajectory should be in front of the blue sphere and not behind (in particular, the lower leg in the above plot), but seems to send it to the back, even if the line is in the front in the coordinate space.

What do I do to plot it like it actually is in 3d space?

Thanks!

答:
in matplotlib, you can set the order of your plots with "zorder".

The default drawing order for axes is patches, lines, text. This order is determined by the zorder attribute. The following defaults are set

Artist                   Z-order Patch / PatchCollection  1 Line2D /
  LineCollection    2 Text  3 You can change the order for individual
  artists by setting the zorder. Any individual plot() call can set a
  value for the zorder of that particular item.

The plot that you give zorder =0 will lay under all of the plots and then zorder =1 on top of that and so on.
for example:

```<code>plt.plot(x, y, z, 'r-', zorder = 1)
</code>```

for Axis3D you can also use zorder = -1.

Body:
in matplotlib, you can set the order of your plots with "zorder".

The default drawing order for axes is patches, lines, text. This order is determined by the zorder attribute. The following defaults are set

Artist                   Z-order Patch / PatchCollection  1 Line2D /
  LineCollection    2 Text  3 You can change the order for individual
  artists by setting the zorder. Any individual plot() call can set a
  value for the zorder of that particular item.

The plot that you give zorder =0 will lay under all of the plots and then zorder =1 on top of that and so on.
for example:

plt.plot(x, y, z, 'r-', zorder = 1)

for Axis3D you can also use zorder = -1.


问:
Making a new line in js string
I want to make a new line between Editing and Become.
I tried \n but it didn't work
Any clue?</p>

```<code>var i = 0;
var text = "Animation - Web Development- Video Editing Become a member & More.";

function typeWriter(){
    if(i < text.length){
        document.getElementById("text").innerHTML += text.charAt(i);
        i++;
        setTimeout(typeWriter, 50);
    }
}
typeWriter();
</code>```

答:
Add a line break to your string with \n. In your code check to see if a line break is the character, if it is, replace it with

var i = 0;
var text = "Animation - Web Development- Video Editing\nBecome a member & More.";

function typeWriter() {
  var ch = text.charAt(i)
  if (ch === '\n') {
    ch = '
'
  }
  document.getElementById("text").innerHTML += ch
  i++;
  i < text.length && setTimeout(typeWriter, 50);
}
typeWriter();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="text"></div></code>```

Title: Making a new line in js string

Body:
I want to make a new line between Editing and Become.
I tried \n but it didn't work
Any clue?

var i = 0;
var text = "Animation - Web Development- Video Editing Become a member & More.";

function typeWriter(){
    if(i < text.length){
        document.getElementById("text").innerHTML += text.charAt(i);
        i++;
        setTimeout(typeWriter, 50);
    }
}
typeWriter();

Body:
Add a line break to your string with \n. In your code check to see if a line break is the character, if it is, replace it with <br/>

var i = 0;
var text = "Animation - Web Development- Video Editing\nBecome a member & More.";

function typeWriter() {
  var ch = text.charAt(i)
  if (ch === '\n') {
    ch = '<br/>'
  }
  document.getElementById("text").innerHTML += ch
  i++;
  i < text.length && setTimeout(typeWriter, 50);
}
typeWriter();

<div id="text"></div>


问:
PyTorch non-deterministic dropout
I'm trying to make output of BLSTM deterministic, after investigation its appeared that my dropout layer creates not deterministic dropout masks, so I was researching about how to fix random seed in pytorch. I found this page and other suggestions though I put everything in code it did not help. Here is my code:

import sys
import random
import datetime as dt

import numpy as np
import torch

torch.manual_seed(42)
torch.cuda.manual_seed(42)
np.random.seed(42)
random.seed(42)
torch.backends.cudnn.deterministic = True

ex = torch.ones(10)
torch.nn.functional.dropout(ex, p=0.5, training=True)
# Out[29]: tensor([0., 0., 2., 0., 0., 0., 0., 0., 2., 2.])

torch.nn.functional.dropout(ex, p=0.5, training=True)
# Out[30]: tensor([0., 2., 0., 2., 2., 0., 0., 2., 2., 2.])

```

Please help me get deterministic output from dropout for the same input

答:
every time you want the same output you need to reset the random seed again so:

```<code>>>> import torch

>>> torch.manual_seed(42)
<torch._C.Generator object at 0x127cd9170>

>>> ex = torch.ones(10)

>>> torch.nn.functional.dropout(ex, p=0.5, training=True)
tensor([0., 0., 2., 2., 2., 2., 2., 0., 2., 0.])

>>> torch.manual_seed(42)
<torch._C.Generator object at 0x127cd9170>

>>> torch.nn.functional.dropout(ex, p=0.5, training=True)
tensor([0., 0., 2., 2., 2., 2., 2., 0., 2., 0.])
</code>```

You may want to keep resetting all those random seeds in general though, you can find a lot of different randomness when building neural nets in python

Title: PyTorch non-deterministic dropout

Body:
I'm trying to make output of BLSTM deterministic, after investigation its appeared that my dropout layer creates not deterministic dropout masks, so I was researching about how to fix random seed in pytorch. I found this page and other suggestions though I put everything in code it did not help. Here is my code:

import sys
import random
import datetime as dt

import numpy as np
import torch

torch.manual_seed(42)
torch.cuda.manual_seed(42)
np.random.seed(42)
random.seed(42)
torch.backends.cudnn.deterministic = True

ex = torch.ones(10)
torch.nn.functional.dropout(ex, p=0.5, training=True)
# Out[29]: tensor([0., 0., 2., 0., 0., 0., 0., 0., 2., 2.])

torch.nn.functional.dropout(ex, p=0.5, training=True)
# Out[30]: tensor([0., 2., 0., 2., 2., 0., 0., 2., 2., 2.])

Please help me get deterministic output from dropout for the same input

Body:
every time you want the same output you need to reset the random seed again so:

>>> import torch

>>> torch.manual_seed(42)
<torch._C.Generator object at 0x127cd9170>

>>> ex = torch.ones(10)

>>> torch.nn.functional.dropout(ex, p=0.5, training=True)
tensor([0., 0., 2., 2., 2., 2., 2., 0., 2., 0.])

>>> torch.manual_seed(42)
<torch._C.Generator object at 0x127cd9170>

>>> torch.nn.functional.dropout(ex, p=0.5, training=True)
tensor([0., 0., 2., 2., 2., 2., 2., 0., 2., 0.])

You may want to keep resetting all those random seeds in general though, you can find a lot of different randomness when building neural nets in python


问:
Efficient way to find Frequency of a character in a String in java :  O(n)
In a recent interview I was asked to write the below program.
Find out the character whose frequency is minimum in the given String ?
So I tried by iterating through the string by using charAt and storing the character as key in a HashMap and the number of occurences as its value.
Now Again I have to iterate on the Map to find the lowest element.

Is there a more efficient way to do it as obviously the above one is too intensive i guess.

Update and Another Solution

After some thought process  and answers I think the best time that this can be is O(n).
In the first iteration we will have to iterate through the String character by character and then store their frequency in an Array at the specific position(character is an int) and same time have two temporary variables which maintain the least count and the corresponding character.So when I go to the next character and store its frequency in arr[char] = arr[char]+1;At the same time I will check if the temp varible has a value greater than this value,if yes then the temp varible will be this value and also the char will be this one.In this way i suppose we dont need a second iteration to find the smallest and also no sorting is required I guess

.... Wat say  ? Or any more solutions

答:
I'd use an array rather than a hash map. If we're limited to ascii, that's just 256 entries; if we're using Unicode, 64k. Either way not an impossible size. Besides that, I don't see how you could improve on your approach. I'm trying to think of some clever trick to make it more efficient but I can't come up with any.

Seems to me the answer is almost always going to be a whole list of characters: all of those that are used zero times.

Update

This is probably clost to the most efficient it could be in Java. For convenience, I'm assuming we're using plain Ascii.

```<code>public List<Character> rarest(String s)
{
  int[] freq=new int[256];

  for (int p=s.length()-1;p>=0;--p)
  {
    char c=s.charAt(p);
    if (c>255)
      throw new UnexpectedDataException("Wasn't expecting that");
    ++freq[c];
  }
  int min=Integer.MAX_VALUE;
  for (int x=freq.length-1;x>=0;--x)
  {
    // I'm assuming we don't want chars with frequency of zero
    if (freq[x]>0 && min>freq[x])
      min=freq[x];
  }
  List<Character> rares=new ArrayList<Character>();
  for (int x=freq.length-1;x>=0;--x)
  {
    if (freq[x]==min)
      rares.add((char)x);
  }
  return rares;
}
</code>```

Any effort to keep the list sorted by frequency as you go is going to be way more inefficient, because it will have to re-sort every time you examine one character.

Any attempt to sort the list of frequencies at all is going to be more inefficient, as sorting the whole list is clearly going to be slower than just picking the smallest value.

Sorting the string and then counting is going to be slower because the sort will be more expensive than the count.

Technically, it would be faster to create a simple array at the end rather than an ArrayList, but the ArrayList makes slightly more readable code.

There may be a way to do it faster, but I suspect this is close to the optimum solution. I'd certainly be interested to see if someone has a better idea.

Body:
I'd use an array rather than a hash map. If we're limited to ascii, that's just 256 entries; if we're using Unicode, 64k. Either way not an impossible size. Besides that, I don't see how you could improve on your approach. I'm trying to think of some clever trick to make it more efficient but I can't come up with any.

Seems to me the answer is almost always going to be a whole list of characters: all of those that are used zero times.

Update

This is probably clost to the most efficient it could be in Java. For convenience, I'm assuming we're using plain Ascii.

public List<Character> rarest(String s)
{
  int[] freq=new int[256];

  for (int p=s.length()-1;p>=0;--p)
  {
    char c=s.charAt(p);
    if (c>255)
      throw new UnexpectedDataException("Wasn't expecting that");
    ++freq[c];
  }
  int min=Integer.MAX_VALUE;
  for (int x=freq.length-1;x>=0;--x)
  {
    // I'm assuming we don't want chars with frequency of zero
    if (freq[x]>0 && min>freq[x])
      min=freq[x];
  }
  List<Character> rares=new ArrayList<Character>();
  for (int x=freq.length-1;x>=0;--x)
  {
    if (freq[x]==min)
      rares.add((char)x);
  }
  return rares;
}

Any effort to keep the list sorted by frequency as you go is going to be way more inefficient, because it will have to re-sort every time you examine one character.

Any attempt to sort the list of frequencies at all is going to be more inefficient, as sorting the whole list is clearly going to be slower than just picking the smallest value.

Sorting the string and then counting is going to be slower because the sort will be more expensive than the count.

Technically, it would be faster to create a simple array at the end rather than an ArrayList, but the ArrayList makes slightly more readable code.

There may be a way to do it faster, but I suspect this is close to the optimum solution. I'd certainly be interested to see if someone has a better idea.


问:
Using cv2 dnn with .model filetype?
I've been following this tutorial and wanted to import a TensorFlow/keras model using "cv2.dnn.readNetFromTensorFlow" However, I only have .model files for my premade models, but I think I need .pb? Do you know how to get around this? Thanks!</p>

答: Sadly, OpenCV is not compatible yet with SavedModel but in the link to the issue you can find code how to convert your savedModel to protobuf so it can be loaded with OpenCV</p>

Title: Using cv2 dnn with .model filetype?


问:
Laravel/Passport scope issue
Hi stackoverflow developers.

I'm facing an issue with Laravel/Passport scopes. An error occurs when i use a route with scope middleware.

```<code>{
"message": "in_array() expects parameter 2 to be array, null given",
"exception": "ErrorException",
"file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\passport\src\Token.php",
"line": 95,
"trace": [
    {
        "function": "handleError",
        "class": "Illuminate\Foundation\Bootstrap\HandleExceptions",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\passport\src\Token.php",
        "line": 95,
        "function": "in_array"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\passport\src\HasApiTokens.php",
        "line": 54,
        "function": "can",
        "class": "Laravel\Passport\Token",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\passport\src\Http\Middleware\CheckForAnyScope.php",
        "line": 27,
        "function": "tokenCan",
        "class": "App\User",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Laravel\Passport\Http\Middleware\CheckForAnyScope",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Routing\Middleware\SubstituteBindings.php",
        "line": 41,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Illuminate\Routing\Middleware\SubstituteBindings",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Routing\Middleware\ThrottleRequests.php",
        "line": 59,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Illuminate\Routing\Middleware\ThrottleRequests",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Auth\Middleware\Authenticate.php",
        "line": 44,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Illuminate\Auth\Middleware\Authenticate",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 103,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Routing\Router.php",
        "line": 687,
        "function": "then",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Routing\Router.php",
        "line": 662,
        "function": "runRouteWithinStack",
        "class": "Illuminate\Routing\Router",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Routing\Router.php",
        "line": 628,
        "function": "runRoute",
        "class": "Illuminate\Routing\Router",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Routing\Router.php",
        "line": 617,
        "function": "dispatchToRoute",
        "class": "Illuminate\Routing\Router",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php",
        "line": 165,
        "function": "dispatch",
        "class": "Illuminate\Routing\Router",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 128,
        "function": "Illuminate\Foundation\Http\{closure}",
        "class": "Illuminate\Foundation\Http\Kernel",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php",
        "line": 21,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Illuminate\Foundation\Http\Middleware\TransformsRequest",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php",
        "line": 21,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Illuminate\Foundation\Http\Middleware\TransformsRequest",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\ValidatePostSize.php",
        "line": 27,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Illuminate\Foundation\Http\Middleware\ValidatePostSize",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode.php",
        "line": 63,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\fruitcake\laravel-cors\src\HandleCors.php",
        "line": 37,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Fruitcake\Cors\HandleCors",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\fideloper\proxy\src\TrustProxies.php",
        "line": 57,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Fideloper\Proxy\TrustProxies",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 103,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php",
        "line": 140,
        "function": "then",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php",
        "line": 109,
        "function": "sendRequestThroughRouter",
        "class": "Illuminate\Foundation\Http\Kernel",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\public\index.php",
        "line": 55,
        "function": "handle",
        "class": "Illuminate\Foundation\Http\Kernel",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\server.php",
        "line": 21,
        "function": "require_once"
    }
]
</code>```

My Route is:

```<code>Route::middleware(["auth:api", "scope:Administrator"])->post('atts/languages', 'AttribsController@createLanguage');
</code>```

Scopes definition in AuthServiceProvider:

```<code>public function boot()
{
    $this->registerPolicies();
    Passport::routes();
    Passport::tokensExpireIn(now()->addCentury());
    Passport::tokensCan([
        'Administrator' => 'Administrator',
        'Moderator' => 'Moderator',
        'Journalist' => 'Journalist',
        'Client' => 'Client'
    ]);
    Passport::setDefaultScope(['Client']);
}
</code>```

Token affectation in AuthController:

```<code> $token = $user->createToken('app', ['Administrator'])->accessToken;

    $user->token = $token;

    return response()->json($user);
</code>```

Any solution for this?

And thanks.

Environment: Windows 10 OS, Laravel 7.13, Passport 9.2, PHP 7.2, Database MySQL.

Update:
AuthController.php

```<code><?php
namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller{
public function signup(Request $request){
$request->validate([
    'email' => 'required|string|unique:users|email',
    'password' => 'required|string',
    "username" => 'required|string|unique:users',
    'name' => 'required|string',
    'typeId' => 'required|int',
    'lName' => 'required|string',
]);

$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->type_id = $request->typeId;
$user->lName = $request->lName;
$user->username = $request->username;
$user->photo = $request->photo;
$user->phone = $request->phone;
$user->address = $request->adr;
$user->bio = $request->bio;

$user->save();

$user = User::with(['type'])->find($user->id);

$token = $user->createToken('app', [$user->type->name])->accessToken;

$user->token = $token;

return response()->json($user);
}

public function login(){
if (!Auth::attempt(['email' => request('email'), "password" =>>request('password')]))
    return response()->json(['message' => 'not acceptable'], Response::HTTP_NOT_ACCEPTABLE);

$user = request()->user();

$user->token = $user->createToken('app', [$user->type->name])->accessToken;

return response()->json($user);
}

public function logout(){
request()->user()->token()->revoke();
return response()->json(['message' => 'goodbye']);
}
}
</code>```

答: Solved, just removed withAccessToken($accessToken) method in User model (don't know the origin of that).

Title: Laravel/Passport scope issue

Body:
Hi stackoverflow developers.

I'm facing an issue with Laravel/Passport scopes. An error occurs when i use a route with scope middleware.

{
"message": "in_array() expects parameter 2 to be array, null given",
"exception": "ErrorException",
"file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\passport\src\Token.php",
"line": 95,
"trace": [
    {
        "function": "handleError",
        "class": "Illuminate\Foundation\Bootstrap\HandleExceptions",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\passport\src\Token.php",
        "line": 95,
        "function": "in_array"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\passport\src\HasApiTokens.php",
        "line": 54,
        "function": "can",
        "class": "Laravel\Passport\Token",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\passport\src\Http\Middleware\CheckForAnyScope.php",
        "line": 27,
        "function": "tokenCan",
        "class": "App\User",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Laravel\Passport\Http\Middleware\CheckForAnyScope",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Routing\Middleware\SubstituteBindings.php",
        "line": 41,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Illuminate\Routing\Middleware\SubstituteBindings",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Routing\Middleware\ThrottleRequests.php",
        "line": 59,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Illuminate\Routing\Middleware\ThrottleRequests",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Auth\Middleware\Authenticate.php",
        "line": 44,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Illuminate\Auth\Middleware\Authenticate",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 103,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Routing\Router.php",
        "line": 687,
        "function": "then",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Routing\Router.php",
        "line": 662,
        "function": "runRouteWithinStack",
        "class": "Illuminate\Routing\Router",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Routing\Router.php",
        "line": 628,
        "function": "runRoute",
        "class": "Illuminate\Routing\Router",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Routing\Router.php",
        "line": 617,
        "function": "dispatchToRoute",
        "class": "Illuminate\Routing\Router",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php",
        "line": 165,
        "function": "dispatch",
        "class": "Illuminate\Routing\Router",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 128,
        "function": "Illuminate\Foundation\Http\{closure}",
        "class": "Illuminate\Foundation\Http\Kernel",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php",
        "line": 21,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Illuminate\Foundation\Http\Middleware\TransformsRequest",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php",
        "line": 21,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Illuminate\Foundation\Http\Middleware\TransformsRequest",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\ValidatePostSize.php",
        "line": 27,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Illuminate\Foundation\Http\Middleware\ValidatePostSize",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode.php",
        "line": 63,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\fruitcake\laravel-cors\src\HandleCors.php",
        "line": 37,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Fruitcake\Cors\HandleCors",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\fideloper\proxy\src\TrustProxies.php",
        "line": 57,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Fideloper\Proxy\TrustProxies",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 103,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php",
        "line": 140,
        "function": "then",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php",
        "line": 109,
        "function": "sendRequestThroughRouter",
        "class": "Illuminate\Foundation\Http\Kernel",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\public\index.php",
        "line": 55,
        "function": "handle",
        "class": "Illuminate\Foundation\Http\Kernel",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\server.php",
        "line": 21,
        "function": "require_once"
    }
]

My Route is:

Route::middleware(["auth:api", "scope:Administrator"])->post('atts/languages', 'AttribsController@createLanguage');

Scopes definition in AuthServiceProvider:

public function boot()
{
    $this->registerPolicies();
    Passport::routes();
    Passport::tokensExpireIn(now()->addCentury());
    Passport::tokensCan([
        'Administrator' => 'Administrator',
        'Moderator' => 'Moderator',
        'Journalist' => 'Journalist',
        'Client' => 'Client'
    ]);
    Passport::setDefaultScope(['Client']);
}

Token affectation in AuthController:

 $token = $user->createToken('app', ['Administrator'])->accessToken;

    $user->token = $token;

    return response()->json($user);

Any solution for this?

And thanks.

Environment: Windows 10 OS, Laravel 7.13, Passport 9.2, PHP 7.2, Database MySQL.

Update:
AuthController.php

<?php
namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller{
public function signup(Request $request){
$request->validate([
    'email' => 'required|string|unique:users|email',
    'password' => 'required|string',
    "username" => 'required|string|unique:users',
    'name' => 'required|string',
    'typeId' => 'required|int',
    'lName' => 'required|string',
]);

$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->type_id = $request->typeId;
$user->lName = $request->lName;
$user->username = $request->username;
$user->photo = $request->photo;
$user->phone = $request->phone;
$user->address = $request->adr;
$user->bio = $request->bio;

$user->save();

$user = User::with(['type'])->find($user->id);

$token = $user->createToken('app', [$user->type->name])->accessToken;

$user->token = $token;

return response()->json($user);
}

public function login(){
if (!Auth::attempt(['email' => request('email'), "password" =>>request('password')]))
    return response()->json(['message' => 'not acceptable'], Response::HTTP_NOT_ACCEPTABLE);

$user = request()->user();

$user->token = $user->createToken('app', [$user->type->name])->accessToken;

return response()->json($user);
}

public function logout(){
request()->user()->token()->revoke();
return response()->json(['message' => 'goodbye']);
}
}


问:
Simple fetch and display using IPFS - CORS issue
I'm attempting to fetch the following image hosted on IPFS, and present it dynamically in a webpage:

https://ipfs.io/ipfs/QmcRD4wkPPi6dig81r5sLj9Zm1gDCL4zgpEj9CfuRrGbzF

I've got the following:

  <meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline' 'unsafe-eval' https: ;script-src 'unsafe-inline' 'unsafe-eval';">

```
</div>
</div>
</p>

<p>Firefox/chrome give the following error:</p>

<p>Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://ipfs.io/ipfs/QmcRD4wkPPi6dig81r5sLj9Zm1gDCL4zgpEj9CfuRrGbzF. (Reason: CORS request did not succeed)</p>

<p><strong>Does the "Same Origin Policy" in this error refer to the settings on the server or in the browser?</strong></p>

<p><em>N.b. this resource (https://ipfs.github.io/public-gateway-checker/) seems to imply that CORS requests should work on the ipfs.io server.</em></p>

<p><strong>What is the most simple way to fetch and display an image from a remote IPFS node, solely in the browser?</strong></p>

<p>Edit: I've managed to get something partially working, based on the examples at js.ipfs.io.</p>

<p>I still get CORS errors, but it does pull one chunk of text and display it (the image doesn't work still.</p>

<p>Why does this partially work?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
<script src="https://unpkg.com/ipfs@0.41.0-rc.2/dist/index.min.js"></script>
<script>

async function main() {
  const container = document.getElementById('container')
  let node;
    node = await Ipfs.create({ repo: 'ipfs-' + Math.random()})
  const stream = node.cat('QmPChd2hVbrJ6bfo3WBcTW4iZnpHm8TEzWkLHmLpXhF68A')
  let data = ''

  for await (const chunk of stream) {
    console.log('chunk',chunk)
    data += chunk.toString()
  }
  document.getElementById('container').innerHTML = data

}
main()
</script>

<style>
  #container {
    background-color: green;
    width:100%;
    width:150px;
  }
</style>
</head>
<body>
<div id='container'>
</div>
</body>
</html></code>```

答:
Does the "Same Origin Policy" in this error refer to the settings on the server or in the browser?
yes it does refer to the settings on the server as the headers sent from the server are not set to allow-cross-origin.
For your request to work you can use a proxy or make your own one on cloudflare  or host it on heroku
for a quick solution, add this at the beginning of the url

https://cors-anywhere.herokuapp.com/

Body:
I'm attempting to fetch the following image hosted on IPFS, and present it dynamically in a webpage:

https://ipfs.io/ipfs/QmcRD4wkPPi6dig81r5sLj9Zm1gDCL4zgpEj9CfuRrGbzF

I've got the following:

  <meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline' 'unsafe-eval' https: ;script-src 'unsafe-inline' 'unsafe-eval';">

Firefox/chrome give the following error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://ipfs.io/ipfs/QmcRD4wkPPi6dig81r5sLj9Zm1gDCL4zgpEj9CfuRrGbzF. (Reason: CORS request did not succeed)

Does the "Same Origin Policy" in this error refer to the settings on the server or in the browser?

N.b. this resource (https://ipfs.github.io/public-gateway-checker/) seems to imply that CORS requests should work on the ipfs.io server.

What is the most simple way to fetch and display an image from a remote IPFS node, solely in the browser?

Edit: I've managed to get something partially working, based on the examples at js.ipfs.io.

I still get CORS errors, but it does pull one chunk of text and display it (the image doesn't work still.

Why does this partially work?


问:
How to get n stars on 5 stars here
This is the function I'm getting the stars for rating. I need 5 white stars and get the n golden on it.

```<code>let n = []
for(var i = 0; i < product.avg_rating; i++) {
  n.push(<i class="fa fa-star" key={i}></i>)
}
</code>```

I'm calling this variable here

```<code><div className="rating">
  {n}
</div>
</code>```

答:
Create a Rating component that takes a rating prop value and conditionally colors a star. You can do this in a single pass.

```<code>import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faStar } from "@fortawesome/free-solid-svg-icons";

// create [1,2,3,4,5] once
const starArray = [...Array(5).keys()].map(i => i + 1);

const Rating = ({ rating }) =>
  starArray.map(i => ( // use many times
    <FontAwesomeIcon
      key={i}
      icon={faStar}
      color={rating >= i ? "orange" : "lightgrey"}
    />
  ));
</code>```

I used react-fontawesome, but logic is conceptually identical, just swap in whatever iconography you are using.

Title: How to get n stars on 5 stars here

Body:
This is the function I'm getting the stars for rating. I need 5 white stars and get the n golden on it.

let n = []
for(var i = 0; i < product.avg_rating; i++) {
  n.push()
}

I'm calling this variable here

  {n}

Body:
Create a Rating component that takes a rating prop value and conditionally colors a star. You can do this in a single pass.

import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faStar } from "@fortawesome/free-solid-svg-icons";

// create [1,2,3,4,5] once
const starArray = [...Array(5).keys()].map(i => i + 1);

const Rating = ({ rating }) =>
  starArray.map(i => ( // use many times
    <FontAwesomeIcon
      key={i}
      icon={faStar}
      color={rating >= i ? "orange" : "lightgrey"}
    />
  ));

I used react-fontawesome, but logic is conceptually identical, just swap in whatever iconography you are using.


问:
No files to submit even after I add them to perforce changlist
I get a changelist number and I am able to add the files to the changelist

```<code>>>> createdCLNumber
'1157545'
>>> p4.run_add("-c", createdCLNumber, "/Users/ciasto/ciasto_piekarz/sandbox/main/upgrade_tools/upgrade_gitlab")
['//depot/td/main/bin/upgrade_gitlab#1 - currently opened for add']
</code>```

but when I try to submit them I get the error.

```<code>>>> p4.run_submit(changeList)
P4.P4Exception: [P4#run] Errors during command execution( "p4 submit -i" )

        [Error]: 'No files to submit.'
</code>```

答:
If you want to submit a numbered changelist (implied by the fact that you used p4 add -c CHANGELIST), do:

```<code>p4 submit -c CHANGELIST
</code>```

See p4 help submit:

```<code>submit -- Submit open files to the depot

p4 submit [-Af -r -s -f option --noretransfer 0|1]
p4 submit [-Af -r -s -f option] file
p4 submit [-Af -r -f option] -d description
p4 submit [-Af -r -f option] -d description file
p4 submit [-Af -r -f option --noretransfer 0|1] -c changelist#
p4 submit -e shelvedChange#
p4 submit -i [-Af -r -s -f option]
          --parallel=threads=N[,batch=N][,min=N]
</code>```

If you only specify a single argument, it's interpreted as a file path:

```<code>p4 submit [options] file
</code>```

To specify a changelist you want this form:

```<code>p4 submit [options] -c changelist#
</code>```

Body:
I get a changelist number and I am able to add the files to the changelist

>>> createdCLNumber
'1157545'
>>> p4.run_add("-c", createdCLNumber, "/Users/ciasto/ciasto_piekarz/sandbox/main/upgrade_tools/upgrade_gitlab")
['//depot/td/main/bin/upgrade_gitlab#1 - currently opened for add']

but when I try to submit them I get the error.

>>> p4.run_submit(changeList)
P4.P4Exception: [P4#run] Errors during command execution( "p4 submit -i" )

        [Error]: 'No files to submit.'

Body:
If you want to submit a numbered changelist (implied by the fact that you used p4 add -c CHANGELIST), do:

p4 submit -c CHANGELIST

See p4 help submit:

submit -- Submit open files to the depot

p4 submit [-Af -r -s -f option --noretransfer 0|1]
p4 submit [-Af -r -s -f option] file
p4 submit [-Af -r -f option] -d description
p4 submit [-Af -r -f option] -d description file
p4 submit [-Af -r -f option --noretransfer 0|1] -c changelist#
p4 submit -e shelvedChange#
p4 submit -i [-Af -r -s -f option]
          --parallel=threads=N[,batch=N][,min=N]

If you only specify a single argument, it's interpreted as a file path:

p4 submit [options] file

To specify a changelist you want this form:

p4 submit [options] -c changelist#


问:
Angular2 without hash in the url
Now, my website's url looks like this because I'm using the approach described here

http://localhost:4200/#/cadastro

Is it possible to remove the hash in the url and not get the 404 error?

EDIT: Router Module added

```<code>const appRoutes: Routes = [
    { path: '', component: HomeComponent },
    { path: 'cadastro', component: CadastroNoivosComponent },
    { path: '**', component: HomeComponent }
];

export const routing = RouterModule.forRoot(appRoutes);
</code>```

答:
Create a .htaccess file Paste the following Code And Upload on your prod Server.</p>

```<code>RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</code>```

Title: Angular2 without hash in the url

Body:
Now, my website's url looks like this because I'm using the approach described here

http://localhost:4200/#/cadastro

Is it possible to remove the hash in the url and not get the 404 error?

EDIT: Router Module added

const appRoutes: Routes = [
    { path: '', component: HomeComponent },
    { path: 'cadastro', component: CadastroNoivosComponent },
    { path: '**', component: HomeComponent }
];

export const routing = RouterModule.forRoot(appRoutes);

Body:
Create a .htaccess file Paste the following Code And Upload on your prod Server.

RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]


问:
Can I add optional attributes to an element in React?
Currently, in my React app I have this,

```<code><input style={{ borderColor: valid ? null : "red", boxShadow: valid ? null : "rgb(2, 0, 0)"}} />
</code>```

If I have more styling to do, it doesn't make sense checking the same condition again and again right? I wish to make the entire style attribute optional; something like this,

```<code><input valid ? null : style={{ borderColor: "red", boxShadow: "rgb(2, 0, 0)"}} />
</code>```

But I know that's not the right syntax. Isn't there a better way to do this?

答:
You need to put the logic into the style attribute and pass a neutral element for it in case of valid (or extract it into a variable).
I think this should do the trick:</p>

```<code><input style={valid ? {} : { borderColor: "red", boxShadow: "rgb(2, 0, 0)"}} />
</code>```

Body:
Currently, in my React app I have this,

<input style={{ borderColor: valid ? null : "red", boxShadow: valid ? null : "rgb(2, 0, 0)"}} />

If I have more styling to do, it doesn't make sense checking the same condition again and again right? I wish to make the entire style attribute optional; something like this,

<input valid ? null : style={{ borderColor: "red", boxShadow: "rgb(2, 0, 0)"}} />

But I know that's not the right syntax. Isn't there a better way to do this?

Body:
You need to put the logic into the style attribute and pass a neutral element for it in case of valid (or extract it into a variable).
I think this should do the trick:

<input style={valid ? {} : { borderColor: "red", boxShadow: "rgb(2, 0, 0)"}} />


问:
How can I set the max number of MySQL processes or threads?
ps axuw| grep mysql indicates only MySQL process, but if I run htop I can see 10 rows each one of them with a separate PID. So I wonder if they are threads or processes that for some reason I cannot see using ps.

Would it make any sense to try to limit them to two on my development machine, where I don't need concurrent access of many clients.

BTW Running on Ubuntu 8.10

答:
MySQL does use threads, ps can see them if you run ps -eLf.

That said, I wouldn't worry about it - dormant threads use almost no resources whatsoever, and if you constrain the server too much it's bound to come back and bite you on the backside sometime later when you've forgotten that you did it.

OwnerDisplayName: szabgab

OwnerDisplayName: Alnitak

ContentLicense: CC BY-SA 2.5


问:
Javascript onclick form validation
Can someone tell me what I am doing wrong over here.. Its printing out alert when I put character like abc but when I have valid number its not saving...</p>

```<code>function ValidateNumeric() {
    var val = document.getElementById("tbNumber").value;
    var validChars = '0123456789.';

    for(var i = 0; i < val.length; i++) {
      if(validChars.indexOf(val.charAt(i)) == -1)
       alert('Please enter valid number');
       return false;
        }

        return true;
    }

<INPUT TYPE=SUBMIT NAME="action" VALUE="Save Changes" onclick="return ValidateNumeric();" >
</code>```

答:
Use regular expressions!

```<code>function validateNumeric() {
    var val = document.getElementById("tbNumber").value;
    var regex = /^[0-9\.]+$/;

    if(regex.test(value))
        return true
    else {
        alert("Please enter a valid number");
        return false;
    }
}
</code>```

However, that regex allows 1.22.3.6...2 as an input, which is probably not desired. You probably want to have the regex  ^(\d+(\.\d+)?|\.\d+)$

Also, HTML tags should be lower case, and attributes should be quoted:

```<code><input type="number" id="tbNumber" />
<input type="submit" name="action" value="Save Changes" onclick="return validateNumeric();"  />
</code>```

Title: Javascript onclick form validation

Body:
Can someone tell me what I am doing wrong over here.. Its printing out alert when I put character like abc but when I have valid number its not saving...

function ValidateNumeric() {
    var val = document.getElementById("tbNumber").value;
    var validChars = '0123456789.';

    for(var i = 0; i < val.length; i++) {
      if(validChars.indexOf(val.charAt(i)) == -1)
       alert('Please enter valid number');
       return false;
        }

        return true;
    }

<INPUT TYPE=SUBMIT NAME="action" VALUE="Save Changes" onclick="return ValidateNumeric();" >

Body:
Use regular expressions!

function validateNumeric() {
    var val = document.getElementById("tbNumber").value;
    var regex = /^[0-9\.]+$/;

    if(regex.test(value))
        return true
    else {
        alert("Please enter a valid number");
        return false;
    }
}

However, that regex allows 1.22.3.6...2 as an input, which is probably not desired. You probably want to have the regex  ^(\d+(\.\d+)?|\.\d+)$

Also, HTML tags should be lower case, and attributes should be quoted:

<input type="number" id="tbNumber" />
<input type="submit" name="action" value="Save Changes" onclick="return validateNumeric();"  />


问:
Postgres Password Authentication Failed
I am running a Postgres 12 database on Ubuntu 18.04 on WSL (Windows Subsystem for Linux).

I can connect to the database with sudo -u postgres psql without any issues, and can view and create new databases and users.

I created a new user with CREATE USER myusername WITH PASSWORD 'mypassword'; and psql returns CREATE ROLE.

However, when I try to log in as this user with the password that I set with psql -h localhost -U myusername, I get psql: error: could not connect to server: FATAL:  password authentication failed for user "myusername".

I have tried changing the password on this user multiple times with ALTER USER myusername WITH PASSWORD 'newpassword'; and psql returns ALTER ROLE.

A common solution I have found, such as this post, is to modify the pg_hba.conf file.

My pg_hba.conf file is:

```<code>local   all             postgres                                peer

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     peer
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     peer
host    replication     all             127.0.0.1/32            md5
</code>```

I have tried modifying both the first and second lines to md5 and ident, and restarted the postgres server each time, to no avail. I have also tried completely uninstalling and reinstalling Postgres, which does not work either.

Is there anything I am missing? Anything else that I can do to try and fix this? Thanks!

答:
For future reference to those who encounter this problem on Windows Subsystem for Linux, I used the Command Prompt to search the running services and see if a Postgres service was running with sc queryex type=service state=all | find /i "postgres".

This returned:

```<code>SERVICE_NAME: postgresql-x64-9.5
DISPLAY_NAME: postgresql-x64-9.5 - PostgreSQL Server 9.5
</code>```

I then was able to use sc stop with the service name to stop the service:

```<code>sc stop postgresql-x64-9.5
</code>```

This solved the password authentication issue.

Title: Postgres Password Authentication Failed

Body:
I am running a Postgres 12 database on Ubuntu 18.04 on WSL (Windows Subsystem for Linux).

I can connect to the database with sudo -u postgres psql without any issues, and can view and create new databases and users.

I created a new user with CREATE USER myusername WITH PASSWORD 'mypassword'; and psql returns CREATE ROLE.

However, when I try to log in as this user with the password that I set with psql -h localhost -U myusername, I get psql: error: could not connect to server: FATAL:  password authentication failed for user "myusername".

I have tried changing the password on this user multiple times with ALTER USER myusername WITH PASSWORD 'newpassword'; and psql returns ALTER ROLE.

A common solution I have found, such as this post, is to modify the pg_hba.conf file.

My pg_hba.conf file is:

local   all             postgres                                peer

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     peer
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     peer
host    replication     all             127.0.0.1/32            md5

I have tried modifying both the first and second lines to md5 and ident, and restarted the postgres server each time, to no avail. I have also tried completely uninstalling and reinstalling Postgres, which does not work either.

Is there anything I am missing? Anything else that I can do to try and fix this? Thanks!

Body:
For future reference to those who encounter this problem on Windows Subsystem for Linux, I used the Command Prompt to search the running services and see if a Postgres service was running with sc queryex type=service state=all | find /i "postgres".

This returned:

SERVICE_NAME: postgresql-x64-9.5
DISPLAY_NAME: postgresql-x64-9.5 - PostgreSQL Server 9.5

I then was able to use sc stop with the service name to stop the service:

sc stop postgresql-x64-9.5

This solved the password authentication issue.