问:
Why do we need [basic.scope.class]/2?
I understand all the errors shown in the example in [basic.scope.class]/5 refer to [basic.scope.class]/2.

[basic.scope.class]/2:

A name N used in a class S shall refer to the same declaration in its
  context and when re-evaluated in the completed scope of S. No
  diagnostic is required for a violation of this rule.

But what I'd like to know is why do we need such a rule in the language in the first place?

For instance, consider the first example in [basic.scope.class]/5:

What would be problem if the language allowed this, i.e., v[i] an array of one element below

```<code>enum { i = 1 };

class X {
  char  v[i];
  enum { i = 2 };
};
</code>```

and an array of two elements in the example that follows?

```<code>enum { i = 1 };

class X {
  enum { i = 2 };
  char  v[i];
};
</code>```

答:
Two reasons, at least.

First, that enum { i = 1 }; might not be present in every translation unit that includes the header that defines X. The result would be conflicting definitions of X.

Second, suppose that, in your first example, the class also has a member function defined after the array:

```<code>void show() const {
    for (int idx = 0; idx < i; ++idx)
        std::cout << v[idx];
}
</code>```

How is the compiler supposed to figure out that the i here should be the same as the first i and not the second?

Title: Why do we need [basic.scope.class]/2?

Body:
I understand all the errors shown in the example in [basic.scope.class]/5 refer to [basic.scope.class]/2.

[basic.scope.class]/2:

A name N used in a class S shall refer to the same declaration in its
  context and when re-evaluated in the completed scope of S. No
  diagnostic is required for a violation of this rule.

But what I'd like to know is why do we need such a rule in the language in the first place?

For instance, consider the first example in [basic.scope.class]/5:

What would be problem if the language allowed this, i.e., v[i] an array of one element below

enum { i = 1 };

class X {
  char  v[i];
  enum { i = 2 };
};

and an array of two elements in the example that follows?

enum { i = 1 };

class X {
  enum { i = 2 };
  char  v[i];
};

Body:
Two reasons, at least.

First, that enum { i = 1 }; might not be present in every translation unit that includes the header that defines X. The result would be conflicting definitions of X.

Second, suppose that, in your first example, the class also has a member function defined after the array:

void show() const {
    for (int idx = 0; idx < i; ++idx)
        std::cout << v[idx];
}

How is the compiler supposed to figure out that the i here should be the same as the first i and not the second?


来源: stackexchange

问:
How to create a form with checkboxes and a hoverable dropdown menu to chose action
I would like to implement the following. A table with a checkbox in a cell for every row. To submit the form a dropdown menu offers the different actions to take (move, delete, etc).

It would look like:

The submit button would be a hoverable dropdown with different actions:

The working code for the table:

```<code><form action="/action_page.php" method="get">
    <input type="submit" value="Submit">
    <table>
      @foreach ($tags as $tag)
      <tr>
        <td>
           <br>{{$tag->title}}</br>
        </td>
        <td>
            <input type="checkbox" name={{$tag->title}} value="true"><br>
        </td>
      </tr>
      @endforeach
    </table>
  </form>
</code>```

source: https://www.w3schools.com/tags/att_input_checked.asp

Potential code for the hoverable menu:

```<code><div class="dropdown">
  <button class="dropbtn">Dropdown</button>
  <div class="dropdown-content">
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>
  </div>
</div>
</code>```

source: https://www.w3schools.com/howto/howto_css_dropdown.asp

How could this be achieved? A form has only one action for the button and how to make the submit button into a hoverable dropdown?

Thank you.

答:
I think you're searching for something like this:

```<code><html>
<head>
    <link rel="stylesheet" type="text/css" href="css.css">
</head>
<body>
    <form method="POST" action="mypage.php">
    <div class="dropdown">
      <input type="submit" value="dropdown" />
            <div class="dropdown-content">
                <table border="1" style="width: 160px;">
                <tr>
                    <td>rugby</td>
                    <td><input type="checkbox" value="rugby" name="sport[]"/></td>
                </tr>
                <tr>
                    <td>tennis</td>
                    <td><input type="checkbox" value="tennis" name="sport[]" /></td>
                </tr>
                </table>
            </div>
    </div>
    </form>
</body>
</html>
</code>```

You select elements from the dropdown menu and then you click on the button sumbit to send them to a PHP page as an array. The css I've used is the same shown in the link of the dropdown menu.
This is the result:

Hope it helps.

ContentLicense: CC BY-SA 3.0

Body:
I would like to implement the following. A table with a checkbox in a cell for every row. To submit the form a dropdown menu offers the different actions to take (move, delete, etc).

It would look like:

The submit button would be a hoverable dropdown with different actions:

The working code for the table:

<form action="/action_page.php" method="get">
    <input type="submit" value="Submit">

      @foreach ($tags as $tag)

{{$tag->title}}

            <input type="checkbox" name={{$tag->title}} value="true">

      @endforeach

  </form>

source: https://www.w3schools.com/tags/att_input_checked.asp

Potential code for the hoverable menu:

  <button class="dropbtn">Dropdown</button>

    Link 1
    Link 2
    Link 3

source: https://www.w3schools.com/howto/howto_css_dropdown.asp

How could this be achieved? A form has only one action for the button and how to make the submit button into a hoverable dropdown?

Thank you.

Body:
I think you're searching for something like this:

<html>
<head>
    <link rel="stylesheet" type="text/css" href="css.css">
</head>
<body>
    <form method="POST" action="mypage.php">
    <div class="dropdown">
      <input type="submit" value="dropdown" />
            <div class="dropdown-content">
                <table border="1" style="width: 160px;">
                <tr>
                    <td>rugby</td>
                    <td><input type="checkbox" value="rugby" name="sport[]"/></td>
                </tr>
                <tr>
                    <td>tennis</td>
                    <td><input type="checkbox" value="tennis" name="sport[]" /></td>
                </tr>
                </table>
            </div>
    </div>
    </form>
</body>
</html>

You select elements from the dropdown menu and then you click on the button sumbit to send them to a PHP page as an array. The css I've used is the same shown in the link of the dropdown menu.
This is the result:

Hope it helps.


问:
How to use the wizard to replicate 2 tables into one using a join?
I have one app with one database, and I need to make a replication of some of those tables, and also include one new table which is a join of more than one of those tables.

I tried transaction replication, but the filter for the tables only allows me to modify the 'where' clause.

Anybody can help me with this?

答: I'd replicate the two tables in question as-is, then create a view on the subscriber to represent your desired join.</p>

ContentLicense: CC BY-SA 2.5


问:
Mysql sum all columns starting with some letters
I am trying add one column in my Mysql database that sums all the columns starting by 'tokenvalid' which can take the value of 1 or 0.

And let's say I have 50 columns like that in my database (i.e. tokenvalid1, tokenvalid2 ...., tokenvalide50) with other columns between.

Please find below the code I would like to implement. I know that is not correct at all but it is just to give you an idea of what I am trying to do.
Thank you for your help!

```<code>'SELECT *, sum(column_name LIKE "tokenvalid"%) as total FROM points WHERE 1'
</code>```

答:
This post should help you. The post describes how to get the columns and then query for results.

MySQL Like statement in SELECT column_name

Body:
I am trying add one column in my Mysql database that sums all the columns starting by 'tokenvalid' which can take the value of 1 or 0.

And let's say I have 50 columns like that in my database (i.e. tokenvalid1, tokenvalid2 ...., tokenvalide50) with other columns between.

Please find below the code I would like to implement. I know that is not correct at all but it is just to give you an idea of what I am trying to do.
Thank you for your help!

'SELECT *, sum(column_name LIKE "tokenvalid"%) as total FROM points WHERE 1'


问:
How to get Active status based on status field in sql?

Suppose there is active and inactive state in 2 rows

```<code>select * from table name where status in (Active,Inactive);
</code>```

If active status is there need to consider that as 1st priority else need to get Inactive state

Could any one suggest some solution

```<code>    SCH_NAME,   STATE,  VER
</code>```

1   pk  Planned 2

2   pk  Active 1

答:
I assume that (sch_name, ver) is the primary key.

Here's my solution:

Assign an id to every status (1: Active, 2: Planned/Passive)

For every row get the minimum status id for (sch_name) field and for the (sch_name, ver) fields

Return only the rows where the two values are equals

It works because:

if a sch_name has an "Active" row, that will be the minimal status id (so no passive row wil be returned for that sch_name).

if a sch_name doesn't have an "Active" row, the minimal status id will be the one assigned to "Passive", so only "Passive" rows will be returned

```<code>create table user3231655
(
   schname varchar2(20),
   st   varchar2(20),
   vr   integer
 );

 delete user3231655;
 insert into user3231655 values ('pk','Active',1);
 insert into user3231655 values ('pk','Planned',2);
 insert into user3231655 values ('fk','Planned',2);

 select * from (
 select a.*, min(case st when 'Active' then 1 when 'Planned' then 2 end) ver (partition by schname) as min1,
         min(case st when 'Active' then 1 when 'Planned' then 2 end) ver (partition by schname, vr) as min2
 from user3231655 a
 ) b
 where min1=min2
</code>```

There are surely more elegant ways to solve it.

Body:
Suppose there is active and inactive state in 2 rows

select * from table name where status in (Active,Inactive);

If active status is there need to consider that as 1st priority else need to get Inactive state

Could any one suggest some solution

    SCH_NAME,   STATE,  VER

1   pk  Planned 2

2   pk  Active 1

Body:
I assume that (sch_name, ver) is the primary key.

Here's my solution:

Assign an id to every status (1: Active, 2: Planned/Passive)

For every row get the minimum status id for (sch_name) field and for the (sch_name, ver) fields

Return only the rows where the two values are equals

It works because:

if a sch_name has an "Active" row, that will be the minimal status id (so no passive row wil be returned for that sch_name).

if a sch_name doesn't have an "Active" row, the minimal status id will be the one assigned to "Passive", so only "Passive" rows will be returned

create table user3231655
(
   schname varchar2(20),
   st   varchar2(20),
   vr   integer
 );

 delete user3231655;
 insert into user3231655 values ('pk','Active',1);
 insert into user3231655 values ('pk','Planned',2);
 insert into user3231655 values ('fk','Planned',2);

 select * from (
 select a.*, min(case st when 'Active' then 1 when 'Planned' then 2 end) ver (partition by schname) as min1,
         min(case st when 'Active' then 1 when 'Planned' then 2 end) ver (partition by schname, vr) as min2
 from user3231655 a
 ) b
 where min1=min2

There are surely more elegant ways to solve it.


问:
How to flush the print buffer in R?
I want to run a long-running simulation and have updates printed periodically. However, I am finding that my print statements are being buffered, even when I explicitly try to flush. Here, for example:

```<code>for (i in 1:10)
{
    print(i)
    flush(stdout())
    Sys.sleep(1)
}
</code>```

