问:
open new browser window within dialog ajax call - jquery NOT popup
I am stumped.  How do I open a link "go" in this situation using jquery?

Opened a dialog and when click on activate button. The link should open a new browser window / tab the same as clicking on a link "go" with target=_blank.

```<code><div id="dialog">
<a href="http://stackoverflow.com" target="_blank" >go</a>
</div>
<script type="text/javascript">
$( "#dialog" ).dialog({buttons: {
"Activate": function(event) {
    $.get("404.html").error(function(){
    $("#dialog a").click(); //doesnt work
    $("#dialog a").trigger("click"); //doesnt work
    window.open("http://stackoverflow.com",'_blank'); //opens a popup, not what i need
    window.location.href //is not what i need since its in same window/tab
       });
    }
}});
</script>
</code>```

答:
You were partially correct. You do use window.open(strUrl, strWindowName[, strWindowFeatures]);. However, you have to fill in more attributes.

```<code>window.open('link','mywindow','width='+ $(window).width() +',height='+ $(window).height() +',toolbar=yes,
location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,
resizable=yes')
</code>```

Here is good documentation on how to use window.open: https://developer.mozilla.org/en-US/docs/Web/API/Window.open

Below is a short list of the attributes you can use:

width=300
Use this to define the width of the new window.

height=200
Use this to define the height of the new window.

resizable=yes or no
Use this to control whether or not you want the user to be able to resize the window.

scrollbars=yes or no
This lets you decide whether or not to have scrollbars on the window.

toolbar=yes or no
Whether or not the new window should have the browser navigation bar at the top (The back, foward, stop buttons..etc.).