I would expect this to increment every 1sec, but it outputs everything at the end, after 10 seconds.

How would you force a flush of the print buffer?

答:
I usually do it like this:</p>

```<code>for (i in 1:10) {
    message(i,"\r",appendLF=FALSE)
    flush.console()
    Sys.sleep(1)
}
</code>```

Title: How to flush the print buffer in R?

Body:
I want to run a long-running simulation and have updates printed periodically. However, I am finding that my print statements are being buffered, even when I explicitly try to flush. Here, for example:

for (i in 1:10)
{
    print(i)
    flush(stdout())
    Sys.sleep(1)
}

I would expect this to increment every 1sec, but it outputs everything at the end, after 10 seconds.

How would you force a flush of the print buffer?

Body:
I usually do it like this:

for (i in 1:10) {
    message(i,"\r",appendLF=FALSE)
    flush.console()
    Sys.sleep(1)
}


问:
node.js share dynamic variables between modules
I have a variable named number_of_clusters which must be updated periodically. number_of_clusters must also be shared with other modules to read it. how can I assure that reading modules will read a fresh copy of this variable each time they access that?
I dont want to use database to share this variable so I thought I could share it via process.env

```<code>process.env.number_of_clusters = 1;
</code>```

is it a good practice?

答: You could use socket.io to store the variable on the server and have it emit to all pages.</p>

Body:
I have a variable named number_of_clusters which must be updated periodically. number_of_clusters must also be shared with other modules to read it. how can I assure that reading modules will read a fresh copy of this variable each time they access that?
I dont want to use database to share this variable so I thought I could share it via process.env

process.env.number_of_clusters = 1;

is it a good practice?


问:
Returning array without given object
I have the following interfaces in my Angular app:

```<code>interface Reservation {
  id: string;
  from: Date;
  to: Date;
}

interface Bedroom {
  id: string;
  reservations: Array < Reservation > ;
}

interface House {
  id: string;
  bedrooms: Array < Bedroom >;
}
</code>```

At some point, I have to delete a Reservation from within a certain Bedroom from within the Array of Houses and return a copy of the whole House Array only without that deleted Reservation item.

I cannot mutate the existing Array of Houses. How should I do this?

答:
You should use splice method on your array, combinet with clone of object (ie provided by underscore.js):
https://www.w3schools.com/jsref/jsref_splice.asp
http://underscorejs.org/#clone

It would be something (I did not check that code) like this:

```<code>import * as _ from 'underscore';
removeReservation(bedroom: Bedroom, reservation: Reservation): Bedroom {
    let position = bedroom.reservations.findIndex(checkingRes => {
         return checkingRes.id == reservation.id
    });
    let bedroomCopy = _.clone(bedroom);
    bedroomCopy.reservations.splice(position, position + 1);
    return bedroomCopy;
}
</code>```

If you want to pernamently delete reservation, you just ommit the clone operation.

```<code>removeReservation(bedroom: Bedroom, reservation: Reservation): Bedroom {
    let position = bedroom.reservations.findIndex(checkingRes => {
         return checkingRes.id == reservation.id
    });
    bedroom.reservations.splice(position, position + 1);
    return bedroom;
}
</code>```

Title: Returning array without given object

Body:
I have the following interfaces in my Angular app:

interface Reservation {
  id: string;
  from: Date;
  to: Date;
}

interface Bedroom {
  id: string;
  reservations: Array < Reservation > ;
}

interface House {
  id: string;
  bedrooms: Array < Bedroom >;
}

At some point, I have to delete a Reservation from within a certain Bedroom from within the Array of Houses and return a copy of the whole House Array only without that deleted Reservation item.

I cannot mutate the existing Array of Houses. How should I do this?

Body:
You should use splice method on your array, combinet with clone of object (ie provided by underscore.js):
https://www.w3schools.com/jsref/jsref_splice.asp
http://underscorejs.org/#clone

It would be something (I did not check that code) like this:

import * as _ from 'underscore';
removeReservation(bedroom: Bedroom, reservation: Reservation): Bedroom {
    let position = bedroom.reservations.findIndex(checkingRes => {
         return checkingRes.id == reservation.id
    });
    let bedroomCopy = _.clone(bedroom);
    bedroomCopy.reservations.splice(position, position + 1);
    return bedroomCopy;
}

If you want to pernamently delete reservation, you just ommit the clone operation.

removeReservation(bedroom: Bedroom, reservation: Reservation): Bedroom {
    let position = bedroom.reservations.findIndex(checkingRes => {
         return checkingRes.id == reservation.id
    });
    bedroom.reservations.splice(position, position + 1);
    return bedroom;
}


问:
build maven project with propriatery libraries included
How to create maven pom, which will make project buildable, can I include propriatery jars with my project directly without having to take them from repository? anyone did this before ?

EDIT :

I don't want to make it runnable by building assembly with dependencies jar, I want it to be buildable. So anyone having this project is able to build it, even if jars are nowhere to be found at any repository.

答:
1 Either you can include that jar in your classpath of application

2 you can install particular jar file in your maven reopos by

```<code>mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> \
    -DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging>
</code>```

Body:
1 Either you can include that jar in your classpath of application

2 you can install particular jar file in your maven reopos by

mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> \
    -DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging>


问:
Getting specific fields' values of a text using awk, sed, and grep
I would like to get the values of the name fields of the following text, using sed, awk, grep or similar.

```<code>{
    "cast": [
        {
            "character": "",
            "credit_id": "52532e3119c29579400012b5",
            "gender": null,
            "id": 23629,
            "name": "Brian O'Halloran",
            "order": 0,
            "profile_path": "/eJsLxovTdcm6QK9PDB2pCe5FMqK.jpg"
        },
        {
            "character": "",
            "credit_id": "52532e3119c2957940001315",
            "gender": null,
            "id": 19302,
            "name": "Jason Mewes",
            "order": 1,
            "profile_path": "/so3nT2vgSCZMO2QXDVHF3ubxaFX.jpg"
        },
        {
            "character": "",
            "credit_id": "52532e3119c295794000133d",
            "gender": null,
            "id": 23630,
            "name": "Jeff Anderson",
            "order": 2,
            "profile_path": "/vjt5WhpJAx0jxvmiGc5PAOBzzb7.jpg"
        },
        {
            "character": "Silent Bob",
            "credit_id": "52532e3219c2957940001359",
            "gender": null,
            "id": 19303,
            "name": "Kevin Smith",
            "order": 4,
            "profile_path": "/3XXThSMqHQgQFjM4bMJ25U1EJTj.jpg"
        }
    ],
    "crew": [
        {
            "credit_id": "55425dbe9251410efa000094",
            "department": "Visual Effects",
            "gender": null,
            "id": 1419667,
            "job": "Animation Manager",
            "name": "Richard J. Gasparian",
            "profile_path": null
        },
        {
            "credit_id": "5544521dc3a3680ce60037e8",
            "department": "Art",
            "gender": null,
            "id": 1450356,
            "job": "Background Designer",
            "name": "Tristin Cole",
            "profile_path": null
        },
        {
            "credit_id": "554a142dc3a3683c84001851",
            "department": "Art",
            "gender": null,
            "id": 1447432,
            "job": "Background Designer",
            "name": "Nadia Vurbenova",
            "profile_path": null
        },
        {
            "credit_id": "554bcd2b9251414692002c9b",
            "department": "Production",
            "gender": null,
            "id": 1447493,
            "job": "Location Manager",
            "name": "Simon Rodgers",
            "profile_path": null
        },
        {
            "credit_id": "52532e3219c29579400013cd",
            "department": "Production",
            "gender": null,
            "id": 19303,
            "job": "Executive Producer",
            "name": "Kevin Smith",
            "profile_path": "/3XXThSMqHQgQFjM4bMJ25U1EJTj.jpg"
        },
        {
            "credit_id": "52532e3319c2957940001405",
            "department": "Production",
            "gender": null,
            "id": 59839,
            "job": "Producer",
            "name": "Harvey Weinstein",
            "profile_path": "/k4UCnh7n0r5CEjq30gAl6QCfF9g.jpg"
        },
        {
            "credit_id": "52532e3319c29579400014a7",
            "department": "Production",
            "gender": null,
            "id": 1307,
            "job": "Producer",
            "name": "Bob Weinstein",
            "profile_path": "/oe5Oxp034UOubnvZqqhurp6a1EP.jpg"
        }
    ],
    "id": 2
}
</code>```

答:
You should parse the JSON file rather than use a regex.

You can use Ruby to do:

```<code>$ ruby -0777 -r json -lane '
                   d=JSON.parse($_)
                  (d["cast"]+d["crew"]).each { |x| p x["name"] }' json
"Brian O'Halloran"
"Jason Mewes"
"Jeff Anderson"
"Kevin Smith"
"Richard J. Gasparian"
"Tristin Cole"
"Nadia Vurbenova"
"Simon Rodgers"
"Kevin Smith"
"Harvey Weinstein"
"Bob Weinstein"
</code>```

Or if you want to separate cast from crew:

```<code>$ ruby -0777 -r json -lane '
                   d=JSON.parse($_)
                   %w(cast crew).each {|w|
                   puts "#{w.capitalize}:"
                  (d[w]).each { |x| puts "\t#{x["name"]}" }}' json
Cast:
    Brian O'Halloran
    Jason Mewes
    Jeff Anderson
    Kevin Smith
Crew:
    Richard J. Gasparian
    Tristin Cole
    Nadia Vurbenova
    Simon Rodgers
    Kevin Smith
    Harvey Weinstein
    Bob Weinstein
</code>```

Body:
I would like to get the values of the name fields of the following text, using sed, awk, grep or similar.

{
    "cast": [
        {
            "character": "",
            "credit_id": "52532e3119c29579400012b5",
            "gender": null,
            "id": 23629,
            "name": "Brian O'Halloran",
            "order": 0,
            "profile_path": "/eJsLxovTdcm6QK9PDB2pCe5FMqK.jpg"
        },
        {
            "character": "",
            "credit_id": "52532e3119c2957940001315",
            "gender": null,
            "id": 19302,
            "name": "Jason Mewes",
            "order": 1,
            "profile_path": "/so3nT2vgSCZMO2QXDVHF3ubxaFX.jpg"
        },
        {
            "character": "",
            "credit_id": "52532e3119c295794000133d",
            "gender": null,
            "id": 23630,
            "name": "Jeff Anderson",
            "order": 2,
            "profile_path": "/vjt5WhpJAx0jxvmiGc5PAOBzzb7.jpg"
        },
        {
            "character": "Silent Bob",
            "credit_id": "52532e3219c2957940001359",
            "gender": null,
            "id": 19303,
            "name": "Kevin Smith",
            "order": 4,
            "profile_path": "/3XXThSMqHQgQFjM4bMJ25U1EJTj.jpg"
        }
    ],
    "crew": [
        {
            "credit_id": "55425dbe9251410efa000094",
            "department": "Visual Effects",
            "gender": null,
            "id": 1419667,
            "job": "Animation Manager",
            "name": "Richard J. Gasparian",
            "profile_path": null
        },
        {
            "credit_id": "5544521dc3a3680ce60037e8",
            "department": "Art",
            "gender": null,
            "id": 1450356,
            "job": "Background Designer",
            "name": "Tristin Cole",
            "profile_path": null
        },
        {
            "credit_id": "554a142dc3a3683c84001851",
            "department": "Art",
            "gender": null,
            "id": 1447432,
            "job": "Background Designer",
            "name": "Nadia Vurbenova",
            "profile_path": null
        },
        {
            "credit_id": "554bcd2b9251414692002c9b",
            "department": "Production",
            "gender": null,
            "id": 1447493,
            "job": "Location Manager",
            "name": "Simon Rodgers",
            "profile_path": null
        },
        {
            "credit_id": "52532e3219c29579400013cd",
            "department": "Production",
            "gender": null,
            "id": 19303,
            "job": "Executive Producer",
            "name": "Kevin Smith",
            "profile_path": "/3XXThSMqHQgQFjM4bMJ25U1EJTj.jpg"
        },
        {
            "credit_id": "52532e3319c2957940001405",
            "department": "Production",
            "gender": null,
            "id": 59839,
            "job": "Producer",
            "name": "Harvey Weinstein",
            "profile_path": "/k4UCnh7n0r5CEjq30gAl6QCfF9g.jpg"
        },
        {
            "credit_id": "52532e3319c29579400014a7",
            "department": "Production",
            "gender": null,
            "id": 1307,
            "job": "Producer",
            "name": "Bob Weinstein",
            "profile_path": "/oe5Oxp034UOubnvZqqhurp6a1EP.jpg"
        }
    ],
    "id": 2
}

Body:
You should parse the JSON file rather than use a regex.

You can use Ruby to do:

$ ruby -0777 -r json -lane '
                   d=JSON.parse($_)
                  (d["cast"]+d["crew"]).each { |x| p x["name"] }' json
"Brian O'Halloran"
"Jason Mewes"
"Jeff Anderson"
"Kevin Smith"
"Richard J. Gasparian"
"Tristin Cole"
"Nadia Vurbenova"
"Simon Rodgers"
"Kevin Smith"
"Harvey Weinstein"
"Bob Weinstein"

Or if you want to separate cast from crew:

$ ruby -0777 -r json -lane '
                   d=JSON.parse($_)
                   %w(cast crew).each {|w|
                   puts "#{w.capitalize}:"
                  (d[w]).each { |x| puts "\t#{x["name"]}" }}' json
Cast:
    Brian O'Halloran
    Jason Mewes
    Jeff Anderson
    Kevin Smith
Crew:
    Richard J. Gasparian
    Tristin Cole
    Nadia Vurbenova
    Simon Rodgers
    Kevin Smith
    Harvey Weinstein
    Bob Weinstein


问:
Calling event click with JavaScript
It is possible to call a event click with JavaScript? how?

I'm trying to call this event when a button get clicked.

I'm creating Buttons dynamically so the id's change constantly

Here is how i make the buttons dynamically and assign the event click

```<code>protected void Page_Init(object sender, EventArgs e)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "showAndHide();", true);

            Button Btn_clic = (Button)sender;
            var name = Btn_clic.Text;

            List.ListUsers listArea = new List.ListUsers();
            List<Data.Area> Area = listArea.AreaList();

            List<Data.Area> ListOfEquiposOk = Area.Where(x => x.AREA == name && x.STANDBY == 0).ToList();

            List<Button> Botones = new List<Button>();

            var TeamFCH = ListOfEquiposOk.Select(x => x.TEAM).Distinct().ToList();

            foreach (var team in TeamFCH)
            {
                Button newButton = new Button();
                newButton.CommandName = "Btn" + Convert.ToString(team);
                newButton.ID = "Btn_" + Convert.ToString(team);
                newButton.Text = team;
                newButton.CommandArgument = name;

                newButton.Click += new System.EventHandler(newButton_Click);

                Botones.Add(newButton);

                GoodPanel.Controls.Add(newButton);
                newButton.CssClass = "btn-primary outline separate";
            }
        }

protected void newButton_Click(object sender, EventArgs e)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ModalGood();", true);

            Button Btnclick = (Button)sender;
            var team = Btnclick.Text;
            string name = Btnclick.CommandArgument;

            List.ListUsers listArea = new List.ListUsers();
            List<Data.Area> Area = listArea.AreaList();

            List<Data.Area> ListOfToolsOk = Area.Where(x => x.AREA == name && x.TEAM == team && x.STANDBY == 0).ToList();

            var ToolArea = ListOfToolsOk.Select(x => x.TEAM);
            Grv_Eng.DataSource = ListOfToolsOk;
            Grv_Eng.DataBind();
        }
</code>```

答:
If you want to assign a OnClick event, do it like this.

```<code>Button Btnclick = new Button();
Btnclick.Click += newButton_Click;
Btnclick.Text = "MyButton";
Btnclick.ID = "MyButtonID";

PlaceHolder1.Controls.Add(Btnclick);
</code>```

And if you want to reference the dynamic ID, use FindControl and ClientID on the aspx page.

```<code>document.getElementById("<%= PlaceHolder1.FindControl("MyButtonID").ClientID %>").click
</code>```

Title: Calling event click with JavaScript

Body:
It is possible to call a event click with JavaScript? how?

I'm trying to call this event when a button get clicked.

I'm creating Buttons dynamically so the id's change constantly

Here is how i make the buttons dynamically and assign the event click

protected void Page_Init(object sender, EventArgs e)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "showAndHide();", true);

            Button Btn_clic = (Button)sender;
            var name = Btn_clic.Text;

            List.ListUsers listArea = new List.ListUsers();
            List<Data.Area> Area = listArea.AreaList();

            List<Data.Area> ListOfEquiposOk = Area.Where(x => x.AREA == name && x.STANDBY == 0).ToList();

            List<Button> Botones = new List<Button>();

            var TeamFCH = ListOfEquiposOk.Select(x => x.TEAM).Distinct().ToList();

            foreach (var team in TeamFCH)
            {
                Button newButton = new Button();
                newButton.CommandName = "Btn" + Convert.ToString(team);
                newButton.ID = "Btn_" + Convert.ToString(team);
                newButton.Text = team;
                newButton.CommandArgument = name;

                newButton.Click += new System.EventHandler(newButton_Click);

                Botones.Add(newButton);

                GoodPanel.Controls.Add(newButton);
                newButton.CssClass = "btn-primary outline separate";
            }
        }

protected void newButton_Click(object sender, EventArgs e)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ModalGood();", true);

            Button Btnclick = (Button)sender;
            var team = Btnclick.Text;
            string name = Btnclick.CommandArgument;

            List.ListUsers listArea = new List.ListUsers();
            List<Data.Area> Area = listArea.AreaList();

            List<Data.Area> ListOfToolsOk = Area.Where(x => x.AREA == name && x.TEAM == team && x.STANDBY == 0).ToList();

            var ToolArea = ListOfToolsOk.Select(x => x.TEAM);
            Grv_Eng.DataSource = ListOfToolsOk;
            Grv_Eng.DataBind();
        }

Body:
If you want to assign a OnClick event, do it like this.

Button Btnclick = new Button();
Btnclick.Click += newButton_Click;
Btnclick.Text = "MyButton";
Btnclick.ID = "MyButtonID";

PlaceHolder1.Controls.Add(Btnclick);

And if you want to reference the dynamic ID, use FindControl and ClientID on the aspx page.

document.getElementById("<%= PlaceHolder1.FindControl("MyButtonID").ClientID %>").click


问:
How to make if statement with null parameter?
How do you make an if statement check if something is null, and will return null if the if statement is true?     </p>

```<code>public String getMiddle(String word)
   {
      // I don't know if 'is null' or 'return null' are actually things
      if (is null){
         return null;
      }
   }
</code>```

<p>Also, what would be an example of an input that would make it null? </p>

答:
As Aominè and litelite both said(in the same way at the same time), you can just do this:

```<code>if(word == null) return null;
</code>```

And your second question:

Also, what would be an example of an input that would make it null?

If you call the method like getMiddle(null), then that would be possible.

Here are a bunch of ways to check if a word is null:

1:

```<code>private static void getWord(String str){
    try {
        if(!str.equals("")) {
            System.out.println(str);
        }
    } catch (NullPointerException e) {
        System.out.println("Your word was null.");
    }
}
</code>```

2:

```<code>private static void getWord(String str){
    try {
        if(!str.equals(null)) {
            System.out.println(str);
        }
    } catch (NullPointerException e) {
        System.out.println("Your word was null.");
    }
}
</code>```

3:

```<code>private static void getWord(String str){
    try {
        if(str != null) {
            System.out.println(str);
        }
    } catch (NullPointerException e) {
        System.out.println("Your word was null.");
    }
}
</code>```

Body:
How do you make an if statement check if something is null, and will return null if the if statement is true?

public String getMiddle(String word)
   {
      // I don't know if 'is null' or 'return null' are actually things
      if (is null){
         return null;
      }
   }

Also, what would be an example of an input that would make it null?

Body:
As Aominè and litelite both said(in the same way at the same time), you can just do this:

if(word == null) return null;

And your second question:

Also, what would be an example of an input that would make it null?

If you call the method like getMiddle(null), then that would be possible.

Here are a bunch of ways to check if a word is null:

1:

private static void getWord(String str){
    try {
        if(!str.equals("")) {
            System.out.println(str);
        }
    } catch (NullPointerException e) {
        System.out.println("Your word was null.");
    }
}

2:

private static void getWord(String str){
    try {
        if(!str.equals(null)) {
            System.out.println(str);
        }
    } catch (NullPointerException e) {
        System.out.println("Your word was null.");
    }
}

3:

private static void getWord(String str){
    try {
        if(str != null) {
            System.out.println(str);
        }
    } catch (NullPointerException e) {
        System.out.println("Your word was null.");
    }
}


问:
My PHP code is not picking up the variables when using the mail function
My PHP code is not picking up the variables in $message, when $message is sent to an email address using the mail function the variables are missing. Not sure what I am doing wrong.

```<code>    <?php

    $to = 'test@email.com';
    $subject = 'Booking';

    $name = $_post['name'];
    $email = $_post['email'];
    $pickup = $_post['pickup'];
    $destination = $_post['destination'];

    $message = <<<Email
    Hi,
    Please pick up $name from $pickup and drop to $destination
    Email;

    $header = $email;

    mail($to, $subject, $message, $header);

    echo "Message Sent";

    ?>
</code>```

The html code is provided below, not sure why $_POST is not pulling through.