location=yes or no
Whether or not you wish to show the location box with the current url (The place to type http:// address).

directories=yes or no
Whether or not the window should show the extra buttons. (what's cool, personal buttons, etc...).

status=yes or no
Whether or not to show the window status bar at the bottom of the window.

menubar=yes or no
Whether or not to show the menus at the top of the window (File, Edit, etc...).

copyhistory=yes or no
Whether or not to copy the old browser window's history list to the new window.

Body:
I am stumped.  How do I open a link "go" in this situation using jquery?

Opened a dialog and when click on activate button. The link should open a new browser window / tab the same as clicking on a link "go" with target=_blank.

go

Body:
You were partially correct. You do use window.open(strUrl, strWindowName[, strWindowFeatures]);. However, you have to fill in more attributes.

window.open('link','mywindow','width='+ $(window).width() +',height='+ $(window).height() +',toolbar=yes,
location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,
resizable=yes')

Here is good documentation on how to use window.open: https://developer.mozilla.org/en-US/docs/Web/API/Window.open

Below is a short list of the attributes you can use:

width=300
Use this to define the width of the new window.

height=200
Use this to define the height of the new window.

resizable=yes or no
Use this to control whether or not you want the user to be able to resize the window.

scrollbars=yes or no
This lets you decide whether or not to have scrollbars on the window.

toolbar=yes or no
Whether or not the new window should have the browser navigation bar at the top (The back, foward, stop buttons..etc.).

location=yes or no
Whether or not you wish to show the location box with the current url (The place to type http:// address).

directories=yes or no
Whether or not the window should show the extra buttons. (what's cool, personal buttons, etc...).

status=yes or no
Whether or not to show the window status bar at the bottom of the window.

menubar=yes or no
Whether or not to show the menus at the top of the window (File, Edit, etc...).

copyhistory=yes or no
Whether or not to copy the old browser window's history list to the new window.


来源: stackexchange

问:
Fetch particular string from particular block
I am new to c#. I have text file with data in it but I want to read particular block line data.

Here address can occur multiple times in text file.

```<code>Something here...
... ... ...
    interface "system"
        address 10.4.1.10/32
        no shutdown
    exit
something here...
... ... ...
    address 101.4.1.11/32
</code>```

but i want to capture within this

```<code>interface "system"
        address 10.4.1.10/32
        no shutdown
    exit
</code>```

I want to capture this ip from the block:

```<code>10.4.1.10
</code>```

I tried this code:

```<code>int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
   Console.WriteLine (line);
   counter++;
}
file.Close();
// Suspend the screen.
Console.ReadLine();
</code>```

Expected Output:

my expected output is to capture the ip address from that block ie.10.4.1.10
that ip is inside "interface system" block.. that makes that address as unique.. as there can be many ips with keyword address. So i want to take address which is inside interface system block.

Please let me know how i can capture particular string from the block.

答:
If the start of the block and the end of the block are well defined, in order to find the block you can simply:

Search for the start of the block

Do something with the lines until the end of the block

```<code>string line;
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");

while((line = file.ReadLine()) != null && !line.Equals(START_OF_BLOCK)); // 1.

while((line = file.ReadLine()) != null && !line.Equals(END_OF_BLOCK)) // 2.
{
    // do something with the lines
}

file.Close();
</code>```

 Updated answer after edited question:

In order to "extract" the string in a form of an IP address inside the block, you could, for example, use Regular expressions with a .NET Regex class, with previously finding the needed block:

Search for the start of the block

Search for the line inside the block which contains "address"

Extract the IP address from the line using Regexp.Match()

```<code>string line;
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
string pat = @"\b(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\b";
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(pat);

while ((line = Console.ReadLine()) != null && !line.Equals(START_OF_BLOCK)); // 1.
while ((line = Console.ReadLine()) != null && !line.Equals(END_OF_BLOCK)) // 2.
{
    if (line.Contains("address"))
    {
        System.Text.RegularExpressions.Match ip = reg.Match(line);
        Console.WriteLine(ip);
        break; // break if you are sure there's only one ip in that block
    }
}

file.Close();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am new to c#. I have text file with data in it but I want to read particular block line data.

Here address can occur multiple times in text file.

Something here...
... ... ...
    interface "system"
        address 10.4.1.10/32
        no shutdown
    exit
something here...
... ... ...
    address 101.4.1.11/32

but i want to capture within this

interface "system"
        address 10.4.1.10/32
        no shutdown
    exit

I want to capture this ip from the block:

10.4.1.10

I tried this code:

int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
   Console.WriteLine (line);
   counter++;
}
file.Close();
// Suspend the screen.
Console.ReadLine();

Expected Output:

my expected output is to capture the ip address from that block ie.10.4.1.10
that ip is inside "interface system" block.. that makes that address as unique.. as there can be many ips with keyword address. So i want to take address which is inside interface system block.

Please let me know how i can capture particular string from the block.

Body:
If the start of the block and the end of the block are well defined, in order to find the block you can simply:

Search for the start of the block

Do something with the lines until the end of the block

string line;
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");

while((line = file.ReadLine()) != null && !line.Equals(START_OF_BLOCK)); // 1.

while((line = file.ReadLine()) != null && !line.Equals(END_OF_BLOCK)) // 2.
{
    // do something with the lines
}

file.Close();

 Updated answer after edited question:

In order to "extract" the string in a form of an IP address inside the block, you could, for example, use Regular expressions with a .NET Regex class, with previously finding the needed block:

Search for the start of the block

Search for the line inside the block which contains "address"

Extract the IP address from the line using Regexp.Match()

string line;
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
string pat = @"\b(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\b";
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(pat);

while ((line = Console.ReadLine()) != null && !line.Equals(START_OF_BLOCK)); // 1.
while ((line = Console.ReadLine()) != null && !line.Equals(END_OF_BLOCK)) // 2.
{
    if (line.Contains("address"))
    {
        System.Text.RegularExpressions.Match ip = reg.Match(line);
        Console.WriteLine(ip);
        break; // break if you are sure there's only one ip in that block
    }
}

file.Close();


问:
Firebase dynamic link with query parameters
I've been looking at replacing all the links in the firebase password reset and welcome emails with something more custom, so it doesn't look terrible for users (so moving from https://some-app-123f.firebaseapp.com to link.some-app.com).

I thought that the best way to do this might be to use the firebase dynamic links, so I set up link.some-app.com in there. All good so far.

I generated a new dynamic link directly in the web interface. This is basically going to be used for everyone, or that is my hope. Let's call that link link.some-app.com/email-link. I have then set this up to point to https://some-app-123f.firebaseapp.com/__/auth/action. Going to the first takes me to the second, all good so far. The links just open the web, not apps, and no interstitial page.

I can replace the "Action URL" in the email template with link.some-app.com/email-link. When I email a password reset, I get a link that looks like this: https://link.some-app.com/email-link?mode=resetPassword&oobCode=[hash]&apiKey=[key]&lang=en

However, when I click on this link in debug mode (adding d=1 to the end), I get a bunch of errors:

```<code>The format of parameter (mode) is not whitelisted for this domain.
</code>```

So I thought that I could solve this by using the whitelisting feature on the link domain in the firebase console, so I've tried a bunch of different options, but these are the two most permissive (to cover both domain bases, though I am pretty sure I need to be whitelisting the target domain i.e. firebase)

```<code>^https://some-app-123f.firebaseapp.com.*$
^https://link.some-app.com/email-link.*$
</code>```

Am I completely missing something? Is this something that just isn't possible because it is redirecting back to firebase?

tl;dr: I'm trying to create an effectively serverless redirect link to the password reset functionality in firebase using a prettier url than firebase gives you out of the box

答: If an improper program from the Dynamic Links prevents redirection to the sites that are beyond your control then you need to whitelist the URLs where the Dynamic Links can redirect to. For more information regarding whitelisting URLs please visit the link enter here .</p>

Body:
I've been looking at replacing all the links in the firebase password reset and welcome emails with something more custom, so it doesn't look terrible for users (so moving from https://some-app-123f.firebaseapp.com to link.some-app.com).

I thought that the best way to do this might be to use the firebase dynamic links, so I set up link.some-app.com in there. All good so far.

I generated a new dynamic link directly in the web interface. This is basically going to be used for everyone, or that is my hope. Let's call that link link.some-app.com/email-link. I have then set this up to point to https://some-app-123f.firebaseapp.com/__/auth/action. Going to the first takes me to the second, all good so far. The links just open the web, not apps, and no interstitial page.

I can replace the "Action URL" in the email template with link.some-app.com/email-link. When I email a password reset, I get a link that looks like this: https://link.some-app.com/email-link?mode=resetPassword&oobCode=[hash]&apiKey=[key]&lang=en

However, when I click on this link in debug mode (adding d=1 to the end), I get a bunch of errors:

The format of parameter (mode) is not whitelisted for this domain.

So I thought that I could solve this by using the whitelisting feature on the link domain in the firebase console, so I've tried a bunch of different options, but these are the two most permissive (to cover both domain bases, though I am pretty sure I need to be whitelisting the target domain i.e. firebase)

^https://some-app-123f.firebaseapp.com.*$
^https://link.some-app.com/email-link.*$

Am I completely missing something? Is this something that just isn't possible because it is redirecting back to firebase?

tl;dr: I'm trying to create an effectively serverless redirect link to the password reset functionality in firebase using a prettier url than firebase gives you out of the box


问:
Laravel - How to consume and refresh external api into db using Guzzle
I am having this model in my Laravel-5.8 project:

Employee

```<code>class Employee extends Model
{
   protected $table = 'employees';

   protected $primaryKey = 'id';

   protected $fillable = [
              'staff_code',
              'first_name',
              'last_name',
              'department_id',
          ];

  public function department()
  {
     return $this->belongsTo('App\Department','department_id');
  }

}
</code>```

That is,:

App\Employee

Also I have an external api that comes in form of JSON get request.

```<code>https://api.employees.net/allemployees
</code>```

I have viewed it with postman get request and I have something like this:

```<code> {
    "ID": "1",
    "StaffCode": "STC001",
    "FirstName": "Japheth",
    "LastName": "Shalom",
    "DepartmentCode": "dep2",
 },
 {
    "ID": "2",
    "StaffCode": "STC002",
   "FirstName": "Ahitophel",
   "last_name": "Nedum",
   "DepartmentCode": "dep1",
},
{
    "ID": "3",
    "StaffCode": "STC003",
    "FirstName": "Joash",
    "FirstName": "Nathan",
    "DepartmentCode": "dep2",
 },
</code>```

and so on... this continues

Already I have created this function:

```<code> use App\Employee;
 use App\Department;

 public function index()
 {
    $client = new GuzzleHttp\Client();
    $res = $client->request('GET','https://api.employees.net/allemployees');
    $clientdatas = json_decode($res, true);

   ...
 }
</code>```

Apart from the id and staff_code that are UNIQUE, any of the others fields too can change from the source.

Since any of the fields can change at any time. How do I refresh the entire db, save new data and update changes?

Thank you

答:
Don't know will it work or not but the logic you can keep.. In the other answer he is querying under a loop which is bad!

Hope It will Help you a little bit

```<code>public function index() {
    $client = new GuzzleHttp\Client();
    $res = $client->request('GET','https://api.employees.net/allemployees');
    $clientdatas = json_decode($res->getBody()->getContents(), true);
    // create a blank array for insert
    $insert_arr = [];
    foreach($clientdatas as $clientdata) {
        $make_array = [
            'id' => $clientdata['ID'],
            'staff_code' => $clientdata['StaffCode'],
            'first_name' => $clientdata['FirstName'],
            .
            .
        ];
        array_push($insert_arr, $make_array);
        // Now the the $insert_arr will ready for insert
    }
    // Here you have to check its duplicate or not
    $exist_in_db = Employee::all('id')->toArray(); // get the id array from db

    // do the stuff for unset the duplicate
    $final_id = array_map(function($value) {
        return $value['id'];
    }, $team_id);
    unset($exist_in_db);
    if(count($final_id) > 0){
        foreach ($insert_arr as $key => $value) {
            if (in_array($value['id'], $final_id)) {
                unset($insert_arr[$key]);
            } else {
                array_push($final_id, $value['id']);
            }
        }
    }

    // finally insert it here
    if (count($insert_arr) > 0) {
        Employee::insert($insert_arr);
    }
}
</code>```

Let me know its helpful or not!

Body:
I am having this model in my Laravel-5.8 project:

Employee

class Employee extends Model
{
   protected $table = 'employees';

   protected $primaryKey = 'id';

   protected $fillable = [
              'staff_code',
              'first_name',
              'last_name',
              'department_id',
          ];

  public function department()
  {
     return $this->belongsTo('App\Department','department_id');
  }

}

That is,:

App\Employee

Also I have an external api that comes in form of JSON get request.

https://api.employees.net/allemployees

I have viewed it with postman get request and I have something like this:

 {
    "ID": "1",
    "StaffCode": "STC001",
    "FirstName": "Japheth",
    "LastName": "Shalom",
    "DepartmentCode": "dep2",
 },
 {
    "ID": "2",
    "StaffCode": "STC002",
   "FirstName": "Ahitophel",
   "last_name": "Nedum",
   "DepartmentCode": "dep1",
},
{
    "ID": "3",
    "StaffCode": "STC003",
    "FirstName": "Joash",
    "FirstName": "Nathan",
    "DepartmentCode": "dep2",
 },

and so on... this continues

Already I have created this function:

 use App\Employee;
 use App\Department;

 public function index()
 {
    $client = new GuzzleHttp\Client();
    $res = $client->request('GET','https://api.employees.net/allemployees');
    $clientdatas = json_decode($res, true);

   ...
 }

Apart from the id and staff_code that are UNIQUE, any of the others fields too can change from the source.

Since any of the fields can change at any time. How do I refresh the entire db, save new data and update changes?

Thank you

Body:
Don't know will it work or not but the logic you can keep.. In the other answer he is querying under a loop which is bad!

Hope It will Help you a little bit

public function index() {
    $client = new GuzzleHttp\Client();
    $res = $client->request('GET','https://api.employees.net/allemployees');
    $clientdatas = json_decode($res->getBody()->getContents(), true);
    // create a blank array for insert
    $insert_arr = [];
    foreach($clientdatas as $clientdata) {
        $make_array = [
            'id' => $clientdata['ID'],
            'staff_code' => $clientdata['StaffCode'],
            'first_name' => $clientdata['FirstName'],
            .
            .
        ];
        array_push($insert_arr, $make_array);
        // Now the the $insert_arr will ready for insert
    }
    // Here you have to check its duplicate or not
    $exist_in_db = Employee::all('id')->toArray(); // get the id array from db

    // do the stuff for unset the duplicate
    $final_id = array_map(function($value) {
        return $value['id'];
    }, $team_id);
    unset($exist_in_db);
    if(count($final_id) > 0){
        foreach ($insert_arr as $key => $value) {
            if (in_array($value['id'], $final_id)) {
                unset($insert_arr[$key]);
            } else {
                array_push($final_id, $value['id']);
            }
        }
    }

    // finally insert it here
    if (count($insert_arr) > 0) {
        Employee::insert($insert_arr);
    }
}

Let me know its helpful or not!


问:
How to upload images to fastify + graphql backend with axios?
When sending images via axios I found I have to use formdata. I add my images here but when sending the formdata my entire backend just freezes, just says "pending".

Ive been following this

And my attempt so far:

backend:

Apollo:

```<code>import { ApolloServer, makeExecutableSchema } from 'apollo-server-fastify';

const schema = makeExecutableSchema({ typeDefs, resolvers });

const apolloServer = new ApolloServer({
  schema,
  uploads: {
    maxFileSize: 10000000,
    maxFiles: 5,
  },
});

(async function() {
  app.register(apolloServer.createHandler({ path: '/api' }));
})();
</code>```

schema:

```<code>  scalar DateTime
  scalar Upload

  input addUser {
    Email: String!
    Password: String
    FirstName: String!
    LastName: String!
    Age: DateTime!
    JobTitle: String!
    File: Upload
  }

  type Mutation {
    register(input: addUser!): Boolean
  }
</code>```

resolver:

```<code>  Mutation: {
    register: async (obj, args, context, info) => {
        // how to get the formData?
      },
  }
</code>```

FrontEnd:

I build the request like this:

```<code>const getMutation = (mutate: MutationNames, returParams?: any): any => {
  const mutation = {
    login: print(
      gql`
        mutation($email: String!, $password: String!) {
          login(email: $email, password: $password) {
            token
            refreshToken
          }
        }
      `
    ),
    register: print(
      gql`
        mutation(
          $firstName: String!
          $email: String!
          $lastName: String!
          $age: DateTime!
          $jobTitle: String!
          $file: Upload
        ) {
          register(
            input: {
              FirstName: $firstName
              LastName: $lastName
              Email: $email
              Age: $age
              JobTitle: $jobTitle
              File: $file
            }
          )
        }
      `
    ),

  }[mutate];

  if (!mutation) return {};

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

In this case im using the register mutation.

I have a few hooks on how I handle the data fetching so Im not going to include it since it is alot of code. The data is fetched correctly in the front end and before posting to the backend im putting everything to a formData object:

```<code>  const submitForm: SubmitForm = (obj: SendObject) => {
    const Fdata = new FormData();

    Fdata.append('0', fileImp.file);

    Fdata.append('operations', JSON.stringify(obj.data));

    const map = {
      '0': ['variables.file'],
    };
    Fdata.append('map', JSON.stringify(map));

    callAxiosFn(
      {
        method,
        url: 'http://localhost:4000/api',
        data: Fdata,
        // headers: obj.headers,
      },
      qlType.toString()
    );
  };
</code>```

gets called like this:

```<code>  const response = await axios({
    headers: {
      Accept: 'application/json',
      'x-token': localStorage.getItem('token'),
      'x-refresh-token': localStorage.getItem('refreshToken'),
      ...(config.headers || {}),
    },
    ...config,
  });
</code>```

config is AxiosRequestConfig

What Im sending:

I dont exactly understand How the formdata will hit my resolver endpoint  and for that reason im doing something wrong since the backend returns:

(node:748) UnhandledPromiseRejectionWarning: [object Array] (node:748)
  UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
  error originated either by throwing inside of an async function
  without a catch block, or by rejecting a promise which was not handled
  with .catch(). (rejection id: 1) (node:748) [DEP0018]
  DeprecationWarning: Unhandled promise rejections are deprecated. In
  the future, promise rejections that are not handled will terminate the
  Node.js process with a non-zero exit code.

I realize this is alot but Im at the end of my vits here, been at this the entire day. Any help is deeply appreciated.

EDIT:

Since my backend was questioned I thought I would just show that when sending data without appending Formdata like I do above then I get it working:

```<code>  const submitForm: SubmitForm = (obj: SendObject) => {

    callAxiosFn(
      {
        method,
        url: 'http://localhost:4000/api',
        data: obj.data,
      },
      qlType.toString()
    );
  };
</code>```

obj.data is:

```<code>{query: "mutation ($firstName: String!, $email: String!, $l… Age: $age, JobTitle: $jobTitle, File: $file})↵}↵", variables: {…}}
query: "mutation ($firstName: String!, $email: String!, $lastName: String!, $age: DateTime!, $jobTitle: String!, $file: Upload) {↵  register(input: {FirstName: $firstName, LastName: $lastName, Email: $email, Age: $age, JobTitle: $jobTitle, File: $file})↵}↵"
variables:
age: "1977-04-04"
email: "JhoneDoe@hotmail.com"
file: File {name: "something.jpg", lastModified: 1589557760497, lastModifiedDate: Fri May 15 2020 17:49:20 GMT+0200 (centraleuropeisk sommartid), webkitRelativePath: "", size: 32355, …}
firstName: "Jhon"
jobTitle: "SomethingCool"
lastName: "Doe"
password: "CoolPassword!"123"
__proto__: Object
__proto__: Object
</code>```

query getting sent in the browser:

Backend reciving the data but the image is not included:

EDIT:

Recently found that my fastify backend might have issues with reading formData.
tried installing

```<code>fastify-multipart
</code>```

but got errors when registering it:

FST_ERR_CTP_ALREADY_PRESENT(contentType) ^ FastifyError
  [FST_ERR_CTP_ALREADY_PRESENT]:

After that I tried:

```<code>npm uninstall fastify-file-upload
</code>```

Error remained.

答:
@CodingLittle glad you figured out the answer was related to the multipart form field ordering.

Some things to add (answering as I don't have the 50 reputation required to make a comment on your answer, despite being the graphql-upload author)…

Also note that in my qestion I missed setting the file itself to null in the variables

This is true, and good to get right, although in reality a lot of GraphQL multipart request spec server implementations will simply replace whatever is at the mapped path for a file with the upload scalar value without caring what was there — in theory, you could replace files in variables with asdf instead of null and it would still work. JSON.stringify would have replaced the file instances with something like {}.

A lot of your headaches could have been avoided if the backend responded with a clear 400 status and descriptive error message instead of throwing a gnarly UnhandledPromiseRejectionWarning error. If your graphql-upload dependency was up to date on the backend, you should have seen a descriptive error message when the requests were not conforming to the GraphQL multipart request spec regarding field ordering, as can be seen in the graphql-upload tests:

https://github.com/jaydenseric/graphql-upload/blob/v11.0.0/test/public/processRequest.test.js#L929

Try running npm ls graphql-upload in your backend project to check only one version is installed, and that it’s the latest published to npm (v11 at the time of this answer). Note that if you’re relying on Apollo Server to install it for you, they use a very out of date version (v8).

Body:
When sending images via axios I found I have to use formdata. I add my images here but when sending the formdata my entire backend just freezes, just says "pending".

Ive been following this

And my attempt so far:

backend:

Apollo:

import { ApolloServer, makeExecutableSchema } from 'apollo-server-fastify';

const schema = makeExecutableSchema({ typeDefs, resolvers });

const apolloServer = new ApolloServer({
  schema,
  uploads: {
    maxFileSize: 10000000,
    maxFiles: 5,
  },
});

(async function() {
  app.register(apolloServer.createHandler({ path: '/api' }));
})();

schema:

  scalar DateTime
  scalar Upload

  input addUser {
    Email: String!
    Password: String
    FirstName: String!
    LastName: String!
    Age: DateTime!
    JobTitle: String!
    File: Upload
  }

  type Mutation {
    register(input: addUser!): Boolean
  }

resolver:

  Mutation: {
    register: async (obj, args, context, info) => {
        // how to get the formData?
      },
  }

FrontEnd:

I build the request like this:

const getMutation = (mutate: MutationNames, returParams?: any): any => {
  const mutation = {
    login: print(
      gql`
        mutation($email: String!, $password: String!) {
          login(email: $email, password: $password) {
            token
            refreshToken
          }
        }
      `
    ),
    register: print(
      gql`
        mutation(
          $firstName: String!
          $email: String!
          $lastName: String!
          $age: DateTime!
          $jobTitle: String!
          $file: Upload
        ) {
          register(
            input: {
              FirstName: $firstName
              LastName: $lastName
              Email: $email
              Age: $age
              JobTitle: $jobTitle
              File: $file
            }
          )
        }
      `
    ),

  }[mutate];

  if (!mutation) return {};

  return mutation;
};

In this case im using the register mutation.

I have a few hooks on how I handle the data fetching so Im not going to include it since it is alot of code. The data is fetched correctly in the front end and before posting to the backend im putting everything to a formData object:

  const submitForm: SubmitForm = (obj: SendObject) => {
    const Fdata = new FormData();

    Fdata.append('0', fileImp.file);

    Fdata.append('operations', JSON.stringify(obj.data));

    const map = {
      '0': ['variables.file'],
    };
    Fdata.append('map', JSON.stringify(map));

    callAxiosFn(
      {
        method,
        url: 'http://localhost:4000/api',
        data: Fdata,
        // headers: obj.headers,
      },
      qlType.toString()
    );
  };

gets called like this:

  const response = await axios({
    headers: {
      Accept: 'application/json',
      'x-token': localStorage.getItem('token'),
      'x-refresh-token': localStorage.getItem('refreshToken'),
      ...(config.headers || {}),
    },
    ...config,
  });

config is AxiosRequestConfig

What Im sending:

I dont exactly understand How the formdata will hit my resolver endpoint  and for that reason im doing something wrong since the backend returns:

(node:748) UnhandledPromiseRejectionWarning: [object Array] (node:748)
  UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
  error originated either by throwing inside of an async function
  without a catch block, or by rejecting a promise which was not handled
  with .catch(). (rejection id: 1) (node:748) [DEP0018]
  DeprecationWarning: Unhandled promise rejections are deprecated. In
  the future, promise rejections that are not handled will terminate the
  Node.js process with a non-zero exit code.

I realize this is alot but Im at the end of my vits here, been at this the entire day. Any help is deeply appreciated.

EDIT:

Since my backend was questioned I thought I would just show that when sending data without appending Formdata like I do above then I get it working:

  const submitForm: SubmitForm = (obj: SendObject) => {

    callAxiosFn(
      {
        method,
        url: 'http://localhost:4000/api',
        data: obj.data,
      },
      qlType.toString()
    );
  };

obj.data is:

{query: "mutation ($firstName: String!, $email: String!, $l… Age: $age, JobTitle: $jobTitle, File: $file})↵}↵", variables: {…}}
query: "mutation ($firstName: String!, $email: String!, $lastName: String!, $age: DateTime!, $jobTitle: String!, $file: Upload) {↵  register(input: {FirstName: $firstName, LastName: $lastName, Email: $email, Age: $age, JobTitle: $jobTitle, File: $file})↵}↵"
variables:
age: "1977-04-04"
email: "JhoneDoe@hotmail.com"
file: File {name: "something.jpg", lastModified: 1589557760497, lastModifiedDate: Fri May 15 2020 17:49:20 GMT+0200 (centraleuropeisk sommartid), webkitRelativePath: "", size: 32355, …}
firstName: "Jhon"
jobTitle: "SomethingCool"
lastName: "Doe"
password: "CoolPassword!"123"
__proto__: Object
__proto__: Object

query getting sent in the browser:

Backend reciving the data but the image is not included:

EDIT:

Recently found that my fastify backend might have issues with reading formData.
tried installing

fastify-multipart

but got errors when registering it:

FST_ERR_CTP_ALREADY_PRESENT(contentType) ^ FastifyError
  [FST_ERR_CTP_ALREADY_PRESENT]:

After that I tried:

npm uninstall fastify-file-upload

Error remained.


问:
How to repeat values in case of null values on left join
I have a table with a calendar, and a table with rates. In the table with the rates, there are no values existing for days in the weekend. I'm trying to join the two, in order to have a table where there is a rate for all days, and I need the rates in the weekend to be the latest available rate. Instad of it showing NULL values, as it would when you make a left join and the record doesn't exist, it should just take the latest available, repeating the previous value.

I have the below code, which works, but it takes 2 min to do on 7,397 rows, which is way too long.

Does anyone know a faster way to get the same results?

```<code>SELECT
c.CalendarID,
MAX(r.RateID)

FROM Dim_Calendar c

LEFT JOIN Dim_Rates r ON r.RateDate <= c.CalendarID
</code>```

What I get without <= and just an = is the following

```<code>CalendarID | RateID
20131001   | 2
20131002   | 3
20131003   | 4
20131004   | 5
20131005   | NULL
20131006   | NULL
20131007   | 6
</code>```

And this is the desired table:

```<code>CalendarID | RateID
20131001   | 2
20131002   | 3
20131003   | 4
20131004   | 5
20131005   | 5
20131006   | 5
20131007   | 6
</code>```

答:
You can use LAG() window function:

```<code>SELECT c.CalendarID,
  COALESCE(
    r.RateID,
    LAG(r.RateID, 1) OVER (ORDER BY c.CalendarID),
    LAG(r.RateID, 2) OVER (ORDER BY c.CalendarID)
  ) RateID
FROM Dim_Calendar c LEFT JOIN Dim_Rates r
ON r.RateDate = c.CalendarID
ORDER BY c.CalendarID
</code>```

See the demo.

Results:

```<code>> CalendarID | RateID
> ---------: | :-----
>   20131001 | 2
>   20131002 | 3
>   20131003 | 4
>   20131004 | 5
>   20131005 | 5
>   20131006 | 5
>   20131007 | 6
</code>```

Body:
I have a table with a calendar, and a table with rates. In the table with the rates, there are no values existing for days in the weekend. I'm trying to join the two, in order to have a table where there is a rate for all days, and I need the rates in the weekend to be the latest available rate. Instad of it showing NULL values, as it would when you make a left join and the record doesn't exist, it should just take the latest available, repeating the previous value.

I have the below code, which works, but it takes 2 min to do on 7,397 rows, which is way too long.

Does anyone know a faster way to get the same results?

SELECT
c.CalendarID,
MAX(r.RateID)

FROM Dim_Calendar c

LEFT JOIN Dim_Rates r ON r.RateDate <= c.CalendarID

What I get without <= and just an = is the following

CalendarID | RateID
20131001   | 2
20131002   | 3
20131003   | 4
20131004   | 5
20131005   | NULL
20131006   | NULL
20131007   | 6

And this is the desired table:

CalendarID | RateID
20131001   | 2
20131002   | 3
20131003   | 4
20131004   | 5
20131005   | 5
20131006   | 5
20131007   | 6

Body:
You can use LAG() window function:

SELECT c.CalendarID,
  COALESCE(
    r.RateID,
    LAG(r.RateID, 1) OVER (ORDER BY c.CalendarID),
    LAG(r.RateID, 2) OVER (ORDER BY c.CalendarID)
  ) RateID
FROM Dim_Calendar c LEFT JOIN Dim_Rates r
ON r.RateDate = c.CalendarID
ORDER BY c.CalendarID

See the demo.

Results:

> CalendarID | RateID
> ---------: | :-----
>   20131001 | 2
>   20131002 | 3
>   20131003 | 4
>   20131004 | 5
>   20131005 | 5
>   20131006 | 5
>   20131007 | 6


问:
org.hibernate.QueryException: illegal attempt to dereference collection [events0_.id.typesOfEvents] with element property reference [type_id]
I am using spring boot and jpa with restful api. when i am trying to get list of event then this type of error occurs - org.hibernate.QueryException: illegal attempt to dereference collection [events0_.id.typesOfEvents] with element property reference [type_id]

I am passing List Object to constructor as args into jpa custom query but that query will not execute it will fire error.

Event is Main entity inside this entity i have taken List of typeOfEvents with using ManyToMany relation and that two table of Id is stored into third table.

1.Event.java

```<code>@Builder
@ToString
@Entity
@Table(name = "events")
public @Data
class Events implements Comparable<Events> {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column
    private Long id;

    @ManyToOne(cascade = CascadeType.REFRESH)
    @JoinColumn(name = "site_id")
    private Sites sites;

    @Column
    private boolean multipleDays;

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinTable(name = "events_types",
            joinColumns = @JoinColumn(name = "e_id"),
            inverseJoinColumns = @JoinColumn(name = "t_id", unique = false))
    private List<TypesOfEvents> typesOfEvents = new ArrayList<TypesOfEvents>(Arrays.asList());

    @ManyToMany(cascade = CascadeType.DETACH)
    @JoinTable(name = "events_format",
            joinColumns = @JoinColumn(name = "e_id"),
            inverseJoinColumns = @JoinColumn(name = "fs_id", unique = false))
    private List<FormatStructure> formatStructure = new ArrayList<>();

    @Column
    private String startDate;

    @Column
    private String startTime;

    @Column
    private String endDate;

    @Column
    private String endTime;

    @Column
    private String eventName;

    @Column
    private String subTitle;

    @Column
    private String description;

    @Column
    private String location;

    @ManyToOne(cascade = CascadeType.REFRESH)
    @JoinColumn(name = "city_id")
    private City city;

    @ManyToOne(cascade = CascadeType.REFRESH)
    @JoinColumn(name = "venue_one_off_option_id")
    private VenueOneOffOptions venueOneOffOptions;

    @Column
    private double fee;

    @Column
    private boolean paid;

    @Column
    private String eventImg;

    @ManyToOne(cascade = CascadeType.REFRESH)
    @JoinColumn(name = "event_passport_option_id")
    private EventPassportOptions eventPassportOptions;

    @Column
    private int passportTickets;

    @Column
    private int remainingTickets;

    @Column
    private boolean passport;

    @Column
    private int passportDiscountPercent;

    @Column
    private String promoCode;

    @Column
    private String siteUrl;

    @Column
    private String ticketPurchaseSite;

    @Column
    private String videoUrl;

    @ManyToOne(cascade = CascadeType.REFRESH)
    @JoinColumn(name = "primary_contact_member_id")
    private Members primary_contact_member_id;

    @ManyToOne(cascade = CascadeType.REFRESH)
    @JoinColumn(name = "created_member_id")
    private Members created_member_id;

    @ManyToOne(cascade = CascadeType.REFRESH)
    @JoinColumn(name = "group_id")
    private Groups groups;

    @Column
    private String expectedAttendance;

    @Column
    private boolean myFavourite;

    @ManyToOne(cascade = CascadeType.REFRESH)
    @JoinColumn(name = "eventStatusId")
    private EventStatus eventStatus;

    @Column
    private boolean purchasedPromotionalEmails;

    @Column
    private boolean featured;

    @ManyToMany(cascade = CascadeType.DETACH)
    @JoinTable(name = "events_audience_types",
            joinColumns = @JoinColumn(name = "e_id"),
            inverseJoinColumns = @JoinColumn(name = "at_id", unique = false))
    private List<AudienceTypes> audienceTypes = new ArrayList<>();

    @ManyToMany(cascade = CascadeType.DETACH)
    @JoinTable(name = "events_food_options",
            joinColumns = @JoinColumn(name = "e_id"),
            inverseJoinColumns = @JoinColumn(name = "fo_id", unique = false))
    private List<FoodOptions> foodOptions = new ArrayList<>();

    public Events() {
    }

    @Override
    public int compareTo(Events o) {
        return (int) (this.id - o.id);
    }
}
</code>```

2.EventDTO.java

```<code>@ToString
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.CUSTOM)
public @Data
class TestDTO implements Comparable<TestDTO>{

    private Long id;

    private boolean multipleDays;

    private List<TypesOfEvents> eventType = new ArrayList<>(Arrays.asList());

    private String startDate;

    private String startTime;

    private String endDate;

    private String endTime;

    private String eventName;

    private String subTitle;

    private String location;

    private String city;

    private double fee;

    private boolean paid;

    private String eventImg;

    private Long passportOption;

    private int passportTickets;

    private int remainingTickets;

    private boolean passport;

    private String promoCode;

    private String expectedAttendance;

    private boolean myFavourite;

    private String eventStatus;

    private boolean featured;

    public TestDTO(Long id, boolean multipleDays, List<TypesOfEvents> eventType, String startDate, String startTime, String endDate, String endTime, String eventName, String subTitle, String location, String city, double fee, boolean paid, String eventImg, Long passportOption, int passportTickets, int remainingTickets, boolean passport, String promoCode, String expectedAttendance, boolean myFavourite, String eventStatus, boolean featured) {
        this.id = id;
        this.multipleDays = multipleDays;
        this.eventType = eventType;
        this.startDate = startDate;
        this.startTime = startTime;
        this.endDate = endDate;
        this.endTime = endTime;
        this.eventName = eventName;
        this.subTitle = subTitle;
        this.location = location;
        this.city = city;
        this.fee = fee;
        this.paid = paid;
        this.eventImg = eventImg;
        this.passportOption = passportOption;
        this.passportTickets = passportTickets;
        this.remainingTickets = remainingTickets;
        this.passport = passport;
        this.promoCode = promoCode;
        this.expectedAttendance = expectedAttendance;
        this.myFavourite = myFavourite;
        this.eventStatus = eventStatus;
        this.featured = featured;
    }
}
</code>```

3.Query

```<code>@Query("SELECT new com.test.responseDTO.TestDTO(e.id, e.multipleDays, e.typesOfEvents, e.startDate, e.startTime, e.endDate, e.endTime, e.eventName, e.subTitle, e.location, c.name, e.fee, e.paid, e.eventImg, p.event_passport_option_id, e.passportTickets, e.remainingTickets, e.passport, e.promoCode, e.expectedAttendance, e.myFavourite, s.status, e.featured)" +
            " from Events e LEFT JOIN e.typesOfEvents.type_id t JOIN e.city c JOIN e.eventPassportOptions p JOIN e.eventStatus s WHERE e.startDate BETWEEN :startDate AND :endDate AND e.endDate BETWEEN :startDate AND :endDate ORDER BY e.startDate, e.id ASC")
    List<TestDTO> findAllListOfEventsWithoutEventTypeIdWithOnlyTwoDateTest1(String startDate, String endDate);
</code>```

4.Error

```<code>org.hibernate.QueryException: illegal attempt to dereference collection [events0_.id.typesOfEvents] with element property reference [type_id]
</code>```

答:
You reference type_id from list which its not allowed here, because query expression referring type_id to list, not to entity itself. So only replace this LEFT JOIN e.typesOfEvents.type_id t with LEFT JOIN e.typesOfEvents t and it would be work fine. And it would reference variable t to element from list(Relation).

    @Query("SELECT new com.test.responseDTO.TestDTO(e.id, e.multipleDays, e.typesOfEvents, e.startDate, e.startTime, e.endDate, e.endTime, e.eventName, e.subTitle, e.location, c.name, e.fee, e.paid, e.eventImg, p.event_passport_option_id, e.passportTickets, e.remainingTickets, e.passport, e.promoCode, e.expectedAttendance, e.myFavourite, s.status, e.featured)" +
            " from Events e LEFT JOIN e.typesOfEvents t /*this fixed*/ JOIN e.city c JOIN e.eventPassportOptions p JOIN e.eventStatus s WHERE e.startDate BETWEEN :startDate AND :endDate AND e.endDate BETWEEN :startDate AND :endDate ORDER BY e.startDate, e.id ASC")
    List<TestDTO> findAllListOfEventsWithoutEventTypeIdWithOnlyTwoDateTest1(String startDate, String endDate);

```

<p>My Query with changes into TestDTO</p>

```    @Query("SELECT new com.techavidus.networkingPhoniex.responseDTO.TestDTO(e.id, e.multipleDays, t, e.startDate, e.startTime, e.endDate, e.endTime, e.eventName, e.subTitle, e.location, c.name, e.fee, e.paid, e.eventImg, p.event_passport_option_id, e.passportTickets, e.remainingTickets, e.passport, e.promoCode, e.expectedAttendance, e.myFavourite, s.status, e.featured)" +
            " from Events e LEFT JOIN e.typesOfEvents t JOIN e.city c JOIN e.eventPassportOptions p JOIN e.eventStatus s WHERE e.startDate BETWEEN :startDate AND :endDate AND e.endDate BETWEEN :startDate AND :endDate ORDER BY e.startDate, e.id ASC")
    List<TestDTO> findAllListOfEventsWithoutEventTypeIdWithOnlyTwoDateTest1(String startDate, String endDate);
```

<p>output :</p>

```{
  "success": true,
  "message": "Record's find successfully.",
  "data": [
    {
      "date": "2020/05/28",
      "count": 2,
      "events": [
        {
          "id": 1,
          "multipleDays": true,
          "eventType": {
            "type_id": 1,
            "type": "Musician1",
            "paid_listing": false,
            "color": "Black",
            "_enabled": true
          },
          "startDate": "2020/05/28",
          "startTime": "10:12:15",
          "endDate": "2020/05/30",
          "endTime": "20:18:25",
          "eventName": "Test",
          "subTitle": "Testing demo",
          "location": "string",
          "city": "Bhuj",
          "fee": 49,
          "paid": false,
          "eventImg": "Imgage url",
          "passportOption": 1,
          "passportTickets": 0,
          "remainingTickets": 0,
          "passport": false,
          "promoCode": "TEST123",
          "expectedAttendance": "1500",
          "myFavourite": false,
          "eventStatus": "Pending Approval",
          "featured": false
        },
        {
          "id": 1,
          "multipleDays": true,
          "eventType": {
            "type_id": 2,
            "type": "Personal Growth",
            "paid_listing": true,
            "color": "Black",
            "_enabled": true
          },
          "startDate": "2020/05/28",
          "startTime": "10:12:15",
          "endDate": "2020/05/30",
          "endTime": "20:18:25",
          "eventName": "Test",
          "subTitle": "Testing demo",
          "location": "string",
          "city": "Bhuj",
          "fee": 49,
          "paid": false,
          "eventImg": "Imgage url",
          "passportOption": 1,
          "passportTickets": 0,
          "remainingTickets": 0,
          "passport": false,
          "promoCode": "TEST123",
          "expectedAttendance": "1500",
          "myFavourite": false,
          "eventStatus": "Pending Approval",
          "featured": false
        }
      ]
    }
  ]
}

```

Body:
I am using spring boot and jpa with restful api. when i am trying to get list of event then this type of error occurs - org.hibernate.QueryException: illegal attempt to dereference collection [events0_.id.typesOfEvents] with element property reference [type_id]

I am passing List Object to constructor as args into jpa custom query but that query will not execute it will fire error.

Event is Main entity inside this entity i have taken List of typeOfEvents with using ManyToMany relation and that two table of Id is stored into third table.

1.Event.java

@Builder
@ToString
@Entity
@Table(name = "events")
public @Data
class Events implements Comparable<Events> {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column
    private Long id;

    @ManyToOne(cascade = CascadeType.REFRESH)
    @JoinColumn(name = "site_id")
    private Sites sites;

    @Column
    private boolean multipleDays;

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinTable(name = "events_types",
            joinColumns = @JoinColumn(name = "e_id"),
            inverseJoinColumns = @JoinColumn(name = "t_id", unique = false))
    private List<TypesOfEvents> typesOfEvents = new ArrayList<TypesOfEvents>(Arrays.asList());

    @ManyToMany(cascade = CascadeType.DETACH)
    @JoinTable(name = "events_format",
            joinColumns = @JoinColumn(name = "e_id"),
            inverseJoinColumns = @JoinColumn(name = "fs_id", unique = false))
    private List<FormatStructure> formatStructure = new ArrayList<>();

    @Column
    private String startDate;

    @Column
    private String startTime;

    @Column
    private String endDate;

    @Column
    private String endTime;

    @Column
    private String eventName;

    @Column
    private String subTitle;

    @Column
    private String description;

    @Column
    private String location;

    @ManyToOne(cascade = CascadeType.REFRESH)
    @JoinColumn(name = "city_id")
    private City city;

    @ManyToOne(cascade = CascadeType.REFRESH)
    @JoinColumn(name = "venue_one_off_option_id")
    private VenueOneOffOptions venueOneOffOptions;

    @Column
    private double fee;

    @Column
    private boolean paid;

    @Column
    private String eventImg;

    @ManyToOne(cascade = CascadeType.REFRESH)
    @JoinColumn(name = "event_passport_option_id")
    private EventPassportOptions eventPassportOptions;

    @Column
    private int passportTickets;

    @Column
    private int remainingTickets;

    @Column
    private boolean passport;

    @Column
    private int passportDiscountPercent;

    @Column
    private String promoCode;

    @Column
    private String siteUrl;

    @Column
    private String ticketPurchaseSite;

    @Column
    private String videoUrl;

    @ManyToOne(cascade = CascadeType.REFRESH)
    @JoinColumn(name = "primary_contact_member_id")
    private Members primary_contact_member_id;

    @ManyToOne(cascade = CascadeType.REFRESH)
    @JoinColumn(name = "created_member_id")
    private Members created_member_id;

    @ManyToOne(cascade = CascadeType.REFRESH)
    @JoinColumn(name = "group_id")
    private Groups groups;

    @Column
    private String expectedAttendance;

    @Column
    private boolean myFavourite;

    @ManyToOne(cascade = CascadeType.REFRESH)
    @JoinColumn(name = "eventStatusId")
    private EventStatus eventStatus;

    @Column
    private boolean purchasedPromotionalEmails;

    @Column
    private boolean featured;

    @ManyToMany(cascade = CascadeType.DETACH)
    @JoinTable(name = "events_audience_types",
            joinColumns = @JoinColumn(name = "e_id"),
            inverseJoinColumns = @JoinColumn(name = "at_id", unique = false))
    private List<AudienceTypes> audienceTypes = new ArrayList<>();

    @ManyToMany(cascade = CascadeType.DETACH)
    @JoinTable(name = "events_food_options",
            joinColumns = @JoinColumn(name = "e_id"),
            inverseJoinColumns = @JoinColumn(name = "fo_id", unique = false))
    private List<FoodOptions> foodOptions = new ArrayList<>();

    public Events() {
    }

    @Override
    public int compareTo(Events o) {
        return (int) (this.id - o.id);
    }
}

2.EventDTO.java

@ToString
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.CUSTOM)
public @Data
class TestDTO implements Comparable<TestDTO>{

    private Long id;

    private boolean multipleDays;

    private List<TypesOfEvents> eventType = new ArrayList<>(Arrays.asList());

    private String startDate;

    private String startTime;

    private String endDate;

    private String endTime;

    private String eventName;

    private String subTitle;

    private String location;

    private String city;

    private double fee;

    private boolean paid;

    private String eventImg;

    private Long passportOption;

    private int passportTickets;

    private int remainingTickets;

    private boolean passport;

    private String promoCode;

    private String expectedAttendance;

    private boolean myFavourite;

    private String eventStatus;

    private boolean featured;

    public TestDTO(Long id, boolean multipleDays, List<TypesOfEvents> eventType, String startDate, String startTime, String endDate, String endTime, String eventName, String subTitle, String location, String city, double fee, boolean paid, String eventImg, Long passportOption, int passportTickets, int remainingTickets, boolean passport, String promoCode, String expectedAttendance, boolean myFavourite, String eventStatus, boolean featured) {
        this.id = id;
        this.multipleDays = multipleDays;
        this.eventType = eventType;
        this.startDate = startDate;
        this.startTime = startTime;
        this.endDate = endDate;
        this.endTime = endTime;
        this.eventName = eventName;
        this.subTitle = subTitle;
        this.location = location;
        this.city = city;
        this.fee = fee;
        this.paid = paid;
        this.eventImg = eventImg;
        this.passportOption = passportOption;
        this.passportTickets = passportTickets;
        this.remainingTickets = remainingTickets;
        this.passport = passport;
        this.promoCode = promoCode;
        this.expectedAttendance = expectedAttendance;
        this.myFavourite = myFavourite;
        this.eventStatus = eventStatus;
        this.featured = featured;
    }
}

3.Query

@Query("SELECT new com.test.responseDTO.TestDTO(e.id, e.multipleDays, e.typesOfEvents, e.startDate, e.startTime, e.endDate, e.endTime, e.eventName, e.subTitle, e.location, c.name, e.fee, e.paid, e.eventImg, p.event_passport_option_id, e.passportTickets, e.remainingTickets, e.passport, e.promoCode, e.expectedAttendance, e.myFavourite, s.status, e.featured)" +
            " from Events e LEFT JOIN e.typesOfEvents.type_id t JOIN e.city c JOIN e.eventPassportOptions p JOIN e.eventStatus s WHERE e.startDate BETWEEN :startDate AND :endDate AND e.endDate BETWEEN :startDate AND :endDate ORDER BY e.startDate, e.id ASC")
    List<TestDTO> findAllListOfEventsWithoutEventTypeIdWithOnlyTwoDateTest1(String startDate, String endDate);

4.Error

org.hibernate.QueryException: illegal attempt to dereference collection [events0_.id.typesOfEvents] with element property reference [type_id]

Body:
You reference type_id from list which its not allowed here, because query expression referring type_id to list, not to entity itself. So only replace this LEFT JOIN e.typesOfEvents.type_id t with LEFT JOIN e.typesOfEvents t and it would be work fine. And it would reference variable t to element from list(Relation).

    @Query("SELECT new com.test.responseDTO.TestDTO(e.id, e.multipleDays, e.typesOfEvents, e.startDate, e.startTime, e.endDate, e.endTime, e.eventName, e.subTitle, e.location, c.name, e.fee, e.paid, e.eventImg, p.event_passport_option_id, e.passportTickets, e.remainingTickets, e.passport, e.promoCode, e.expectedAttendance, e.myFavourite, s.status, e.featured)" +
            " from Events e LEFT JOIN e.typesOfEvents t /*this fixed*/ JOIN e.city c JOIN e.eventPassportOptions p JOIN e.eventStatus s WHERE e.startDate BETWEEN :startDate AND :endDate AND e.endDate BETWEEN :startDate AND :endDate ORDER BY e.startDate, e.id ASC")
    List<TestDTO> findAllListOfEventsWithoutEventTypeIdWithOnlyTwoDateTest1(String startDate, String endDate);

My Query with changes into TestDTO

    @Query("SELECT new com.techavidus.networkingPhoniex.responseDTO.TestDTO(e.id, e.multipleDays, t, e.startDate, e.startTime, e.endDate, e.endTime, e.eventName, e.subTitle, e.location, c.name, e.fee, e.paid, e.eventImg, p.event_passport_option_id, e.passportTickets, e.remainingTickets, e.passport, e.promoCode, e.expectedAttendance, e.myFavourite, s.status, e.featured)" +
            " from Events e LEFT JOIN e.typesOfEvents t JOIN e.city c JOIN e.eventPassportOptions p JOIN e.eventStatus s WHERE e.startDate BETWEEN :startDate AND :endDate AND e.endDate BETWEEN :startDate AND :endDate ORDER BY e.startDate, e.id ASC")
    List<TestDTO> findAllListOfEventsWithoutEventTypeIdWithOnlyTwoDateTest1(String startDate, String endDate);

output :

{
  "success": true,
  "message": "Record's find successfully.",
  "data": [
    {
      "date": "2020/05/28",
      "count": 2,
      "events": [
        {
          "id": 1,
          "multipleDays": true,
          "eventType": {
            "type_id": 1,
            "type": "Musician1",
            "paid_listing": false,
            "color": "Black",
            "_enabled": true
          },
          "startDate": "2020/05/28",
          "startTime": "10:12:15",
          "endDate": "2020/05/30",
          "endTime": "20:18:25",
          "eventName": "Test",
          "subTitle": "Testing demo",
          "location": "string",
          "city": "Bhuj",
          "fee": 49,
          "paid": false,
          "eventImg": "Imgage url",
          "passportOption": 1,
          "passportTickets": 0,
          "remainingTickets": 0,
          "passport": false,
          "promoCode": "TEST123",
          "expectedAttendance": "1500",
          "myFavourite": false,
          "eventStatus": "Pending Approval",
          "featured": false
        },
        {
          "id": 1,
          "multipleDays": true,
          "eventType": {
            "type_id": 2,
            "type": "Personal Growth",
            "paid_listing": true,
            "color": "Black",
            "_enabled": true
          },
          "startDate": "2020/05/28",
          "startTime": "10:12:15",
          "endDate": "2020/05/30",
          "endTime": "20:18:25",
          "eventName": "Test",
          "subTitle": "Testing demo",
          "location": "string",
          "city": "Bhuj",
          "fee": 49,
          "paid": false,
          "eventImg": "Imgage url",
          "passportOption": 1,
          "passportTickets": 0,
          "remainingTickets": 0,
          "passport": false,
          "promoCode": "TEST123",
          "expectedAttendance": "1500",
          "myFavourite": false,
          "eventStatus": "Pending Approval",
          "featured": false
        }
      ]
    }
  ]
}


问:
PostgreSQL - How to fetch columns with sum of 1 column value by grouping another 3 columns
Sample Table:

```<code>    ACC  ACCN   PART    DESC    UT  SITE    QTY  HAZ    SERIAL    S2    STATUS
    TR1  MSR    KKGR     NO     Y   56      2     N                       ST
    TR1  MSR    KUIJ     NO     Y   98      2     N                       HD
    TR1  MSR    KKGR     NO     Y   56      1     N                       ST
    TR2  MSR    KUIJ     NO     Y   98      5     N                       ST
    TR2  MSR    KKGR     NO     Y   56      1     N                       ST
    TR5  MSR    KUIJ     NO     Y   98      5     N                       ST
    TR1  MSR    KUIJ     NO     Y   98      5     N     KKMH              ST
</code>```

Desired result:

```<code>ACC    ACCN PART    DESC    UT  SITE    QTY HAZ SERIAL  S2  STATUS
TR1    MSR  KKGR     NO     Y   56      3   N                ST
TR1    MSR  KUIJ     NO     Y   98      2   N                HD
TR2    MSR  KUIJ     NO     Y   98      5   N                ST
TR2    MSR  KKGR     NO     Y   56      1   N                ST
</code>```

SQL query to fetch all columns when serial is EMPTY/NULL then group by site and part and status. but The QTY column value = the sum of qty for site,part,status grouping.

I tried with

```<code>SELECT ACC,
       ACCN,
       PART,
       DESC,
       UT,
       SITE,
       QTY,
       HAZ,
       SERIAL,
       S2,
       STATUS
  FROM mytable
 WHERE acc IN ('TR1','TR2')
   AND serial = ''
 GROUP
    BY (part,site,status)
</code>```

But i got error like:

ERROR: column "mytable.account" must appear in the GROUP BY clause or be used in an aggregate function

答:
From your desired output, it looks like you want to sum the quantity grouped by all other columns in your select. </p>

```<code>SELECT ACC,
       ACCN,
       PART,
       DESC,
       UT,
       SITE,
   SUM(QTY) as QTY,
   HAZ,
   SERIAL,
   S2,
   STATUS
FROM mytable
WHERE acc IN ('TR1','TR2')
AND serial = ''
GROUP BY ACC,
   ACCN,
   PART,
   DESC,
   UT,
   SITE,
   HAZ,
   SERIAL,
   S2,
   STATUS
</code>```

Body:
Sample Table:

    ACC  ACCN   PART    DESC    UT  SITE    QTY  HAZ    SERIAL    S2    STATUS
    TR1  MSR    KKGR     NO     Y   56      2     N                       ST
    TR1  MSR    KUIJ     NO     Y   98      2     N                       HD
    TR1  MSR    KKGR     NO     Y   56      1     N                       ST
    TR2  MSR    KUIJ     NO     Y   98      5     N                       ST
    TR2  MSR    KKGR     NO     Y   56      1     N                       ST
    TR5  MSR    KUIJ     NO     Y   98      5     N                       ST
    TR1  MSR    KUIJ     NO     Y   98      5     N     KKMH              ST

Desired result:

ACC    ACCN PART    DESC    UT  SITE    QTY HAZ SERIAL  S2  STATUS
TR1    MSR  KKGR     NO     Y   56      3   N                ST
TR1    MSR  KUIJ     NO     Y   98      2   N                HD
TR2    MSR  KUIJ     NO     Y   98      5   N                ST
TR2    MSR  KKGR     NO     Y   56      1   N                ST

SQL query to fetch all columns when serial is EMPTY/NULL then group by site and part and status. but The QTY column value = the sum of qty for site,part,status grouping.

I tried with

SELECT ACC,
       ACCN,
       PART,
       DESC,
       UT,
       SITE,
       QTY,
       HAZ,
       SERIAL,
       S2,
       STATUS
  FROM mytable
 WHERE acc IN ('TR1','TR2')
   AND serial = ''
 GROUP
    BY (part,site,status)

But i got error like:

ERROR: column "mytable.account" must appear in the GROUP BY clause or be used in an aggregate function

Body:
From your desired output, it looks like you want to sum the quantity grouped by all other columns in your select.

SELECT ACC,
       ACCN,
       PART,
       DESC,
       UT,
       SITE,
   SUM(QTY) as QTY,
   HAZ,
   SERIAL,
   S2,
   STATUS
FROM mytable
WHERE acc IN ('TR1','TR2')
AND serial = ''
GROUP BY ACC,
   ACCN,
   PART,
   DESC,
   UT,
   SITE,
   HAZ,
   SERIAL,
   S2,
   STATUS


问:
Regex for German house number
Looking for a regex that specifies a German house number:

Valid house number:

25

25 a

25b

25-ab

12-14

1

9

21

1a

121 b

25A

25 a

Not valid house number:

1 a1

1a1

12ab12

0

b

0a

00a

a a

00 a

13àâäèéêë

The last example excludes every non Latin character

My regex doesn't match the way it should:

```<code>\d+(\s|-)?\w*$
</code>```

EDIT: Sorry, I had to change the examples above! Please have a look!

答:
First there's the question of whether this is a good idea or not… (see various articles titled "Falsehoods programmers believe about XYZ") I'm not in Germany but nearby Austria, and my address does not match any of your examples. (There are 2 ways to write it, and neither matches one of yours.)

Aside from that:

What matches are you expecting that don't match?

What doesn't match which you'd expect?

What regex dialect are you using?

Some obvious issues:

```<code>\d+(\s|-)?\w*$
   ^^^^^^^^^^
</code>```

* matches 0 instances. So you're allowing a dash or space followed by no characters. Probably not what you wanted. Try:

```<code>\d+((\s|-)?\w+)?
</code>```

This will make the whole letter block optional, but it must always have a letter.

Speaking of which, letters \w are not digits. So you'll need to explicitly allow them.

\d+ will match 1 or more digits, not "a number not prefixed with 0". If your first digit must not be zero, you'll need to be explicit about this: [1-9]\d*.

You have an end matching character $ but no start matching ^. You probably want either none or both, depending on whether your regex check is of the "match" or "search" kind. (i.e. if your regex library call attempts to validate the entire input string, or whether any substring matches.)

Title: Regex for German house number

Body:
Looking for a regex that specifies a German house number:

Valid house number:

25

25 a

25b

25-ab

12-14

1

9

21

1a

121 b

25A

25 a

Not valid house number:

1 a1

1a1

12ab12

0

b

0a

00a

a a

00 a

13àâäèéêë

The last example excludes every non Latin character

My regex doesn't match the way it should:

\d+(\s|-)?\w*$

EDIT: Sorry, I had to change the examples above! Please have a look!

Body:
First there's the question of whether this is a good idea or not… (see various articles titled "Falsehoods programmers believe about XYZ") I'm not in Germany but nearby Austria, and my address does not match any of your examples. (There are 2 ways to write it, and neither matches one of yours.)

Aside from that:

What matches are you expecting that don't match?

What doesn't match which you'd expect?

What regex dialect are you using?

Some obvious issues:

\d+(\s|-)?\w*$
   ^^^^^^^^^^

* matches 0 instances. So you're allowing a dash or space followed by no characters. Probably not what you wanted. Try:

\d+((\s|-)?\w+)?

This will make the whole letter block optional, but it must always have a letter.

Speaking of which, letters \w are not digits. So you'll need to explicitly allow them.

\d+ will match 1 or more digits, not "a number not prefixed with 0". If your first digit must not be zero, you'll need to be explicit about this: [1-9]\d*.

You have an end matching character $ but no start matching ^. You probably want either none or both, depending on whether your regex check is of the "match" or "search" kind. (i.e. if your regex library call attempts to validate the entire input string, or whether any substring matches.)


问:
How to autoscaled graphs with picking legend (matplotlib)?
I am working on a picking legend with matplotlib. The goal is to hide and shows curves, by clicking on the legend. I found this solution (Hiding lines after showing a pyplot figure), which works very well.

I want improve this code to adapt automatically the axis after each clic on the legend. I don't know if it is possible. Do you have any hint?

Their is an example of what I want on the images below. First of all, the Image 1 represents the graph. Then after clicking on the legend 5*sin(x), the orange curve disappears as expected (Image 2). On the Image 2, the y-axis is not optimized. The result expected is on the Image 3.

Example

Thank you very much,

答:
Adding a call to the relim method with the visible_only flag set to True and updating the axis should perform the way you want. This will need to be added to your on_click/update method.</p>

```<code># Where ax2 is a reference to your second axis
ax2.relim(visible_only=True)  # Ignore the line you've hidden when rescaling.
ax2.autoscale_view()  # assuming the axis has not been altered by set_xlim etc.
</code>```

Body:
Adding a call to the relim method with the visible_only flag set to True and updating the axis should perform the way you want. This will need to be added to your on_click/update method.

# Where ax2 is a reference to your second axis
ax2.relim(visible_only=True)  # Ignore the line you've hidden when rescaling.
ax2.autoscale_view()  # assuming the axis has not been altered by set_xlim etc.


问:
Questions about boxing
I know that boxing is a popular concept with plenty of information available on it, but I have a few questions which I can't really find answers to:

1) If boxing leads to a value type (struct) being converted to an object (Reference type), or reference type, then why use a value type which will be boxed and incur a performance penalty? I am aware of the benefits and suitability in certain cases of either a struct or class. It is said (1) that values (value types) tend to live on the stack in a temporary storage space, but how long for? If I don't need the type, how can I ensure it is taken care of and disposed at that moment? Or is this where the disposable pattern comes into play? I assume the reason to use a struct will be due to its benefits.

Interestingly, if I use a struct to store two strings and a DateTime field, the struct will hold two references (strings) and the DateTime together. I obviously assume this is quicker than the values being scattered. Is there anything I need to be aware of in this design? (2).

1) http://en.csharp-online.net/Classes, Structs, and Objects—Boxing and Unboxing

2) http://dotnetperls.com/Content/Struct-Examples.aspx

I have done a search on here for the answers I am after, but no luck. I usually do searches on this site for topics such as GC, generics, exception handling, etc, as there is a lot of wisdom to learn and share.

Thanks for the (potential) education to all posters! Please excuse any potential naivety. Learning the internals takes me nicely to spending some time on understanding IL, etc (something to tackle, soon).

答:
You don't always need boxing, and with generics there is little need for that.

The memory used by value types (struct is a value type)  will be claimed as

soon as the method ends/returns and you don't
need to do anything for that to happen.

Value types declared as instance members will be in memory until the object

is deleted by the GC.

Reference types are kept on the managed heap.

Reference types instantiated within a method will be deleted by the

garbage collector when no object is holding a reference to it.

GC works by itself and for the most part you should leave it alone.

You can not predict when an object is going to be deleted by the GC.

The Dispose pattern is used on reference types but will not force GC to delete

an object. It's usually used to free unmanaged resources.

For values in the stack consider the following:

Let's say you have a simple program with three methods, like below:

When this program is run, the Main method is run, and so on. Please follow the

numbers below:

```
<code>
Main
{
   // (0) Stack is empty
   int firstInt = 0;
   // (1) Stack now contains:
   //                     firstInt
   DoSomething1();
   // (7) Stack still contains:
   //                     firstInt
}
// Program ends

DoSomething()
{
   int anInteger = 0;
   // (2) Stack now contains:
   //                    anInteger
   //                    firstInt
   DoMore()
   // (5) Stack now contains:
   //                     anInteger
   //                     firstInt
}
// (6) anInteger goes out of scope

DoMore
{
  int anotherInteger = 1;
   // (3) Stack now contains:
   //                     anotherInteger
   //                     anInteger
   //                     firstInt
}
// (4) anotherInteger goes out of scope

```

OwnerDisplayName: GSS

ContentLicense: CC BY-SA 2.5

Title: Questions about boxing

LastEditorDisplayName: jpalecek

Body:
You don't always need boxing, and with generics there is little need for that.

The memory used by value types (struct is a value type)  will be claimed as

soon as the method ends/returns and you don't
need to do anything for that to happen.

Value types declared as instance members will be in memory until the object

is deleted by the GC.

Reference types are kept on the managed heap.

Reference types instantiated within a method will be deleted by the

garbage collector when no object is holding a reference to it.

GC works by itself and for the most part you should leave it alone.

You can not predict when an object is going to be deleted by the GC.

The Dispose pattern is used on reference types but will not force GC to delete

an object. It's usually used to free unmanaged resources.

For values in the stack consider the following:

Let's say you have a simple program with three methods, like below:

When this program is run, the Main method is run, and so on. Please follow the

numbers below:

Main
{
   // (0) Stack is empty
   int firstInt = 0;
   // (1) Stack now contains:
   //                     firstInt
   DoSomething1();
   // (7) Stack still contains:
   //                     firstInt
}
// Program ends

DoSomething()
{
   int anInteger = 0;
   // (2) Stack now contains:
   //                    anInteger
   //                    firstInt
   DoMore()
   // (5) Stack now contains:
   //                     anInteger
   //                     firstInt
}
// (6) anInteger goes out of scope

DoMore
{
  int anotherInteger = 1;
   // (3) Stack now contains:
   //                     anotherInteger
   //                     anInteger
   //                     firstInt
}
// (4) anotherInteger goes out of scope

OwnerDisplayName: Klinger


问:
how do make this show/hide more concise?
There are many show/hide questions and examples but I can't find the answer.

I have a simple code like this which  is used in a few areas within a page.

```<code>jQuery(document).ready(function () {
    jQuery('#mini-cart').hide();
    jQuery('#mini-cart-a').click(function ()  {
        jQuery('#mini-cart').toggle(400);
        return false;
    });
});
</code>```

Each show/hide uses its own ID, so I simply group ids like so:

```<code>jQuery('#show-hide1, #show-hide2').hide();
</code>```

Problem with this method is, when I click on of the show/hid element, all of the elements show.

So I tried something like this but only the first ones works, the second ones isn't working, when I click on it, it does nothing.

```<code>jQuery(document).ready(function () {
    jQuery('show-hide1, #show-hide2').hide();
    jQuery('show-hide1 a, #show-hide2 a').click(function () {
        jQuery(this).next().toogle(400);
    }
    return false;
    });
});
</code>```

There are 4 different areas that I need the show/hide within a page and  really don't want to repeat the same codes 4 times. Thanks!

Update:
(Sorry I can't use the Add Comment nor answer my question)

Thank you all, for your helpful reply.

Lee's version is more like a tabs - I don't want the hidden div associate an ID to anchor tag. It's CMS enviornment so I try to make it simpler if possible.

Andy's version has similar ID issue, so I opted in for roXon's

RoXon:
http://jsbin.com/ihoqi3/2/
Click on View Bag (2), you can see it's working, however if you go to Questions' tab, click on "Ask a question", it opens up the hidden container from View Bag.

Jeremy B's version:
http://jsbin.com/ibayu4
It hides the toggleLink's text.

From the example page, the "Choose your tea" and "Write a Review" in the Reviews Tab require similar treatment, but if I can get the above mentioned two working, the rest will take care by itself :)

Right now I use 4 separate codes to make it work.

p/s, I need to use the herf anchor because this is important for keyboard user, with the JS show/hide the hidden div can't be toggled.

答:
Like Andy's but slightly different, to allow remove ID's as not necessary.

We can keep it simple right?

jsFiddle demo

```<code><a href="#" class="toggleLink">1</a>
<a href="#" class="toggleLink">2</a>
<a href="#" class="toggleLink">3</a>
<a href="#" class="toggleLink">4</a>

<div class="show-hide">div 1</div>
<div class="show-hide">div 2</div>
<div class="show-hide">div 3</div>
<div class="show-hide">div 4</div>
</code>```

```<code>$('.toggleLink').click(function(){
    $('.show-hide:eq('+ $(this).index() +')').toggle(400);
});
</code>```

It's a nice combination on pointing an index anchor to a :eq() element --> as both '0' based.

ContentLicense: CC BY-SA 3.0

Body:
There are many show/hide questions and examples but I can't find the answer.

I have a simple code like this which  is used in a few areas within a page.

jQuery(document).ready(function () {
    jQuery('#mini-cart').hide();
    jQuery('#mini-cart-a').click(function ()  {
        jQuery('#mini-cart').toggle(400);
        return false;
    });
});

Each show/hide uses its own ID, so I simply group ids like so:

jQuery('#show-hide1, #show-hide2').hide();

Problem with this method is, when I click on of the show/hid element, all of the elements show.

So I tried something like this but only the first ones works, the second ones isn't working, when I click on it, it does nothing.

jQuery(document).ready(function () {
    jQuery('show-hide1, #show-hide2').hide();
    jQuery('show-hide1 a, #show-hide2 a').click(function () {
        jQuery(this).next().toogle(400);
    }
    return false;
    });
});

There are 4 different areas that I need the show/hide within a page and  really don't want to repeat the same codes 4 times. Thanks!

Update:
(Sorry I can't use the Add Comment nor answer my question)

Thank you all, for your helpful reply.

Lee's version is more like a tabs - I don't want the hidden div associate an ID to anchor tag. It's CMS enviornment so I try to make it simpler if possible.

Andy's version has similar ID issue, so I opted in for roXon's

RoXon:
http://jsbin.com/ihoqi3/2/
Click on View Bag (2), you can see it's working, however if you go to Questions' tab, click on "Ask a question", it opens up the hidden container from View Bag.

Jeremy B's version:
http://jsbin.com/ibayu4
It hides the toggleLink's text.

From the example page, the "Choose your tea" and "Write a Review" in the Reviews Tab require similar treatment, but if I can get the above mentioned two working, the rest will take care by itself :)

Right now I use 4 separate codes to make it work.

p/s, I need to use the herf anchor because this is important for keyboard user, with the JS show/hide the hidden div can't be toggled.

Body:
Like Andy's but slightly different, to allow remove ID's as not necessary.

We can keep it simple right?

jsFiddle demo

<a href="#" class="toggleLink">1</a>
<a href="#" class="toggleLink">2</a>
<a href="#" class="toggleLink">3</a>
<a href="#" class="toggleLink">4</a>

<div class="show-hide">div 1</div>
<div class="show-hide">div 2</div>
<div class="show-hide">div 3</div>
<div class="show-hide">div 4</div>

$('.toggleLink').click(function(){
    $('.show-hide:eq('+ $(this).index() +')').toggle(400);
});

It's a nice combination on pointing an index anchor to a :eq() element --> as both '0' based.


问:
React router not open 404 not found page
I created following with react router.

```<code>import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

class Main extends Component {

render() {
        return (
    <Router>
     <Switch>
       <Route exact path='/' component={Content} />
       <Route path='/user/:id' component={User} />
       <Route path='*' component={NotFound} />
     </Switch>
    </Router>
    );
}

export default Main
</code>```

I want to open Notfound page if any invalid url.

I tried to open localhost:3000/err but, it will not go to NotFound compoenent.

My notfound component is simple.

```<code>import React from 'react';

const NotFound = () => (
    <h2>404 Page Not Found</h2>
);

export default NotFound;
</code>```

I am using "react-router-dom": "^4.3.1

答:
"react-router-dom": "^5.1.2",
```

```<Router history={history}>
  <Switch>
    <Route exact path={[routes.user.details]} component={UserProfile} />
    <Route exact path={[routes.category.collection]} component={CategoryCollection} />
    <Route exact path={[routes.category.details]} component={CategoryDetails} />
    <Route exact path={[routes.product.collection]} component={ProductCollection} />
    <Route exact path={[routes.product.details]} component={ProductDetails} />

    <Route exact path={routes.auth.login} component={Login} />
    <Route exact path={routes.auth.register} component={Register} />
    <Route exact path={routes.auth.resetPassword} component={ResetPassword} />

    <Route
      path="*"
      component={() => {
        if (user.id) {
          return <Redirect to={routes.user.details} />;
        }

        return <Redirect to={routes.auth.login} />;
      }}
    />

  </Switch>
</Router>
```

Body:
I created following with react router.

import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

class Main extends Component {

render() {
        return (
    <Router>
     <Switch>
       <Route exact path='/' component={Content} />
       <Route path='/user/:id' component={User} />
       <Route path='*' component={NotFound} />
     </Switch>
    </Router>
    );
}

export default Main

I want to open Notfound page if any invalid url.

I tried to open localhost:3000/err but, it will not go to NotFound compoenent.

My notfound component is simple.

import React from 'react';

const NotFound = () => (

404 Page Not Found

);

export default NotFound;

I am using "react-router-dom": "^4.3.1

Body:
"react-router-dom": "^5.1.2",

<Router history={history}>
  <Switch>
    <Route exact path={[routes.user.details]} component={UserProfile} />
    <Route exact path={[routes.category.collection]} component={CategoryCollection} />
    <Route exact path={[routes.category.details]} component={CategoryDetails} />
    <Route exact path={[routes.product.collection]} component={ProductCollection} />
    <Route exact path={[routes.product.details]} component={ProductDetails} />

    <Route exact path={routes.auth.login} component={Login} />
    <Route exact path={routes.auth.register} component={Register} />
    <Route exact path={routes.auth.resetPassword} component={ResetPassword} />

    <Route
      path="*"
      component={() => {
        if (user.id) {
          return <Redirect to={routes.user.details} />;
        }

        return <Redirect to={routes.auth.login} />;
      }}
    />

  </Switch>
</Router>


答:
first of all fill the empty elements and then to convert them into int. It will through the above error. so first fill all empty elements in column then apply this...

```<code>df['col'].replace('','0',inplace=True)

df['col'].astype(int)
</code>```

For example:

```<code>df=pd.DataFrame(['1','2','4','3',''])
df.replace('','0',inplace=True)
df=df.astype('int')
</code>```

Title: Python dataframe - .astype(str).astype(int) gives error ValueError: invalid literal for int() with base 10: ''

Body:
I am trying to convert a dataframe column from object to int using:

df['col'].astype(str).astype(int)

but I am getting an error

ValueError: invalid literal for int() with base 10: ''

due to the fact that some of the elements are empty. How can I deal with that and overcome / get rid off this error?

Here is what a part of my column looks like:

 0001081316
 0001081316
 0001609253
 0000928022
 0000928022
 0000916457
 0000916457
 0000916457
 0000916457
 0000016732
 0001094093
 0000911177
 0000816284
 0000816284
 0000879573
 0000018808
 0000785080
 0000018926
 0000018926
 0000018926
 0000018926
 0001319048
 0001627223
 0000895126
 0000895126
 0000895126
 0000895126
 0000895126
 0000716133
 0000716133
 0000716133
 0000716133
 0000716133
 0000020520
 0000020520
 0000020520
 0000020520
 0001400891
 0001400891
 0001400891
 0000020947
 0000764065
 0000764065
 0000764065
 0000764065
 0000764065
 0000021344
 0000021344
 0000215466
 0000215466
 0001158324
 0001323653
 0001166691
 0001166691
 0001166691
 0001166691
 0001166691
 0001166691
 0001166691
 0000918040
 0000023194
 0000023217
 0001358071
 0001163165
 0001163165
 0001710366
 0000897732
 0000016918
 0000016918
 0000732834
 0000732834
 0000024741
 0001018980
 0000025305
 0000025305
 0001051470
 0001051470
 0000912513
 0000028630
 0000916540
 0000931336
 0001571996
 0000027904
 0000027996
 0001090012
 0001090012
 0001090012
 0001090012
 0000949039
 0000949039
 0000949039
 0000715957
 0000715957
 0000029669
 0000029669
 0000029669
 0000029669
 0000029669
 0000029669
 0000029669
 0000029669
 0000030554
 0000030554
 0000030554
 0000030554
 0001326160
 0001326160
 0001092839
 0000821189
 0000821189
 0000821189
 0000821189
 0000821189
 0000821189
 0000750199
 0000033213
 0000033213
 0000915389
 0001600470
 0001066107
 0001066107
 0001590895
 0000032604
 0000032604
 0001591763
 0001591763
 0000880285
 0000880285
 0000880285
 0001161154
 0001161154
 0001161154
 0001024401
 0001024401
 0000033619
 0001532063
 0001532063
 0001532063
 0000887936
 0001062613
 0000880430
 0000880430
 0000038074
 0000038074

 0000831259
 0000831259
 0000831259
 0000831259

Body:
first of all fill the empty elements and then to convert them into int. It will through the above error. so first fill all empty elements in column then apply this...

df['col'].replace('','0',inplace=True)

df['col'].astype(int)

For example:

df=pd.DataFrame(['1','2','4','3',''])
df.replace('','0',inplace=True)
df=df.astype('int')


问:
Correct way to cancel TPL data flow block
I am using TPL blocks to carry out operation that may be cancelled by user:
I have come up with two options, in first I cancel whole block but don't cancel operation inside the block, like this:

```<code>_downloadCts = new CancellationTokenSource();

var processBlockV1 = new TransformBlock<int, List<int>>(construct =>
{
    List<int> properties = GetPropertiesMethod(construct );
    var entities = properties
        .AsParallel()
        .Select(DoSometheningWithData)
        .ToList();
    return entities;
}, new ExecutionDataflowBlockOptions() { CancellationToken = _downloadCts.Token });
</code>```

and the second I cancel inside operation, but not the block itself:

```<code>var processBlockV2 = new TransformBlock<int, List<int>>(construct =>
{
    List<int> properties = GetPropertiesMethod(construct);
    var entities = properties
        .AsParallel().WithCancellation(_downloadCts.Token)
        .Select(DoSometheningWithData)
        .ToList();
    return entities;
});
</code>```

As I understand, first option will cancel whole block, thus shutting down the whole pipeline. My question is will it also cancel inside operation and dispose of all resources if there are any(open StreamReaders, ect.) or is it better to choose second option for then I myself can make sure everything is cancelled and cleaned and then I could use some means(railway programming) to float raised OperationCanceledException down the pipe and deal with it where I want?

答:
These two options are not equivalent.

The first option (CancellationToken = _downloadCts.Token) will make the processBlockV1 block to discard any messages that are currently in its buffer (its InputCount property will become 0), and stop accepting new messages (invoking its Post method will invariably return false). It will not stop processing the messages that are currently in progress though. These will be processed fully, but will not be propagated to any linked blocks. After these messages are processed, the block will complete in a canceled state (its Completion.Status property will become Canceled).

The second option (canceling the inside operations) will have no effect to the block as a whole. The Dataflow blocks tolerate any OperationCanceledException thrown from their processing function, and just ignore the faulted item and proceed with the next one. So after the cancellation of the token, all posted messages are still going to be processed, and the block will continue accepting more. It just won't propagate anything to its linked blocks, because all items will throw the OperationCanceledException and get ignored. In the specific example the GetPropertiesMethod method will be invoked for all construct messages, and so will impose a delay to the completion of the block. The final state of the block will be RanToCompletion.

It is important to know that the Dataflow blocks are taking seriously the concept of Completion. They will wait for everything that they know to stop running before reporting completion. In case you do want them to complete prematurely and leave behind tasks that are still running, you'll have to do tricks like wrapping your tasks with cancelable wrappers.

Body:
I am using TPL blocks to carry out operation that may be cancelled by user:
I have come up with two options, in first I cancel whole block but don't cancel operation inside the block, like this:

_downloadCts = new CancellationTokenSource();

var processBlockV1 = new TransformBlock<int, List<int>>(construct =>
{
    List<int> properties = GetPropertiesMethod(construct );
    var entities = properties
        .AsParallel()
        .Select(DoSometheningWithData)
        .ToList();
    return entities;
}, new ExecutionDataflowBlockOptions() { CancellationToken = _downloadCts.Token });

and the second I cancel inside operation, but not the block itself:

var processBlockV2 = new TransformBlock<int, List<int>>(construct =>
{
    List<int> properties = GetPropertiesMethod(construct);
    var entities = properties
        .AsParallel().WithCancellation(_downloadCts.Token)
        .Select(DoSometheningWithData)
        .ToList();
    return entities;
});

As I understand, first option will cancel whole block, thus shutting down the whole pipeline. My question is will it also cancel inside operation and dispose of all resources if there are any(open StreamReaders, ect.) or is it better to choose second option for then I myself can make sure everything is cancelled and cleaned and then I could use some means(railway programming) to float raised OperationCanceledException down the pipe and deal with it where I want?


问:
Qt: Correct way to post events to a QThread?
In my Qt application, I have a main thread and a worker thread. The worker thread subclasses QThread and processes events via customEvent. Is this the correct way for the main thread to send events to be processed by the worker thread?

```<code>QThread* myWorkerThread = // ...

QApplication::instance()->postEvent (myWorkerThread, new MyWorkRequestEvent(/* ... */);
</code>```

If I read the documentation correctly, it states that events are processed on the thread of the object that own the event recipient.  Since QThread was created by the main thread, it is owned by the main thread -- so would this event be processed by the main thread (which would be counter-intuitive, and in my case would be wrong)?

答:
Your understanding is correct and is indeed very unintuitive :)

A lot of the trouble comes from the documentation for QThread that suggests subclassing QThread. Although Qthread has its own event loop, only events and signals for QObjects created in the run() method (created in that thread) will be processed in the QThread event loop.

It is much better to encapsulate your thread logic in a QObject subclass and then move that object to an instance of a plain QThread. You can then communicate with that QObject using signals (which will be correctly queued across thread boundaries) or custom events.

There are some links in this similar question that should help.

Body:
In my Qt application, I have a main thread and a worker thread. The worker thread subclasses QThread and processes events via customEvent. Is this the correct way for the main thread to send events to be processed by the worker thread?

QThread* myWorkerThread = // ...

QApplication::instance()->postEvent (myWorkerThread, new MyWorkRequestEvent(/* ... */);

If I read the documentation correctly, it states that events are processed on the thread of the object that own the event recipient.  Since QThread was created by the main thread, it is owned by the main thread -- so would this event be processed by the main thread (which would be counter-intuitive, and in my case would be wrong)?


问:
What prediction format should be the input for ROC function
I am trying to calculate the ROC of a target variable that is binary(0,1) versus a decision tree prediction.

When I set the prediction value to be binary, it gives me the following error:

```<code>> roc(as.numeric(pred),as.numeric(data$target))

Setting levels: control = 0, case = 1
Setting direction: controls < cases
</code>```

When I set the prediction value to be a probability, it gives me the following error:

```<code>> roc(pred[,2],as.numeric(data$target))

'response' has more than two levels. Consider setting 'levels'
explicitly or using 'multiclass.roc' insteadSetting levels:
control = 0.166666666666667, case = 0.232876712328767
Setting direction: controls < cases
</code>```

So I am confused about what format should I set to the prediction to so that the ROC is calculated correctly? Why is my function showing these errors?

答:
If you look at pROC's roc function documentation, you will see that the formal definition has the following form:

```<code>## Default S3 method:
roc(response, predictor, [...]
</code>```

The prediction is therefore the second argument, not the first as you are using. Therefore your call should look like:

```<code>roc(data$target, pred[,2])
</code>```

If you forget the order you can always use named argument in order to ignore the order:

```<code>roc(predictor = pred[,2], response = data$target)
</code>```

Also note it is not necessary and even not recommended to convert the response to a numeric vector, so I removed as.numeric from the calls above.

Body:
I am trying to calculate the ROC of a target variable that is binary(0,1) versus a decision tree prediction.

When I set the prediction value to be binary, it gives me the following error:

> roc(as.numeric(pred),as.numeric(data$target))

Setting levels: control = 0, case = 1
Setting direction: controls < cases

When I set the prediction value to be a probability, it gives me the following error:

> roc(pred[,2],as.numeric(data$target))

'response' has more than two levels. Consider setting 'levels'
explicitly or using 'multiclass.roc' insteadSetting levels:
control = 0.166666666666667, case = 0.232876712328767
Setting direction: controls < cases

So I am confused about what format should I set to the prediction to so that the ROC is calculated correctly? Why is my function showing these errors?

Body:
If you look at pROC's roc function documentation, you will see that the formal definition has the following form:

## Default S3 method:
roc(response, predictor, [...]

The prediction is therefore the second argument, not the first as you are using. Therefore your call should look like:

roc(data$target, pred[,2])

If you forget the order you can always use named argument in order to ignore the order:

roc(predictor = pred[,2], response = data$target)

Also note it is not necessary and even not recommended to convert the response to a numeric vector, so I removed as.numeric from the calls above.