```<code><!DOCTYPE html>
<html>
<head>
    <title>Sign Up</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>

    <form action="form.php" method="POST">
        <fieldset>
            <legend>Book your Journey</legend>
            <label for ="name">Name:</label>
            <input type="text" id="name" name="name">
            <label for="email">Email:</label>
            <input type="email" id="email" name="email">
            <label for="pickup"> Pick Up Location</label>
            <input type="text" id="pickup" name="pickup">
            <label>Time:</label>
            <select>
                <option>--HR--</option>
                <option value="1">01</option>
                <option value="2">02</option>
                <option value="3">03</option>
                <option value="4">04</option>
                <option value="5">05</option>
                <option value="6">06</option>
                <option value="7">07</option>
                <option value="8">08</option>
                <option value="9">09</option>
                <option value="10">10</option>
                <option value="11">11</option>
                <option value="12">12</option>
            </select>
            <label>:</label>
            <select>
                <option>--MIN--</option>
                <option value="00">00</option>
                <option value="15">15</option>
                <option value="30">30</option>
                <option value="45">45</option>
            </select>
            <select>
                <option value="am">am</option>
                <option value="pm">pm</option>
            </select>
            </fieldset>
            <fieldset>
            <label for="destination"> Destination Postal Code</label>
            <input type="text" id="destination" name="destination">
        </fieldset>
        <button>Submit</button>
    </form>

</body>
</html>
</code>```

答:
Case sensitive ...

I also recommend using:filter_input_array();

You can use it as follows:

```<code><?php
$input = filter_input_array(INPUT_POST);

$to      = 'test1@gmail.com';
$subject = 'Booking';

$name        = $input['name'];
$email       = $input['email'];
$pickup      = $input['pickup'];
$destination = $input['destination'];
</code>```

You can also use it with the GET method as follows:

```<code>filter_input_array (INPUT_GET);
</code>```

The use of ?> is not necessary.

Body:
My PHP code is not picking up the variables in $message, when $message is sent to an email address using the mail function the variables are missing. Not sure what I am doing wrong.

    <?php

    $to = 'test@email.com';
    $subject = 'Booking';

    $name = $_post['name'];
    $email = $_post['email'];
    $pickup = $_post['pickup'];
    $destination = $_post['destination'];

    $message = <<<Email
    Hi,
    Please pick up $name from $pickup and drop to $destination
    Email;

    $header = $email;

    mail($to, $subject, $message, $header);

    echo "Message Sent";

    ?>

The html code is provided below, not sure why $_POST is not pulling through.

<!DOCTYPE html>

    <title>Sign Up</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">

    <form action="form.php" method="POST">
        <fieldset>
            <legend>Book your Journey</legend>
            Name:
            <input type="text" id="name" name="name">
            Email:
            <input type="email" id="email" name="email">
             Pick Up Location
            <input type="text" id="pickup" name="pickup">
            Time:
            <select>
                <option>--HR--</option>
                <option value="1">01</option>
                <option value="2">02</option>
                <option value="3">03</option>
                <option value="4">04</option>
                <option value="5">05</option>
                <option value="6">06</option>
                <option value="7">07</option>
                <option value="8">08</option>
                <option value="9">09</option>
                <option value="10">10</option>
                <option value="11">11</option>
                <option value="12">12</option>
            </select>
            :
            <select>
                <option>--MIN--</option>
                <option value="00">00</option>
                <option value="15">15</option>
                <option value="30">30</option>
                <option value="45">45</option>
            </select>
            <select>
                <option value="am">am</option>
                <option value="pm">pm</option>
            </select>
            </fieldset>
            <fieldset>
             Destination Postal Code
            <input type="text" id="destination" name="destination">
        </fieldset>
        <button>Submit</button>
    </form>

Body:
Case sensitive ...

I also recommend using:filter_input_array();

You can use it as follows:

<?php
$input = filter_input_array(INPUT_POST);

$to      = 'test1@gmail.com';
$subject = 'Booking';

$name        = $input['name'];
$email       = $input['email'];
$pickup      = $input['pickup'];
$destination = $input['destination'];

You can also use it with the GET method as follows:

filter_input_array (INPUT_GET);

The use of ?> is not necessary.


问:
how to convert x-www-form-urlencoded payload to json
i am using the npm request module to post data.
by default the posy is of x-www-form-urlencoded
so on the server side i am receiving the data like this

```<code>{
  'files[0][path]': 'myfile1',
  'files[0][contents]': 'some content',
  'files[0][active]': 'true'
}
</code>```

how do i parse the data to json?
like

```<code>{
  files: [{
    path: 'mypath',
    content: 'mycontent',
    active: true
  } {
    path: 'mypath2',
    content: 'mycontent2',
    active: false
  }]
}
</code>```

I think express js might use a middle wire for this, but I am using hapi server.
what are my options to parse the payload to json?

答: with bodyparsing on the server side and hapijs, i happen to bump into hapi-bodyparser which did the job.</p>

Body:
i am using the npm request module to post data.
by default the posy is of x-www-form-urlencoded
so on the server side i am receiving the data like this

{
  'files[0][path]': 'myfile1',
  'files[0][contents]': 'some content',
  'files[0][active]': 'true'
}

how do i parse the data to json?
like

{
  files: [{
    path: 'mypath',
    content: 'mycontent',
    active: true
  } {
    path: 'mypath2',
    content: 'mycontent2',
    active: false
  }]
}

I think express js might use a middle wire for this, but I am using hapi server.
what are my options to parse the payload to json?


问:
How to get matplotlib bar chart to match numeric count in python terminal
My main objective is to be consistent with both my numeric output and my visual output. However, I can't seem to get to them to match.

Here is my setup using python 3.x:

```<code>df = pd.DataFrame([ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1,
   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1,
   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2,
   2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2,
   2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
   2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],columns=['Expo'])
</code>```

Followed by my setup for the bar chart in matplotlib:

```<code>x = df['Expo']
N = len(x)
y = range(N)
width = 0.125
plt.bar(x, y, width, color="blue")
fig = plt.gcf();
</code>```

A Nice pretty graph produced:

However, using this snippet code to check and see what the actual numeric counts of both classes are...

```<code>print("Class 1: "+str(df['Expo'].value_counts()[1]),"Class 2: "+str(df['Expo'].value_counts()[2]))
</code>```

I get the below:

Class 1: 85 Class 2: 70

Since I have 155 records in the data frame, numerically this makes sense. Having a single bar in the bar chart be at 155 does not.

I appreciate any help in advance.

答:
You may use a histogram,

```<code>plt.hist(df["Expo"])
</code>```

or specifying the bins

```<code>plt.hist(df["Expo"], bins=[0.5,1.5,2.5], ec="k")
plt.xticks([1,2])
</code>```

Body:
My main objective is to be consistent with both my numeric output and my visual output. However, I can't seem to get to them to match.

Here is my setup using python 3.x:

df = pd.DataFrame([ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1,
   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1,
   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2,
   2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2,
   2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
   2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],columns=['Expo'])

Followed by my setup for the bar chart in matplotlib:

x = df['Expo']
N = len(x)
y = range(N)
width = 0.125
plt.bar(x, y, width, color="blue")
fig = plt.gcf();

A Nice pretty graph produced:

However, using this snippet code to check and see what the actual numeric counts of both classes are...

print("Class 1: "+str(df['Expo'].value_counts()[1]),"Class 2: "+str(df['Expo'].value_counts()[2]))

I get the below:

Class 1: 85 Class 2: 70

Since I have 155 records in the data frame, numerically this makes sense. Having a single bar in the bar chart be at 155 does not.

I appreciate any help in advance.

Body:
You may use a histogram,

plt.hist(df["Expo"])

or specifying the bins

plt.hist(df["Expo"], bins=[0.5,1.5,2.5], ec="k")
plt.xticks([1,2])


问:
What is the difference between _url and _path while using the routes in rails
When we define routes in routes.rb using the name like map.some_link.We can use the link in two ways- some_link_url, some_link_path.

What are the differences between the two?

Which is more secure to be used?

答:
The _url helper generates a string containing the entire URL, while the _path helper generates a string containing the relative path from the root of the application, e.g.:

```<code>photos_url  # => "http://www.example.com/photos"
photos_path # => "/photos"
</code>```

As per Rails Guides - Routing.

Body:
The _url helper generates a string containing the entire URL, while the _path helper generates a string containing the relative path from the root of the application, e.g.:

photos_url  # => "http://www.example.com/photos"
photos_path # => "/photos"

As per Rails Guides - Routing.


答:
In this code snippet

```<code>enum { i = 1 };

class X {
  char  v[i];
  enum { i = 2 };
};
</code>```

when the array is declared the name i refers to the enumerator declared in the outer scope and the array is declared as having only one element.

If to exchange the declarations of the data members we will get another result that is that the enumerator declared in the class definition hides the enumerator declared in the outer scope. As result the array has two elements.

```<code>enum { i = 1 };

class X {
  enum { i = 2 };
  char  v[i];
};
</code>```

This is a reason for bugs that difficult to find.

For example let's assume that the class has a constructor within which the array is initialized.

```<code>enum { i = 1 };

class X {
public:
    X()
    {
        for (size_t j; j < i; j++) v[j] = 'A' + j;
    }
private:
    char  v[i];
    enum { i = 2 };
};
</code>```

As you can see there will be undefined behavior. Within the constructor the name i refers to the enumerator declared in the class while in the declaration of the array itself the name i refers to the enumerator declared in the outer scope.

Title: Why do we need [basic.scope.class]/2?

Body:
I understand all the errors shown in the example in [basic.scope.class]/5 refer to [basic.scope.class]/2.

[basic.scope.class]/2:

A name N used in a class S shall refer to the same declaration in its
  context and when re-evaluated in the completed scope of S. No
  diagnostic is required for a violation of this rule.

But what I'd like to know is why do we need such a rule in the language in the first place?

For instance, consider the first example in [basic.scope.class]/5:

What would be problem if the language allowed this, i.e., v[i] an array of one element below

enum { i = 1 };

class X {
  char  v[i];
  enum { i = 2 };
};

and an array of two elements in the example that follows?

enum { i = 1 };

class X {
  enum { i = 2 };
  char  v[i];
};

Body:
In this code snippet

enum { i = 1 };

class X {
  char  v[i];
  enum { i = 2 };
};

when the array is declared the name i refers to the enumerator declared in the outer scope and the array is declared as having only one element.

If to exchange the declarations of the data members we will get another result that is that the enumerator declared in the class definition hides the enumerator declared in the outer scope. As result the array has two elements.

enum { i = 1 };

class X {
  enum { i = 2 };
  char  v[i];
};

This is a reason for bugs that difficult to find.

For example let's assume that the class has a constructor within which the array is initialized.

enum { i = 1 };

class X {
public:
    X()
    {
        for (size_t j; j < i; j++) v[j] = 'A' + j;
    }
private:
    char  v[i];
    enum { i = 2 };
};

As you can see there will be undefined behavior. Within the constructor the name i refers to the enumerator declared in the class while in the declaration of the array itself the name i refers to the enumerator declared in the outer scope.


问:
iOS app will not launch until restart phone
I'm not entirely sure where to start with this. I have an iOS app in Swift for iOS 10.3 that uses Crashlytics and Realm, and several times a day, when I launch my app, it just sits at the launch screen, and then promptly closes. I get no logs when this happens (through crashlytics, or on the device), and the only way this solves itself is if I restart my phone, reinstall the app, or if I try again several hours later. I don't know how to debug this issue.

My application launching function is as follows:

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    Fabric.with([Crashlytics.self])
    // Override point for customization after application launch.
    self.createDirectories()
    var performShortcutDelegate = true
    let dir: URL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.BackloggerSharing")!
    let realmPath = dir.appendingPathComponent("db.realm")

    let config = Realm.Configuration(fileURL: realmPath, schemaVersion: 1, migrationBlock: {
        migration, oldSchemaVersion in
        if oldSchemaVersion < 1 {
            // auto migrate
        }
    })
    Realm.Configuration.defaultConfiguration = config
    self.compactRealm(at: realmPath)

    (UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self])).tintColor = Util.appColor
    UISlider.appearance().tintColor = Util.appColor
    self.window?.tintColor = Util.appColor

    if let shortcutItem = launchOptions?[UIApplicationLaunchOptionsKey.shortcutItem] as? UIApplicationShortcutItem {
        self.shortcutItem = shortcutItem
        performShortcutDelegate = false
    }

    return performShortcutDelegate
}

func createDirectories() {
    let playlistsFolder = Util.getPlaylistImagesDirectory()

    if !FileManager.default.fileExists(atPath: playlistsFolder.absoluteString) {
        do {
            try FileManager.default.createDirectory(at: playlistsFolder, withIntermediateDirectories: true, attributes: nil)
        } catch let error as NSError {
            NSLog(error.localizedDescription)
        }
    }
}

func compactRealm(at realmPath: URL) {
    let defaultParentURL = realmPath.deletingLastPathComponent()
    let compactedURL = defaultParentURL.appendingPathComponent("default-compact.realm")
    autoreleasepool {
        let realm = try? Realm()
        try! realm?.writeCopy(toFile: compactedURL)
    }
    try! FileManager.default.removeItem(at: realmPath)
    try! FileManager.default.moveItem(at: compactedURL, to: realmPath)
}
</code>```

Any help on the matter would be greatly appreciated!

答:
if you use Realm, and you make changes in Database you should reinstall the app otherwise it crashes on Launch screen,
if above is not an issue then maybe your app uses maximum memory, or some of your code causes memory leakages.</p>

Body:
I'm not entirely sure where to start with this. I have an iOS app in Swift for iOS 10.3 that uses Crashlytics and Realm, and several times a day, when I launch my app, it just sits at the launch screen, and then promptly closes. I get no logs when this happens (through crashlytics, or on the device), and the only way this solves itself is if I restart my phone, reinstall the app, or if I try again several hours later. I don't know how to debug this issue.

My application launching function is as follows:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    Fabric.with([Crashlytics.self])
    // Override point for customization after application launch.
    self.createDirectories()
    var performShortcutDelegate = true
    let dir: URL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.BackloggerSharing")!
    let realmPath = dir.appendingPathComponent("db.realm")

    let config = Realm.Configuration(fileURL: realmPath, schemaVersion: 1, migrationBlock: {
        migration, oldSchemaVersion in
        if oldSchemaVersion < 1 {
            // auto migrate
        }
    })
    Realm.Configuration.defaultConfiguration = config
    self.compactRealm(at: realmPath)

    (UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self])).tintColor = Util.appColor
    UISlider.appearance().tintColor = Util.appColor
    self.window?.tintColor = Util.appColor

    if let shortcutItem = launchOptions?[UIApplicationLaunchOptionsKey.shortcutItem] as? UIApplicationShortcutItem {
        self.shortcutItem = shortcutItem
        performShortcutDelegate = false
    }

    return performShortcutDelegate
}

func createDirectories() {
    let playlistsFolder = Util.getPlaylistImagesDirectory()

    if !FileManager.default.fileExists(atPath: playlistsFolder.absoluteString) {
        do {
            try FileManager.default.createDirectory(at: playlistsFolder, withIntermediateDirectories: true, attributes: nil)
        } catch let error as NSError {
            NSLog(error.localizedDescription)
        }
    }
}

func compactRealm(at realmPath: URL) {
    let defaultParentURL = realmPath.deletingLastPathComponent()
    let compactedURL = defaultParentURL.appendingPathComponent("default-compact.realm")
    autoreleasepool {
        let realm = try? Realm()
        try! realm?.writeCopy(toFile: compactedURL)
    }
    try! FileManager.default.removeItem(at: realmPath)
    try! FileManager.default.moveItem(at: compactedURL, to: realmPath)
}

Any help on the matter would be greatly appreciated!


问:
How to Generate AccessToken for user who is logged in with External Providers
I have an API implemented by asp.net core.
I've used OpenIddict to generate access token and refresh token for users who registered to my api by email and password.
I've added Google middleware (.UseGoogleAuthentication ... ) to my API and I can successfully log in user with Google.
My client is UWP and I use WebAuthenticationBroker to get redirected to google after sending a reuest to localhost/Account/ExternalLogin/Google.
when the users is logged In with google he is redirected to Account/ExternalLoginConfirmation which is trivial to this point now before it finishes with ExternalLoginConfirmation I Want to generate and send back an Access Token and a refresh token for the user cause if the WebAuthenticationBroker get's closed I have no other way to get tokens for this user(cause he has no password and the username will be unknown to me).
Itried this :

```<code>//
    // POST: /Account/
    [HttpPost("ExternalLoginConfirmation")]
    [AllowAnonymous]
    //[ValidateAntiForgeryToken]
    public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model,
        string returnUrl = null)
    {
        if (ModelState.IsValid)
        {
            // Get the information about the user from the external login provider
            var info = await SignInManager.GetExternalLoginInfoAsync();
            if (info == null)
                return View("ExternalLoginFailure");
            var user = new UserInfo { UserName = model.Email, Email = model.Email };
            var result = await UserManager.CreateAsync(user);
            if (result.Succeeded)
            {
                result = await UserManager.AddLoginAsync(user, info);
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, false);
                    Logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
                    var identity = new ClaimsIdentity(
                OpenIdConnectServerDefaults.AuthenticationScheme,
                OpenIdConnectConstants.Claims.Name, null);

                    // Add a "sub" claim containing the user identifier, and attach
                    // the "access_token" destination to allow OpenIddict to store it
                    // in the access token, so it can be retrieved from your controllers.
                    identity.AddClaim(OpenIdConnectConstants.Claims.Subject,
                        user.Id,
                        OpenIdConnectConstants.Destinations.AccessToken);

                    identity.AddClaim(OpenIdConnectConstants.Claims.Name, user.UserName,
                        OpenIdConnectConstants.Destinations.AccessToken);

                    // ... add other claims, if necessary.

                    var principal = new ClaimsPrincipal(identity);

                    var authenticateInfo = await HttpContext.Authentication.GetAuthenticateInfoAsync(info.LoginProvider);
                    var ticket = CreateTicketAsync(principal, authenticateInfo.Properties);

                    // Ask OpenIddict to generate a new token and return an OAuth2 token response.
                    return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
                    //return RedirectToLocal(returnUrl);
                }
            }
            AddErrors(result);
        }

        //ViewData["ReturnUrl"] = returnUrl;
        return BadRequest();
    }

    #region _helpers

    private AuthenticationTicket CreateTicketAsync(ClaimsPrincipal principal,
        AuthenticationProperties properties = null)
    {
        // Create a new authentication ticket holding the user identity.
        var ticket = new AuthenticationTicket(principal, properties,
            OpenIdConnectServerDefaults.AuthenticationScheme);

       ticket.SetScopes(new[]
       {
           /* openid: */ OpenIdConnectConstants.Scopes.OpenId,
           /* email: */ OpenIdConnectConstants.Scopes.Email,
           /* profile: */ OpenIdConnectConstants.Scopes.Profile,
           /* offline_access: */ OpenIdConnectConstants.Scopes.OfflineAccess,
           /* roles: */ OpenIddictConstants.Scopes.Roles
       });

        ticket.SetAudiences(Configuration["Authentication:OpenIddict:Audience"]);

        return ticket;
    }

    private void AddErrors(IdentityResult result)
    {
        foreach (var error in result.Errors)
            ModelState.AddModelError(string.Empty, error.Description);
    }

    private IActionResult RedirectToLocal(string returnUrl)
    {
        if (Url.IsLocalUrl(returnUrl))
            return Redirect(returnUrl);
        return BadRequest();
    }

    #endregion
</code>```

but this fails and throws exception :
an authorization or token response cannot be returned from this controller

now how do I generate these Tokens for the user?

答:
now how do I generate these Tokens for the user?

OpenIddict deliberately prevents you from returning OIDC responses from non-OIDC endpoints (for obvious security reasons).

To make your scenario work, you must redirect your users back to the authorization endpoint with all the OpenID Connect parameters.

Concretely, you should revert all the changes added to ExternalLoginConfirmation() (that should return RedirectToLocal(returnUrl);) and move the SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme); part back to your authorization controller.

Body:
I have an API implemented by asp.net core.
I've used OpenIddict to generate access token and refresh token for users who registered to my api by email and password.
I've added Google middleware (.UseGoogleAuthentication ... ) to my API and I can successfully log in user with Google.
My client is UWP and I use WebAuthenticationBroker to get redirected to google after sending a reuest to localhost/Account/ExternalLogin/Google.
when the users is logged In with google he is redirected to Account/ExternalLoginConfirmation which is trivial to this point now before it finishes with ExternalLoginConfirmation I Want to generate and send back an Access Token and a refresh token for the user cause if the WebAuthenticationBroker get's closed I have no other way to get tokens for this user(cause he has no password and the username will be unknown to me).
Itried this :

//
    // POST: /Account/
    [HttpPost("ExternalLoginConfirmation")]
    [AllowAnonymous]
    //[ValidateAntiForgeryToken]
    public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model,
        string returnUrl = null)
    {
        if (ModelState.IsValid)
        {
            // Get the information about the user from the external login provider
            var info = await SignInManager.GetExternalLoginInfoAsync();
            if (info == null)
                return View("ExternalLoginFailure");
            var user = new UserInfo { UserName = model.Email, Email = model.Email };
            var result = await UserManager.CreateAsync(user);
            if (result.Succeeded)
            {
                result = await UserManager.AddLoginAsync(user, info);
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, false);
                    Logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
                    var identity = new ClaimsIdentity(
                OpenIdConnectServerDefaults.AuthenticationScheme,
                OpenIdConnectConstants.Claims.Name, null);

                    // Add a "sub" claim containing the user identifier, and attach
                    // the "access_token" destination to allow OpenIddict to store it
                    // in the access token, so it can be retrieved from your controllers.
                    identity.AddClaim(OpenIdConnectConstants.Claims.Subject,
                        user.Id,
                        OpenIdConnectConstants.Destinations.AccessToken);

                    identity.AddClaim(OpenIdConnectConstants.Claims.Name, user.UserName,
                        OpenIdConnectConstants.Destinations.AccessToken);

                    // ... add other claims, if necessary.

                    var principal = new ClaimsPrincipal(identity);

                    var authenticateInfo = await HttpContext.Authentication.GetAuthenticateInfoAsync(info.LoginProvider);
                    var ticket = CreateTicketAsync(principal, authenticateInfo.Properties);

                    // Ask OpenIddict to generate a new token and return an OAuth2 token response.
                    return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
                    //return RedirectToLocal(returnUrl);
                }
            }
            AddErrors(result);
        }

        //ViewData["ReturnUrl"] = returnUrl;
        return BadRequest();
    }

    #region _helpers

    private AuthenticationTicket CreateTicketAsync(ClaimsPrincipal principal,
        AuthenticationProperties properties = null)
    {
        // Create a new authentication ticket holding the user identity.
        var ticket = new AuthenticationTicket(principal, properties,
            OpenIdConnectServerDefaults.AuthenticationScheme);

       ticket.SetScopes(new[]
       {
           /* openid: */ OpenIdConnectConstants.Scopes.OpenId,
           /* email: */ OpenIdConnectConstants.Scopes.Email,
           /* profile: */ OpenIdConnectConstants.Scopes.Profile,
           /* offline_access: */ OpenIdConnectConstants.Scopes.OfflineAccess,
           /* roles: */ OpenIddictConstants.Scopes.Roles
       });

        ticket.SetAudiences(Configuration["Authentication:OpenIddict:Audience"]);

        return ticket;
    }

    private void AddErrors(IdentityResult result)
    {
        foreach (var error in result.Errors)
            ModelState.AddModelError(string.Empty, error.Description);
    }

    private IActionResult RedirectToLocal(string returnUrl)
    {
        if (Url.IsLocalUrl(returnUrl))
            return Redirect(returnUrl);
        return BadRequest();
    }

    #endregion

but this fails and throws exception :
an authorization or token response cannot be returned from this controller

now how do I generate these Tokens for the user?


问:
Linq help with SQL in() statement
I need help writing a Linq statement that does the same as the following sql query...

```<code>select col1, col2, col3
from table1
where col1 = 'foo'
and col2 = 0
and IsNull(col3, '') IN('A','')
</code>```

thanks

答:
```<code>from t in context.table1
where
   t.col1 == "foo"
&& t.col2 == 0
&& (new string[]{"A", string.Empty}).Contains(t.col3.DefaultIfEmpty(string.Empty))
select new {t.col1, t.col2, t.col3};
</code>```

Title: Linq help with SQL in() statement

Body:
I need help writing a Linq statement that does the same as the following sql query...

select col1, col2, col3
from table1
where col1 = 'foo'
and col2 = 0
and IsNull(col3, '') IN('A','')

thanks


答:
Seems like your searching for a global variable:

```<code>global. number_of_clusters = 1
</code>```

However using a database or a file would probably be a nicer solution.

Title: node.js share dynamic variables between modules

Body:
I have a variable named number_of_clusters which must be updated periodically. number_of_clusters must also be shared with other modules to read it. how can I assure that reading modules will read a fresh copy of this variable each time they access that?
I dont want to use database to share this variable so I thought I could share it via process.env

process.env.number_of_clusters = 1;

is it a good practice?

Body:
Seems like your searching for a global variable:

global. number_of_clusters = 1

However using a database or a file would probably be a nicer solution.


问:
Get SingularAttribute from JPA metamodel by looping through a list
I'm having a JPA metamodel where I retrieving attributes from.

@StaticMetamodel(Test.class)
public class Test_{
    public static volatile SingularAttribute<Test, Boolean> var1;
    public static volatile SingularAttribute<Test, Boolean> var2;
    public static volatile SingularAttribute<Test, Boolean> var3;
}
```

<p>I can call and use them manually:</p>

<pre class="lang-java prettyprint-override"><code>Test_.var1
Test_.var2
Test_.var3
</code>```

But how can I do that by looping through a list:

List<String> vars = new ArrayList<String>();
vars.add("var1");
vars.add("var2");
vars.add("var3");

for (int i=0; i < vars.size(); i++) {
    String var = vars.get(i).toString();
    System.out.println(var); // prints: var1, var2, var3

    // How? (s. update below)

}
```

<p>How do I get the attribute from the metamodel using string <code>var</code>.</p>

<hr>

<h3>Update</h3>

<p>I tried to use java reflection as suggested by @naXa within the loop but without success:</p>

<pre class="lang-java prettyprint-override"><code>// suppose to be
System.out.println(Test_.var1); // com.example.entities.Test.var1
System.out.println(Test_.var1.getType()); // boolean
</code>```

// looping through list
Class object = Test_.class;
try {
    Field field = object.getDeclaredField(var);
    field.setAccessible(true); // public static volatile javax.persistence.metamodel.SingularAttribute com.example.entities.Test.var1
    System.out.println(field); // com.example.entities.Test.var1
    System.out.println(field.getType()); // interface javax.persistence.metamodel.SingularAttribute
    // but <field> is still no Expression <Boolean>
} catch(NoSuchFieldException e) {
    System.out.println("Error");
}
```

It doesn't return the correct name nor type (see output comments in code).

答:
In your Reflection code you are using the field directly but that is not the static SingularAttribute (Test_.var1) value you are looking for. You need to get the actual static value using field.get(null)

```<code>Field[] fields = Test_.class.getDeclaredFields();
for (Field field : fields) {
    if (Modifier.isPublic(field.getModifiers())) {
        // For Each Public Field
        try {
            Object obj = field.get(null); // Equivalent to Test_.var1 but you need to cast it
            if (obj instanceof SingularAttribute) {
                System.out.println(obj); // Equivalent to Test_.var1
                System.out.println(SingularAttribute.class.cast(obj).getType()); // Equivalent to Test_.var1.getType()
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
</code>```

Body:
I'm having a JPA metamodel where I retrieving attributes from.

@StaticMetamodel(Test.class)
public class Test_{
    public static volatile SingularAttribute<Test, Boolean> var1;
    public static volatile SingularAttribute<Test, Boolean> var2;
    public static volatile SingularAttribute<Test, Boolean> var3;
}

I can call and use them manually:

Test_.var1
Test_.var2
Test_.var3

But how can I do that by looping through a list:

List<String> vars = new ArrayList<String>();
vars.add("var1");
vars.add("var2");
vars.add("var3");

for (int i=0; i < vars.size(); i++) {
    String var = vars.get(i).toString();
    System.out.println(var); // prints: var1, var2, var3

    // How? (s. update below)

}

How do I get the attribute from the metamodel using string var.

Update

I tried to use java reflection as suggested by @naXa within the loop but without success:

// suppose to be
System.out.println(Test_.var1); // com.example.entities.Test.var1
System.out.println(Test_.var1.getType()); // boolean

// looping through list
Class object = Test_.class;
try {
    Field field = object.getDeclaredField(var);
    field.setAccessible(true); // public static volatile javax.persistence.metamodel.SingularAttribute com.example.entities.Test.var1
    System.out.println(field); // com.example.entities.Test.var1
    System.out.println(field.getType()); // interface javax.persistence.metamodel.SingularAttribute
    // but <field> is still no Expression <Boolean>
} catch(NoSuchFieldException e) {
    System.out.println("Error");
}

It doesn't return the correct name nor type (see output comments in code).

Body:
In your Reflection code you are using the field directly but that is not the static SingularAttribute (Test_.var1) value you are looking for. You need to get the actual static value using field.get(null)

Field[] fields = Test_.class.getDeclaredFields();
for (Field field : fields) {
    if (Modifier.isPublic(field.getModifiers())) {
        // For Each Public Field
        try {
            Object obj = field.get(null); // Equivalent to Test_.var1 but you need to cast it
            if (obj instanceof SingularAttribute) {
                System.out.println(obj); // Equivalent to Test_.var1
                System.out.println(SingularAttribute.class.cast(obj).getType()); // Equivalent to Test_.var1.getType()
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}


问:
Is it possible to make a property of type class A, inside of class A?
So lets say that I have a class named A. Class A has several basic properties, however one of it's properties is supposed to be of type Class A. Here is an example of what I am talking about:

```<code>class A {
public:
    int a;
    bool b;
    A c;
};
</code>```

However, when I try to build this, I get the error "incomplete type is not allowed", which I am assuming has to do with the fact that property c does not have a definition for A yet, but even if I put:

```<code>class A;
</code>```

before I construct class A, however I still get the error "incomplete type is not allowed". If anyone knows how to create a property of type class A inside of class A, I would appreciate your help.
Thanks

Edit: I do not believe this post is a duplicate because I am trying to find out How you can create a property of type class A inside class A, instead of simply "why you can't create an instance of itself..."

答:
As far as I know you need complete types to define data members by value because they are allocated directly within each class object and this is important to know the class object size. The forward declaration doesn't help here because it only provides an incomplete type. You can have a reference or pointer to A, for example:

```<code>class A {
public:
    int a;
    bool b;
    A* c;
};
</code>```

Body:
So lets say that I have a class named A. Class A has several basic properties, however one of it's properties is supposed to be of type Class A. Here is an example of what I am talking about:

class A {
public:
    int a;
    bool b;
    A c;
};

However, when I try to build this, I get the error "incomplete type is not allowed", which I am assuming has to do with the fact that property c does not have a definition for A yet, but even if I put:

class A;

before I construct class A, however I still get the error "incomplete type is not allowed". If anyone knows how to create a property of type class A inside of class A, I would appreciate your help.
Thanks

Edit: I do not believe this post is a duplicate because I am trying to find out How you can create a property of type class A inside class A, instead of simply "why you can't create an instance of itself..."

Body:
As far as I know you need complete types to define data members by value because they are allocated directly within each class object and this is important to know the class object size. The forward declaration doesn't help here because it only provides an incomplete type. You can have a reference or pointer to A, for example:

class A {
public:
    int a;
    bool b;
    A* c;
};


答:
Here you go try this for dynamically created buttons</p>

```<code>$(document).on('click', '#id', function(){});
</code>```

Title: Calling event click with JavaScript

Body:
It is possible to call a event click with JavaScript? how?

I'm trying to call this event when a button get clicked.

I'm creating Buttons dynamically so the id's change constantly

Here is how i make the buttons dynamically and assign the event click

protected void Page_Init(object sender, EventArgs e)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "showAndHide();", true);

            Button Btn_clic = (Button)sender;
            var name = Btn_clic.Text;

            List.ListUsers listArea = new List.ListUsers();
            List<Data.Area> Area = listArea.AreaList();

            List<Data.Area> ListOfEquiposOk = Area.Where(x => x.AREA == name && x.STANDBY == 0).ToList();

            List<Button> Botones = new List<Button>();

            var TeamFCH = ListOfEquiposOk.Select(x => x.TEAM).Distinct().ToList();

            foreach (var team in TeamFCH)
            {
                Button newButton = new Button();
                newButton.CommandName = "Btn" + Convert.ToString(team);
                newButton.ID = "Btn_" + Convert.ToString(team);
                newButton.Text = team;
                newButton.CommandArgument = name;

                newButton.Click += new System.EventHandler(newButton_Click);

                Botones.Add(newButton);

                GoodPanel.Controls.Add(newButton);
                newButton.CssClass = "btn-primary outline separate";
            }
        }

protected void newButton_Click(object sender, EventArgs e)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ModalGood();", true);

            Button Btnclick = (Button)sender;
            var team = Btnclick.Text;
            string name = Btnclick.CommandArgument;

            List.ListUsers listArea = new List.ListUsers();
            List<Data.Area> Area = listArea.AreaList();

            List<Data.Area> ListOfToolsOk = Area.Where(x => x.AREA == name && x.TEAM == team && x.STANDBY == 0).ToList();

            var ToolArea = ListOfToolsOk.Select(x => x.TEAM);
            Grv_Eng.DataSource = ListOfToolsOk;
            Grv_Eng.DataBind();
        }

Body:
Here you go try this for dynamically created buttons

$(document).on('click', '#id', function(){});


答:
```<code>var q = from row in YourTableObject
        where row.col1 = "foo"
              && row.col2 = 0
              && (string.IsNullOrEmpty(row.col3) || row.col3 == "A")
        select new {
                       col1,
                       col2,
                       col3
                    }
</code>```

Title: Linq help with SQL in() statement


问:
Methods defined in class Object are instance and class one at the same time
How can be described that a method boo defined in Object class becomes instance and class one at the same time in class Foo?

```<code>class Foo; end

class Object
  def boo
    'boo method'
  end
end

p Foo.boo # => boo method
p Foo.new.boo # => boo method
</code>```

答:
If you really want to do this, keep in mind that the class context and the instance context are entirely different so instance variables are not equivalent.

```<code>module FooMethods
  def boo
    'boo'
  end
end

class Foo
  extend FooMethods
  include FooMethods
end
</code>```

This deliberately imports the mixin at both the class level via extend and instance level via include.

Body:
How can be described that a method boo defined in Object class becomes instance and class one at the same time in class Foo?

class Foo; end

class Object
  def boo
    'boo method'
  end
end

p Foo.boo # => boo method
p Foo.new.boo # => boo method

Body:
If you really want to do this, keep in mind that the class context and the instance context are entirely different so instance variables are not equivalent.

module FooMethods
  def boo
    'boo'
  end
end

class Foo
  extend FooMethods
  include FooMethods
end

This deliberately imports the mixin at both the class level via extend and instance level via include.


问:
Is there a way to do some ng-model of a non-input form element?
I have a form with 50 fields. I want to preview to the user what they typed in the form in my template like this:

```<code><div> STRING RESULT {{textfield1}} - {{textfield2}} - 3 {{textfield3}}</div>
</code>```

I wanted to store this into a variable

```<code><div [(ngModel)]="myresultmodel"> STRING RESULT {{textfield1}} - {{textfield2}} - 3 {{textfield3}}</div>
</code>```

The problem when I do that is I get:

```<code>ERROR Error: No value accessor for form control with unspecified name attribute
</code>```

Is this not possible/shunned upon? Or is there a good way to do this?

Note: The result I am looking for is a single variable that contains the entire string within the div: "STRING RESULT {{textfield1}} - {{textfield2}} - 3 {{textfield3}}"

答:
You can access to the inner HTML of the div with ViewChild.

See this plunker

I use the doCheck lifecycle to automatically update the result. The doCheck occurs before actually rendering the HTML, so you have to wrap the refresh in an async closure. Just call setTimeout without any timer do the trick.

I'm not a big fan of using the setTimeout hack. I think you can inject the changeDetector and call the changeDetection manually. But calling the changeDetection inside the doCheck can have side effect.

Body:
I have a form with 50 fields. I want to preview to the user what they typed in the form in my template like this:

 STRING RESULT {{textfield1}} - {{textfield2}} - 3 {{textfield3}}

I wanted to store this into a variable

 STRING RESULT {{textfield1}} - {{textfield2}} - 3 {{textfield3}}

The problem when I do that is I get:

ERROR Error: No value accessor for form control with unspecified name attribute

Is this not possible/shunned upon? Or is there a good way to do this?

Note: The result I am looking for is a single variable that contains the entire string within the div: "STRING RESULT {{textfield1}} - {{textfield2}} - 3 {{textfield3}}"


问:
Export Video with Images in C#
So here's an overview of my program. You select a folder, containing images. The program imports all images in said folder (with the .JPG extension). Then, it exports these images into an MP4. For this program, I don't need a visible timeline, just a way to export said images.

I'd like to be able to set a universal duration and I want to (if possible) have a Ken Burns effect on each image, where the image simply is scaled up by like a factor of 5%-10% (this part doesn't have to change each time). As of right now, this is my code:

```<code>private void btnOpen_Click(object sender, EventArgs e)
{
    openFolder.Description = "Open a folder containing pictures for the slideshow!";

    if (openFolder.ShowDialog() == DialogResult.OK)
    {
        var folderPath = openFolder.SelectedPath;
        MessageBox.Show(folderPath);

        var fileArray = Directory.GetFiles(folderPath, "*.JPG");
        float duration = 4;
        float startpos = 0;
        foreach (var file in fileArray)
        {
            var filePath = $@"{folderPath}\{file}";
            MessageBox.Show(filePath);
            //add image to "timeline"
            startpos += 4;
        }
    }
    else
    {
        MessageBox.Show("Next time, select a folder and click open!", "Selection Cancelled", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

private void btnExport_Click(object sender, EventArgs e)
{
    if (presetList.SelectedIndex == -1)
        MessageBox.Show("Please select a preset!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    else
    {
        if (presetList.SelectedItem.ToString() == "720p, 30fps")
        {
            //export code here
        }
        else if (presetList.SelectedItem.ToString() == "720p, 60fps")
        {
            //export code here
        }
        else if (presetList.SelectedItem.ToString() == "1080p, 30fps")
        {
            //export code here
        }
        else if (presetList.SelectedItem.ToString() == "1080p, 60fps")
        {
            //export code here
        }
    }
}
</code>```

I've looked at a few libraries so far, but none of them seem to fit my needs, and all of them seem to be ridiculously expensive.

答: I have used Magick.net for similar tasks and it's a great open source library for these things. I know that they offer a feature to scale images.</p>

Title: Export Video with Images in C#

Body:
So here's an overview of my program. You select a folder, containing images. The program imports all images in said folder (with the .JPG extension). Then, it exports these images into an MP4. For this program, I don't need a visible timeline, just a way to export said images.

I'd like to be able to set a universal duration and I want to (if possible) have a Ken Burns effect on each image, where the image simply is scaled up by like a factor of 5%-10% (this part doesn't have to change each time). As of right now, this is my code:

private void btnOpen_Click(object sender, EventArgs e)
{
    openFolder.Description = "Open a folder containing pictures for the slideshow!";

    if (openFolder.ShowDialog() == DialogResult.OK)
    {
        var folderPath = openFolder.SelectedPath;
        MessageBox.Show(folderPath);

        var fileArray = Directory.GetFiles(folderPath, "*.JPG");
        float duration = 4;
        float startpos = 0;
        foreach (var file in fileArray)
        {
            var filePath = $@"{folderPath}\{file}";
            MessageBox.Show(filePath);
            //add image to "timeline"
            startpos += 4;
        }
    }
    else
    {
        MessageBox.Show("Next time, select a folder and click open!", "Selection Cancelled", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

private void btnExport_Click(object sender, EventArgs e)
{
    if (presetList.SelectedIndex == -1)
        MessageBox.Show("Please select a preset!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    else
    {
        if (presetList.SelectedItem.ToString() == "720p, 30fps")
        {
            //export code here
        }
        else if (presetList.SelectedItem.ToString() == "720p, 60fps")
        {
            //export code here
        }
        else if (presetList.SelectedItem.ToString() == "1080p, 30fps")
        {
            //export code here
        }
        else if (presetList.SelectedItem.ToString() == "1080p, 60fps")
        {
            //export code here
        }
    }
}

I've looked at a few libraries so far, but none of them seem to fit my needs, and all of them seem to be ridiculously expensive.


问:
Mount directory as volume in Docker on Windows 10
I installed Docker on Windows 10 but I have an problem with mount directory (docker it is installed with virtualbox).

I want to mount this path -v /D/www/project_name:/usr/public/www . But I can not do that because I don't have permission.

If I try to mount -v /C/Users/Public/test:/usr/public/www, that works.

How can set permission on partition D? or on path D:www/project_name.

Thanks!

答:
Under windows 10 with the recent versions of docker (which relies on Hyper-V and not VirtualBox) you do not have this kind of issues anymore.

But if you do not have the choice, you should to mount shared directories into virtual box as shown there : http://developmentalmadness.com/2016/03/05/docker-permanently-mount-a-virtualbox-shared-folder/


问:
VB.net send keypress to game
ive seen other questions about this issue but none of them resolved it for me so here i go. I'm trying to send a keypress to a game to save the progress(its a 64bit game). what i've coded so far is :

```<code>Dim p() As Process
Dim GameID As Integer = 0
 Dim p As Process() = Process.GetProcessesByName("Gamename")

    If p.Length > 0 Then
        For i As Integer = 0 To p.Length - 1
            GameID = (p(i).Id)
        Next
    End If
AutoSaveTimer.Enabled = True
    Dim Test As Integer = 0
    GetAsyncKeyState(Test)
    AppActivate("GameName")
    My.Computer.Keyboard.SendKeys(";", True)
</code>```

now i've tried Sendkeys.Send(";") but without luck, and the game runs under "GameName" but then the keypress needs to be sent in a window under the game :
Blacked out is the game and under the first window is where the keypress needs to be sent

thanks in advance for the help

答:
You can simulate keyboard input to a program like this:</p>

```<code>    <DllImport("user32.dll")> _
Public Shared Function SetForegroundWindow(hWnd As IntPtr) As Boolean
End Function

Public Sub Send()
        Dim p As System.Diagnostics.Process() = System.Diagnostics.Process.GetProcessesByName("notepad")
        'search for process notepad
        If p.Length > 0 Then
            'check if window was found
            'bring notepad to foreground
            SetForegroundWindow(p(0).MainWindowHandle)
        End If

        SendKeys.SendWait("a")
        'send key "a" to notepad
    End Sub
</code>```

Title: VB.net send keypress to game

Body:
ive seen other questions about this issue but none of them resolved it for me so here i go. I'm trying to send a keypress to a game to save the progress(its a 64bit game). what i've coded so far is :

Dim p() As Process
Dim GameID As Integer = 0
 Dim p As Process() = Process.GetProcessesByName("Gamename")

    If p.Length > 0 Then
        For i As Integer = 0 To p.Length - 1
            GameID = (p(i).Id)
        Next
    End If
AutoSaveTimer.Enabled = True
    Dim Test As Integer = 0
    GetAsyncKeyState(Test)
    AppActivate("GameName")
    My.Computer.Keyboard.SendKeys(";", True)

now i've tried Sendkeys.Send(";") but without luck, and the game runs under "GameName" but then the keypress needs to be sent in a window under the game :
Blacked out is the game and under the first window is where the keypress needs to be sent

thanks in advance for the help

Body:
You can simulate keyboard input to a program like this:

    <DllImport("user32.dll")> _
Public Shared Function SetForegroundWindow(hWnd As IntPtr) As Boolean
End Function

Public Sub Send()
        Dim p As System.Diagnostics.Process() = System.Diagnostics.Process.GetProcessesByName("notepad")
        'search for process notepad
        If p.Length > 0 Then
            'check if window was found
            'bring notepad to foreground
            SetForegroundWindow(p(0).MainWindowHandle)
        End If

        SendKeys.SendWait("a")
        'send key "a" to notepad
    End Sub


问:
SQL Join in ZF3 Expressive - ResultSet does not give joined Columns
I'm trying to get a title out of a second table (by left-join) but my resultSet isn't delivering the column of the joined table.

This is how my TableGateway looks like:

```<code> public function fetchCourseListWithStudyprogram()
{
        $select = $this->getSql()->select();
        $select->where->equalTo('course_active', 'Y');
        $select->join('studyprogram', 'studyprogram.studyprogram_id = course.studyprogram_id', ['studyprogram_title'], $select::JOIN_LEFT);

    $resultSet = $this->selectWith($select);
    var_dump($resultSet);
    return $resultSet->toArray();
}
</code>```

The statement is getting constructed as it should be:

```<code>public 'queryString' => string 'SELECT `course`.*, `studyprogram`.`studyprogram_title` AS `studyprogram_title` FROM `course` LEFT JOIN `studyprogram` ON `studyprogram`.`studyprogram_id` = `course`.`studyprogram_id` WHERE `course_active` = :where1' (length=214)
</code>```

When it comes to getting results, it ignores the "studyprogram_title" column, I guess its because of the given resultSet (with binded CourseEntity)

Is there any way to show the studyprogram_title without adding it to the CourseEntity? Its not really a part of it so I guess its dirty if I add it there.

答:
There is a way how to handle two tables in a model.

If you want to join two tables directly without specifying tablegateway for each table then that will raise an issue. That means you can not make the resultset to an array because, in this case, you are not using the resultsetprototype for the other table as you do for the one (the current model) where you are trying to join two tables.

You may check out this answer!

Body:
I'm trying to get a title out of a second table (by left-join) but my resultSet isn't delivering the column of the joined table.

This is how my TableGateway looks like:

 public function fetchCourseListWithStudyprogram()
{
        $select = $this->getSql()->select();
        $select->where->equalTo('course_active', 'Y');
        $select->join('studyprogram', 'studyprogram.studyprogram_id = course.studyprogram_id', ['studyprogram_title'], $select::JOIN_LEFT);

    $resultSet = $this->selectWith($select);
    var_dump($resultSet);
    return $resultSet->toArray();
}

The statement is getting constructed as it should be:

public 'queryString' => string 'SELECT `course`.*, `studyprogram`.`studyprogram_title` AS `studyprogram_title` FROM `course` LEFT JOIN `studyprogram` ON `studyprogram`.`studyprogram_id` = `course`.`studyprogram_id` WHERE `course_active` = :where1' (length=214)

When it comes to getting results, it ignores the "studyprogram_title" column, I guess its because of the given resultSet (with binded CourseEntity)

Is there any way to show the studyprogram_title without adding it to the CourseEntity? Its not really a part of it so I guess its dirty if I add it there.


问:
Can I read PDF or Word Docs with Node.js?
I can't find any packages to do this. I know PHP has a ton of libraries for PDFs (like http://www.fpdf.org/) but anything for Node?</p>

答:
you can use pdf-text for pdf files. it will extract text from a pdf into an array of text 'chunks'. Useful for doing fuzzy parsing on structured pdf text.

```<code>var pdfText = require('pdf-text')
var pathToPdf = __dirname + "/info.pdf"

pdfText(pathToPdf, function(err, chunks) {
  //chunks is an array of strings
  //loosely corresponding to text objects within the pdf
  //for a more concrete example, view the test file in this repo
})

var fs = require('fs')
var buffer = fs.readFileSync(pathToPdf)
pdfText(buffer, function(err, chunks) {
 console.log(chunks)
})
</code>```

for docx files you can use mammoth, it will extract text from .docx files.

```<code>var mammoth = require("mammoth");

mammoth.extractRawText({path: "./doc.docx"})
    .then(function(result){
        var text = result.value; // The raw text
        console.log(text);
        var messages = result.messages;
    })
    .done();
</code>```

I hope this will help.

Body:
you can use pdf-text for pdf files. it will extract text from a pdf into an array of text 'chunks'. Useful for doing fuzzy parsing on structured pdf text.

var pdfText = require('pdf-text')
var pathToPdf = __dirname + "/info.pdf"

pdfText(pathToPdf, function(err, chunks) {
  //chunks is an array of strings
  //loosely corresponding to text objects within the pdf
  //for a more concrete example, view the test file in this repo
})

var fs = require('fs')
var buffer = fs.readFileSync(pathToPdf)
pdfText(buffer, function(err, chunks) {
 console.log(chunks)
})

for docx files you can use mammoth, it will extract text from .docx files.

var mammoth = require("mammoth");

mammoth.extractRawText({path: "./doc.docx"})
    .then(function(result){
        var text = result.value; // The raw text
        console.log(text);
        var messages = result.messages;
    })
    .done();

I hope this will help.


问:
Add additional menu items to the contextual menu on right click on NSWindow tabs
Currently macOS supports window tabbing and we can merge multiple windows into tabs on a single window. Right now if we do a right click on the tab, it shows default menu items in contextual menu such as "Close Tabs", "Close Other Tabs", "Move Tab to New Window". However Safari tabs has one additional menu item as "Pin Tab" and Xcode tabs has additional item as "New Tab".

I would like to achieve something similar to this in my mac application. How do I add additional menu items to this contextual menu in my application. I have looked into the documentation for NSWindow, NSWindowController and NSDocument but none of it mentions anything about this contextual menu. It would be really helpful if someone who has implemented something similar can share some ideas about how to approach this.

答:
You can observe the NSMenuDidBeginTrackingNotification notification. It will fire before the menu appears. You can add you items to the menu directly, or assign a delegate and add them in the menuNeedsUpdate: method. Be careful not to add your items multiple times, as the notification will fire before the menu opens each time.

The target of the menu item is automatically set to the window represented by the tab. Here is a complete example:

```<code>@implementation TabbedWindow

BOOL didAddMenuItem;

- (void)awakeFromNib
{
    [self toggleTabBar:self];

    self.title = [[NSUUID UUID] UUIDString];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(menuDidStartTracking:) name:@"NSMenuDidBeginTrackingNotification" object:nil];
}

- (IBAction)newWindowForTab:(id)sender
{
    TabbedWindowController* twc = [[TabbedWindowController alloc] initWithWindowNibName:@"TabbedWindowController"];
    [self addTabbedWindow:twc.window ordered:NSWindowAbove];
    [twc.window makeKeyAndOrderFront:nil];
}

- (void)menuDidStartTracking:(NSNotification*)sender
{
    if(didAddMenuItem)
        return;

    NSMenu *tabMenu = (NSMenu *)sender.object;

    NSMenuItem *myMenuItem = [[NSMenuItem alloc] initWithTitle:@"My cool item" action:@selector(myCoolAction:) keyEquivalent:@""];

    NSMenuItem *anotherItem = [tabMenu itemAtIndex:0];
    myMenuItem.target = anotherItem.target;

    [tabMenu addItem:myMenuItem];

    didAddMenuItem = YES;
}

- (void)myCoolAction:(id)sender
{
    NSLog(@"You clicked on the tab for: %@", self.title);
}
</code>```

Note that I tried this code in a custom NSWindow subclass. You may also want to check which NSMenu is sending the notification - depending on your app, it could be a different context menu, the main menu, etc.

Body:
You can observe the NSMenuDidBeginTrackingNotification notification. It will fire before the menu appears. You can add you items to the menu directly, or assign a delegate and add them in the menuNeedsUpdate: method. Be careful not to add your items multiple times, as the notification will fire before the menu opens each time.

The target of the menu item is automatically set to the window represented by the tab. Here is a complete example:

@implementation TabbedWindow

BOOL didAddMenuItem;

- (void)awakeFromNib
{
    [self toggleTabBar:self];

    self.title = [[NSUUID UUID] UUIDString];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(menuDidStartTracking:) name:@"NSMenuDidBeginTrackingNotification" object:nil];
}

- (IBAction)newWindowForTab:(id)sender
{
    TabbedWindowController* twc = [[TabbedWindowController alloc] initWithWindowNibName:@"TabbedWindowController"];
    [self addTabbedWindow:twc.window ordered:NSWindowAbove];
    [twc.window makeKeyAndOrderFront:nil];
}

- (void)menuDidStartTracking:(NSNotification*)sender
{
    if(didAddMenuItem)
        return;

    NSMenu *tabMenu = (NSMenu *)sender.object;

    NSMenuItem *myMenuItem = [[NSMenuItem alloc] initWithTitle:@"My cool item" action:@selector(myCoolAction:) keyEquivalent:@""];

    NSMenuItem *anotherItem = [tabMenu itemAtIndex:0];
    myMenuItem.target = anotherItem.target;

    [tabMenu addItem:myMenuItem];

    didAddMenuItem = YES;
}

- (void)myCoolAction:(id)sender
{
    NSLog(@"You clicked on the tab for: %@", self.title);
}

Note that I tried this code in a custom NSWindow subclass. You may also want to check which NSMenu is sending the notification - depending on your app, it could be a different context menu, the main menu, etc.