问:
SQL - Updating a column from another table while concatenating the related record?
Using SQL, how would I go about updating a column on 1 table, with data from a related/joined table using all the records found, concatenated together? Rather than just updating it based on a specific record, I want to concatenate the fields together and use that for the update.

Table 1

```<code>ID|Col1|Col2
1|Hello|Hello2
2|HelloHello|HelloHello2
</code>```

Table 2

```<code>ParentID|Tbl2Col1|Tbl2Col2
1|Value1|Value2
1|Value1|Value2
1|Value1|Value2
2|Value2|Value3
</code>```

I want to update Table 1, ID 1, Col2 value to be the concatenated values of all the Table 2 Tbl2Col2 child records based on the Table2.ParentID = Table1.ID.

So Table 1 would then look like this when done:

```<code>ID|Col1|Col2
1|Hello|Value2, Value2, Value2
2|HelloHello|HelloHello2
</code>```

ID 1, Col2 is now set to each of the values found from Table 2, Tbl2Col2 column.

Updated 2/17/20
I tried building this out via SQL Fiddle and ran into trouble with the UPDATE statement. I'm able to build out the SELECT query, but I receive an error when I perform the UPDATE: Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

It's actually a bit more complicated too, I need to have Incident.JournalDescriptions end up looking like: Journal.CreatedDateTime + '\n' Journal.Description.

Basically, combine the CreatedDateTime and Description for each of the related Journal records and update the Incident.JournalDescriptions field.

Here's the table structure and queries I've tried:

```<code>CREATE TABLE Incident
    ([RecID] varchar(42), [JournalDescriptions] varchar(max))
;
CREATE TABLE Journal
    ([ParentRecID] varchar(42), [Description] varchar(max), [CreatedDateTime] datetime)
;

INSERT INTO Incident
    ([RecID], [JournalDescriptions])
VALUES
    ('1', ''),
    ('2', '')
;

INSERT INTO Journal
    ([ParentRecID], [Description], [CreatedDateTime])
VALUES
    ('1', 'My Journal Description 1', Getdate()+1),
    ('1', 'My Journal Description 2', Getdate()+2),
    ('2', 'My Journal Description 3', Getdate()+3)
;

-- UPDATE STATEMENT ERRORS: Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
UPDATE Incident
SET JournalDescriptions = (SELECT
  I.RecID,
  I.JournalDescriptions,
  STRING_AGG(J.Description, '<br />') RegDates,
  STRING_AGG(J.CreatedDateTime, '<br />') WaitListDates
FROM
  Incident AS I
  JOIN Journal AS J
  ON I.RecID = J.ParentRecID
GROUP BY I.RecID, I.JournalDescriptions);
WHERE Incident.RecID = '1'

-- SELECT STATEMENT WORKS
SELECT
  I.RecID,
  I.JournalDescriptions,
  STRING_AGG(J.Description, '<br />') RegDates,
  STRING_AGG(J.CreatedDateTime, '<br />') WaitListDates
FROM
  Incident AS I
  JOIN Journal AS J
  ON I.RecID = J.ParentRecID
GROUP BY I.RecID, I.JournalDescriptions
</code>```

Update #2 2/17/20

I was able to get this UPDATE query to work for a SINGLE row only, when I specify the RecID in both the inner/outer clauses.

```<code>UPDATE Incident
SET JournalDescriptions = (SELECT
 STRING_AGG(J.Description + CONVERT(varchar, J.CreatedDateTime), '<br />') AS Updated
FROM
  Incident AS I
  JOIN Journal AS J
  ON I.RecID = J.ParentRecID and I.RecID = '1'
GROUP BY I.RecID)
WHERE Incident.RecID = '1';

SELECT RecID,JournalDescriptions FROM Incident;
</code>```

答:
Thanks everyone for the help/direction.

The actual solution is:

```<code>UPDATE TOP (1000)
       Incident
SET
       AllJournals = STUFF((
    SELECT 'Created: ' + CONVERT(varchar, CreatedDateTime) + CHAR(13) + CHAR(10) + 'Description: ' + Description + CHAR(13) + CHAR(10)
              FROM Journal
              WHERE ParentRecID = RecID
              ORDER BY CreatedDateTime ASC
              FOR XML PATH, TYPE).value(N'.[1]', N'nvarchar(max)'), 1, 0, ''),
       Archived = 1
FROM
       Incident I
WHERE
       CreatedDateTime BETWEEN @Start_Date and @End_Date AND
       Archived != 1
       AND NOT EXISTS (
              SELECT NULL
              FROM ArchiveDB.dbo.Incident I2
              WHERE I2.RecID = I.RecID
       );
</code>```

This code will combine data from the related Journal table based on the RecID column matching. It also only executes the UPDATE when the update has not already happened.

Body:
Using SQL, how would I go about updating a column on 1 table, with data from a related/joined table using all the records found, concatenated together? Rather than just updating it based on a specific record, I want to concatenate the fields together and use that for the update.

Table 1

ID|Col1|Col2
1|Hello|Hello2
2|HelloHello|HelloHello2

Table 2

ParentID|Tbl2Col1|Tbl2Col2
1|Value1|Value2
1|Value1|Value2
1|Value1|Value2
2|Value2|Value3

I want to update Table 1, ID 1, Col2 value to be the concatenated values of all the Table 2 Tbl2Col2 child records based on the Table2.ParentID = Table1.ID.

So Table 1 would then look like this when done:

ID|Col1|Col2
1|Hello|Value2, Value2, Value2
2|HelloHello|HelloHello2

ID 1, Col2 is now set to each of the values found from Table 2, Tbl2Col2 column.

Updated 2/17/20
I tried building this out via SQL Fiddle and ran into trouble with the UPDATE statement. I'm able to build out the SELECT query, but I receive an error when I perform the UPDATE: Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

It's actually a bit more complicated too, I need to have Incident.JournalDescriptions end up looking like: Journal.CreatedDateTime + '\n' Journal.Description.

Basically, combine the CreatedDateTime and Description for each of the related Journal records and update the Incident.JournalDescriptions field.

Here's the table structure and queries I've tried:

CREATE TABLE Incident
    ([RecID] varchar(42), [JournalDescriptions] varchar(max))
;
CREATE TABLE Journal
    ([ParentRecID] varchar(42), [Description] varchar(max), [CreatedDateTime] datetime)
;

INSERT INTO Incident
    ([RecID], [JournalDescriptions])
VALUES
    ('1', ''),
    ('2', '')
;

INSERT INTO Journal
    ([ParentRecID], [Description], [CreatedDateTime])
VALUES
    ('1', 'My Journal Description 1', Getdate()+1),
    ('1', 'My Journal Description 2', Getdate()+2),
    ('2', 'My Journal Description 3', Getdate()+3)
;

-- UPDATE STATEMENT ERRORS: Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
UPDATE Incident
SET JournalDescriptions = (SELECT
  I.RecID,
  I.JournalDescriptions,
  STRING_AGG(J.Description, '
') RegDates,
  STRING_AGG(J.CreatedDateTime, '
') WaitListDates
FROM
  Incident AS I
  JOIN Journal AS J
  ON I.RecID = J.ParentRecID
GROUP BY I.RecID, I.JournalDescriptions);
WHERE Incident.RecID = '1'

-- SELECT STATEMENT WORKS
SELECT
  I.RecID,
  I.JournalDescriptions,
  STRING_AGG(J.Description, '
') RegDates,
  STRING_AGG(J.CreatedDateTime, '
') WaitListDates
FROM
  Incident AS I
  JOIN Journal AS J
  ON I.RecID = J.ParentRecID
GROUP BY I.RecID, I.JournalDescriptions

Update #2 2/17/20

I was able to get this UPDATE query to work for a SINGLE row only, when I specify the RecID in both the inner/outer clauses.

UPDATE Incident
SET JournalDescriptions = (SELECT
 STRING_AGG(J.Description + CONVERT(varchar, J.CreatedDateTime), '
') AS Updated
FROM
  Incident AS I
  JOIN Journal AS J
  ON I.RecID = J.ParentRecID and I.RecID = '1'
GROUP BY I.RecID)
WHERE Incident.RecID = '1';

SELECT RecID,JournalDescriptions FROM Incident;

Body:
Thanks everyone for the help/direction.

The actual solution is:

UPDATE TOP (1000)
       Incident
SET
       AllJournals = STUFF((
    SELECT 'Created: ' + CONVERT(varchar, CreatedDateTime) + CHAR(13) + CHAR(10) + 'Description: ' + Description + CHAR(13) + CHAR(10)
              FROM Journal
              WHERE ParentRecID = RecID
              ORDER BY CreatedDateTime ASC
              FOR XML PATH, TYPE).value(N'.[1]', N'nvarchar(max)'), 1, 0, ''),
       Archived = 1
FROM
       Incident I
WHERE
       CreatedDateTime BETWEEN @Start_Date and @End_Date AND
       Archived != 1
       AND NOT EXISTS (
              SELECT NULL
              FROM ArchiveDB.dbo.Incident I2
              WHERE I2.RecID = I.RecID
       );

This code will combine data from the related Journal table based on the RecID column matching. It also only executes the UPDATE when the update has not already happened.


来源: stackexchange

问:
MESI Protocol & std::atomic - Does it ensure all writes are immediately visible to other threads?
In regards to std::atomic, the C++11 standard states that stores to an atomic variable will become visible to loads of that variable in a "reasonable amount of time".

From 29.3p13:

Implementations should make atomic stores visible to atomic loads within a reasonable amount of time.

However I was curious to know what actually happens when dealing with specific CPU architectures which are based on the MESI cache coherency protocol (x86, x86-64, ARM, etc..).

If my understanding of the MESI protocol is correct, a core will always read the value previously written/being written by another core immediately, possibly by snooping it. (because writing a value means issuing a RFO request which in turn invalidates other cache lines)

Does it mean that when a thread A stores a value into an std::atomic, another thread B which does a load on that atomic successively will in fact always observe the new value written by A on MESI architectures? (Assuming no other threads are doing operations on that atomic)

By “successively” I mean after thread A has issued the atomic store. (Modification order has been updated)

答:
From 29.3p13:

Implementations should make atomic stores visible to atomic loads
  within a reasonable amount of time.

The C and C++ standards are all over the place on threads, hence not usable as formal specifications. They use the concept of time, and somewhat imply that everything runs step by step, sequentially (if not, you wouldn't have a sound program semantic) and then say that some constructs can see effects out of order, without ever telling which is which.

When effects are seen out of order, thread time is ill defined as you don't have a chronometer that would also be out of order: you wouldn't do sport with out of order execution of actions!

Even "out of order" suggests that some things are purely sequential and some other operations can be "out of order" with respect to the firsts. That is not how std::atomic is defined.

What the standards try to say is that there is a notion of progress for each thread, with a CPU time or cost index, and as it increases as more stuff is done, and stuff can only be slightly reordered by the implementation: now reordering is well defined, not in term of other sequential instructions, but in term of cost/cycles/CPU time.

So if two instructions are close to each other in the sequential intra-thread execution, they will be close in CPU time too. A reasonable compiler shouldn't move a volatile operation, a file output, or an atomic operation past a very costly "pure" computation (one that has no externally visible side effect).

A basic idea that many committee members sadly couldn't even spell out!

ContentLicense: CC BY-SA 4.0


问:
detect partial strings and rearrange a csv accordingly
I am very-very new to Python and still learning my way around. I am trying to process some data and I have a very big raw_data.csv file that reads as follows:

```<code>ARB1,k_abc,t_def,s_ghi,1.321
ARB2,ref,k_jkl,t_mno,s_pqr,0.31
ARB3,k_jkl,t_mno,s_pqr,qrs,0.132
ARB4,sql,k_jkl,t_mno,s_pqr,ets,0.023
</code>```

I want to append this data in an existing all_data.csv and it should look like

```<code>ARB1,k_abc,t_def,s_ghi,1.321
ARB2,k_jkl,t_mno,s_pqr,0.31
ARB3,k_jkl,t_mno,s_pqr,0.132
ARB4,k_jkl,t_mno,s_pqr,0.023
</code>```

As you can see, the code has to detect partial strings and numbers and rearrange them in an orderly way (by excluding the cells that don't have them). I was trying to use the csv module with very little luck. Can anyone help please?

答: You can parse this using pandas.read_csv on Pandas. Alternatively, if you don't want to use Pandas, I would recommend simply reading in data, a line at a time and splitting by commas using Python's string operators. You can create a 2-D array that you can populate row-by-row as you read in more data.</p>

Body:
I am very-very new to Python and still learning my way around. I am trying to process some data and I have a very big raw_data.csv file that reads as follows:

ARB1,k_abc,t_def,s_ghi,1.321
ARB2,ref,k_jkl,t_mno,s_pqr,0.31
ARB3,k_jkl,t_mno,s_pqr,qrs,0.132
ARB4,sql,k_jkl,t_mno,s_pqr,ets,0.023

I want to append this data in an existing all_data.csv and it should look like

ARB1,k_abc,t_def,s_ghi,1.321
ARB2,k_jkl,t_mno,s_pqr,0.31
ARB3,k_jkl,t_mno,s_pqr,0.132
ARB4,k_jkl,t_mno,s_pqr,0.023

As you can see, the code has to detect partial strings and numbers and rearrange them in an orderly way (by excluding the cells that don't have them). I was trying to use the csv module with very little luck. Can anyone help please?


问:
Using HttpClient and HttpPost in Android with post parameters
I'm writing code for an Android application that is supposed to take data, package it as Json and post it to a web server, that in turn is supposed to respond with json.

Using a GET request works fine, but for some reason using POST all data seems to get stripped and the server does not receive anything.

Here's a snippet of the code:

```<code>HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 5000);
DefaultHttpClient httpClient = new DefaultHttpClient(params);
BasicCookieStore cookieStore = new BasicCookieStore();
httpClient.setCookieStore(cookieStore);

String uri = JSON_ADDRESS;
String result = "";
String username = "user";
String apikey = "something";
String contentType = "application/json";

JSONObject jsonObj = new JSONObject();

try {
    jsonObj.put("username", username);
    jsonObj.put("apikey", apikey);
} catch (JSONException e) {
    Log.e(TAG, "JSONException: " + e);
}

HttpPost httpPost = new HttpPost(uri);
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("json", jsonObj.toString()));
HttpGet httpGet = null;
try {
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
    entity.setContentEncoding(HTTP.UTF_8);
    entity.setContentType("application/json");
    httpPost.setEntity(entity);

    httpPost.setHeader("Content-Type", contentType);
    httpPost.setHeader("Accept", contentType);
} catch (UnsupportedEncodingException e) {
    Log.e(TAG, "UnsupportedEncodingException: " + e);
}

try {
    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();

    if (httpEntity != null) {
        InputStream is = httpEntity.getContent();
        result = StringUtils.convertStreamToString(is);
        Log.i(TAG, "Result: " + result);
    }
} catch (ClientProtocolException e) {
    Log.e(TAG, "ClientProtocolException: " + e);
} catch (IOException e) {
    Log.e(TAG, "IOException: " + e);
}

return result;
</code>```

I think I have followed the general guidelines on how to create the parameters and post them, but apparently not.

Any help or pointers to where I can find a solution, are very welcome at this point (after spending a few hours realizing no post data was ever sent). The real server is running Wicket on Tomcat, but I've also tested it out on a simple PHP page, with no difference.

答:
I've just checked and i have the same code as you and it works perferctly.
The only difference is how i fill my List for the params :

I use a : ArrayList<BasicNameValuePair> params

and fill it this way :

```<code> params.add(new BasicNameValuePair("apikey", apikey);
</code>```

I do not use any JSONObject to send params to the webservices.

Are you obliged to use the JSONObject ?

ContentLicense: CC BY-SA 3.0

Body:
I'm writing code for an Android application that is supposed to take data, package it as Json and post it to a web server, that in turn is supposed to respond with json.

Using a GET request works fine, but for some reason using POST all data seems to get stripped and the server does not receive anything.

Here's a snippet of the code:

HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 5000);
DefaultHttpClient httpClient = new DefaultHttpClient(params);
BasicCookieStore cookieStore = new BasicCookieStore();
httpClient.setCookieStore(cookieStore);

String uri = JSON_ADDRESS;
String result = "";
String username = "user";
String apikey = "something";
String contentType = "application/json";

JSONObject jsonObj = new JSONObject();

try {
    jsonObj.put("username", username);
    jsonObj.put("apikey", apikey);
} catch (JSONException e) {
    Log.e(TAG, "JSONException: " + e);
}

HttpPost httpPost = new HttpPost(uri);
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("json", jsonObj.toString()));
HttpGet httpGet = null;
try {
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
    entity.setContentEncoding(HTTP.UTF_8);
    entity.setContentType("application/json");
    httpPost.setEntity(entity);

    httpPost.setHeader("Content-Type", contentType);
    httpPost.setHeader("Accept", contentType);
} catch (UnsupportedEncodingException e) {
    Log.e(TAG, "UnsupportedEncodingException: " + e);
}

try {
    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();

    if (httpEntity != null) {
        InputStream is = httpEntity.getContent();
        result = StringUtils.convertStreamToString(is);
        Log.i(TAG, "Result: " + result);
    }
} catch (ClientProtocolException e) {
    Log.e(TAG, "ClientProtocolException: " + e);
} catch (IOException e) {
    Log.e(TAG, "IOException: " + e);
}

return result;

I think I have followed the general guidelines on how to create the parameters and post them, but apparently not.

Any help or pointers to where I can find a solution, are very welcome at this point (after spending a few hours realizing no post data was ever sent). The real server is running Wicket on Tomcat, but I've also tested it out on a simple PHP page, with no difference.

Body:
I've just checked and i have the same code as you and it works perferctly.
The only difference is how i fill my List for the params :

I use a : ArrayList<BasicNameValuePair> params

and fill it this way :

 params.add(new BasicNameValuePair("apikey", apikey);

I do not use any JSONObject to send params to the webservices.

Are you obliged to use the JSONObject ?


问:
Github, create issue on repository without requiring a github user account
I have an electron app that has a bug reporting feature.  I would like this bug reporter to use the github API to create an issue automatically.  Here is the catch, I don't want my users to create and use their own github account to do so.

Is it possible to use the github API to create issues, without requiring an account?

My current workaround is to simply create a 'bug reporting' account, and share that account's access token with the source code. That way, whenever anybody creates an issue it's listed under that user. Seems like a stretch, and I'm wondering if there is a better way to approach this problem.

答:
I just discovered Git Reports while searching for the same thing.

From the website:

Git Reports is a free service that lets you set up a stable URL for anonymous users to submit bugs and other Issues to your GitHub repositories, without exposing your code, requiring users to log in with GitHub, or using a messy two-repository solution. It works with public and private repositories, and it works with personal and organization repositories.

Hope that helps!


问:
Splitting by word boundaries including apostrophes
I want to split each word of a string including spaces and punctuations in different groups, but I want to keep words with apostrophes together.

For example:

```<code>Phrase: This is right.
Groups: [This] [ ] [is] [ ] [right] [.]

Phrase: This isn't right.
Groups: [This] [ ] [isn't] [ ] [right] [.]

Phrase: "I said ok."
Groups: ["] [I] [ ] [said] [ ] [ok] [.] ["]
</code>```

I'm using the regular expression: str.split(/(?=[.,"\s]|\b)/)

However, this doesn't work with apostrophes. For the phase: This isn't right. , it's splitting like:

```<code>[This] [ ] [isn] ['] [t] [ ] [right] [.]
</code>```

Is there a way to keep the isn't in a single group?

答:
I'd use .match instead: match a word character followed by (word characters or apostrophes) (\w[\w']*), or match spaces: +, or match other punctuation ([.,"]):

```<code>\w[\w']*| +|[.,"]
</code>```

https://regex101.com/r/B755JA/1

const inputs = `This is right.
This isn't right.
"I said ok."`.split('\n');
for (const input of inputs) {
  console.log(input.match(/\w[\w']*| +|[.,"]/g));
}```

Body:
I want to split each word of a string including spaces and punctuations in different groups, but I want to keep words with apostrophes together.

For example:

Phrase: This is right.
Groups: [This] [ ] [is] [ ] [right] [.]

Phrase: This isn't right.
Groups: [This] [ ] [isn't] [ ] [right] [.]

Phrase: "I said ok."
Groups: ["] [I] [ ] [said] [ ] [ok] [.] ["]

I'm using the regular expression: str.split(/(?=[.,"\s]|\b)/)

However, this doesn't work with apostrophes. For the phase: This isn't right. , it's splitting like:

[This] [ ] [isn] ['] [t] [ ] [right] [.]

Is there a way to keep the isn't in a single group?

Body:
I'd use .match instead: match a word character followed by (word characters or apostrophes) (\w[\w']*), or match spaces: +, or match other punctuation ([.,"]):

\w[\w']*| +|[.,"]

https://regex101.com/r/B755JA/1

const inputs = `This is right.
This isn't right.
"I said ok."`.split('\n');
for (const input of inputs) {
  console.log(input.match(/\w[\w']*| +|[.,"]/g));
}


问:
Cannot find setter for field - using Kotlin with Room database
I'm integrating with the Room persistence library. I have a data class in Kotlin like:

```<code>@Entity(tableName = "story")
data class Story (
        @PrimaryKey val id: Long,
        val by: String,
        val descendants: Int,
        val score: Int,
        val time: Long,
        val title: String,
        val type: String,
        val url: String
)
</code>```

The @Entity and @PrimaryKey annotations are for the Room library. When I try to build, it is failing with error:

```<code>Error:Cannot find setter for field.
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
</code>```

I also tried providing a default constructor:

```<code>@Entity(tableName = "story")
data class Story (
        @PrimaryKey val id: Long,
        val by: String,
        val descendants: Int,
        val score: Int,
        val time: Long,
        val title: String,
        val type: String,
        val url: String
) {
    constructor() : this(0, "", 0, 0, 0, "", "", "")
}
</code>```

But this doesn't work as well. A thing to note is that it works if I convert this Kotlin class into a Java class with getters and setters. Any help is appreciated!

答:
I've found that another cause of this compilation error can be due to the use of the Room's @Ignore annotation on fields of your entity data class:

```<code>@Entity(tableName = "foo")
data class Foo(

    // Okay
    @PrimaryKey
    val id: String,

    // Okay
    val bar: String,

    // Annotation causes compilation error, all fields of data class report
    // the "Cannot find setter for field" error when Ignore is present
    @Ignore
    val causeserror: String
)
</code>```

The same error also seems to happens when using the @Transient annotation.

I've noticed this issue using version 2.2.2 of Room:

```<code>// build.gradle file
dependencies {
   ...
   kapt "androidx.room:room-compiler:2.2.2"
   ...
}
</code>```

Hope that helps someone!

Body:
I'm integrating with the Room persistence library. I have a data class in Kotlin like:

@Entity(tableName = "story")
data class Story (
        @PrimaryKey val id: Long,
        val by: String,
        val descendants: Int,
        val score: Int,
        val time: Long,
        val title: String,
        val type: String,
        val url: String
)

The @Entity and @PrimaryKey annotations are for the Room library. When I try to build, it is failing with error:

Error:Cannot find setter for field.
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

I also tried providing a default constructor:

@Entity(tableName = "story")
data class Story (
        @PrimaryKey val id: Long,
        val by: String,
        val descendants: Int,
        val score: Int,
        val time: Long,
        val title: String,
        val type: String,
        val url: String
) {
    constructor() : this(0, "", 0, 0, 0, "", "", "")
}

But this doesn't work as well. A thing to note is that it works if I convert this Kotlin class into a Java class with getters and setters. Any help is appreciated!

Body:
I've found that another cause of this compilation error can be due to the use of the Room's @Ignore annotation on fields of your entity data class:

@Entity(tableName = "foo")
data class Foo(

    // Okay
    @PrimaryKey
    val id: String,

    // Okay
    val bar: String,

    // Annotation causes compilation error, all fields of data class report
    // the "Cannot find setter for field" error when Ignore is present
    @Ignore
    val causeserror: String
)

The same error also seems to happens when using the @Transient annotation.

I've noticed this issue using version 2.2.2 of Room:

// build.gradle file
dependencies {
   ...
   kapt "androidx.room:room-compiler:2.2.2"
   ...
}

Hope that helps someone!


问:
Docker Compose : Percona XtraDB Cluster Bootstrapping
I need some help. How can I bootstrap a Percona XtraDB Cluster on a docker-compose as 1st node?

I have this my.cnf file

```<code>wsrep_provider=/usr/lib64/galera3/libgalera_smm.so
wsrep_cluster_name=pxc-cluster
wsrep_cluster_address=gcomm://192.168.56.15,192.168.56.20,192.168.56.25
wsrep_node_name=pxc1
wsrep_node_address=192.168.56.15
wsrep_sst_method=xtrabackup-v2
wsrep_sst_auth=xtrabackup:1q2w3e4r
pxc_strict_mode=ENFORCING
!include /etc/mysql/node.cnf
</code>```

and docker-compose.yml

```<code>version: '2'
services:
    percona-xtradb-cluster:
        container_name: pxc_node
        image: 'percona/percona-xtradb-cluster:5.7'
        environment:
            - MYSQL_ROOT_PASSWORD=root
            - CLUSTER_NAME=pxc-cluster
            - XTRABACKUP_PASSWORD=1q2w3e4r
        ports:
            - 3306:3306
            - 4567:4567
            - 4568:4568
            - 4444:4444
        volumes:
            - /etc/percona.d/my.cnf:/etc/my.cnf
</code>```

run sudo docker-compose up -d

答:
according to manual, it seems you should start 2nd and 3rd servers only after 1st server is started, so, with your docker compose it should be something like this

```<code>

version: '2'
services:
    percona-xtradb-cluster:
        container_name: pxc_node
        image: 'percona/percona-xtradb-cluster:5.7'
        environment:
            - MYSQL_ROOT_PASSWORD=root
            - CLUSTER_NAME=pxc-cluster
            - XTRABACKUP_PASSWORD=1q2w3e4r
        ports:
            - 3306:3306
            - 4567:4567
            - 4568:4568
            - 4444:4444
        volumes:
            - /etc/percona.d/my.cnf:/etc/my.cnf

    percona-xtradb-server1:
        depends_on:
          - percona-xtradb-cluster
        container_name: pxc_node1
        image: 'percona/percona-xtradb-cluster:5.7'
        environment:
            - MYSQL_ROOT_PASSWORD=root
            - CLUSTER_NAME=pxc-cluster
            - CLUSTER_JOIN=pxc_node
            - XTRABACKUP_PASSWORD=1q2w3e4r
        volumes:
            - /etc/percona.d/my.cnf:/etc/my.cnf

    percona-xtradb-server2:
        depends_on:
          - percona-xtradb-cluster
        container_name: pxc_node2
        image: 'percona/percona-xtradb-cluster:5.7'
        environment:
            - MYSQL_ROOT_PASSWORD=root
            - CLUSTER_NAME=pxc-cluster
            - XTRABACKUP_PASSWORD=1q2w3e4r
            - CLUSTER_JOIN=pxc_node
        volumes:
            - /etc/percona.d/my.cnf:/etc/my.cnf

</code>```

Notice depends fields - they are important - see documentation.
And see CLUSTER_JOIN=pxc_node present, they indicate what server to join

Body:
I need some help. How can I bootstrap a Percona XtraDB Cluster on a docker-compose as 1st node?

I have this my.cnf file

wsrep_provider=/usr/lib64/galera3/libgalera_smm.so
wsrep_cluster_name=pxc-cluster
wsrep_cluster_address=gcomm://192.168.56.15,192.168.56.20,192.168.56.25
wsrep_node_name=pxc1
wsrep_node_address=192.168.56.15
wsrep_sst_method=xtrabackup-v2
wsrep_sst_auth=xtrabackup:1q2w3e4r
pxc_strict_mode=ENFORCING
!include /etc/mysql/node.cnf

and docker-compose.yml

version: '2'
services:
    percona-xtradb-cluster:
        container_name: pxc_node
        image: 'percona/percona-xtradb-cluster:5.7'
        environment:
            - MYSQL_ROOT_PASSWORD=root
            - CLUSTER_NAME=pxc-cluster
            - XTRABACKUP_PASSWORD=1q2w3e4r
        ports:
            - 3306:3306
            - 4567:4567
            - 4568:4568
            - 4444:4444
        volumes:
            - /etc/percona.d/my.cnf:/etc/my.cnf

run sudo docker-compose up -d

Body:
according to manual, it seems you should start 2nd and 3rd servers only after 1st server is started, so, with your docker compose it should be something like this

version: '2'
services:
    percona-xtradb-cluster:
        container_name: pxc_node
        image: 'percona/percona-xtradb-cluster:5.7'
        environment:
            - MYSQL_ROOT_PASSWORD=root
            - CLUSTER_NAME=pxc-cluster
            - XTRABACKUP_PASSWORD=1q2w3e4r
        ports:
            - 3306:3306
            - 4567:4567
            - 4568:4568
            - 4444:4444
        volumes:
            - /etc/percona.d/my.cnf:/etc/my.cnf

    percona-xtradb-server1:
        depends_on:
          - percona-xtradb-cluster
        container_name: pxc_node1
        image: 'percona/percona-xtradb-cluster:5.7'
        environment:
            - MYSQL_ROOT_PASSWORD=root
            - CLUSTER_NAME=pxc-cluster
            - CLUSTER_JOIN=pxc_node
            - XTRABACKUP_PASSWORD=1q2w3e4r
        volumes:
            - /etc/percona.d/my.cnf:/etc/my.cnf

    percona-xtradb-server2:
        depends_on:
          - percona-xtradb-cluster
        container_name: pxc_node2
        image: 'percona/percona-xtradb-cluster:5.7'
        environment:
            - MYSQL_ROOT_PASSWORD=root
            - CLUSTER_NAME=pxc-cluster
            - XTRABACKUP_PASSWORD=1q2w3e4r
            - CLUSTER_JOIN=pxc_node
        volumes:
            - /etc/percona.d/my.cnf:/etc/my.cnf

Notice depends fields - they are important - see documentation.
And see CLUSTER_JOIN=pxc_node present, they indicate what server to join


问:
When to prefer `and` over `andalso` in guard tests
I am curious why the comma ‹,› is a shortcut for and and not andalso in guard tests.

Since I'd call myself a “C native” I fail to see any shortcomings of short-circuit boolean evaluation.

I compiled some test code using the to_core flag to see what code is actually generated. Using the comma, I see the left hand value and right and value get evaluated and both and'ed. With andalso you have a case block within the case block and no call to erlang:and/2.

I did no benchmark tests but I daresay the andalso variant is the faster one.

答:
Adam Lindbergs link is right. Using the comma does generate better beam code than using andalso. I compiled the following code using the +to_asm flag:

```<code>a(A,B) ->
    case ok of
        _ when A, B -> true;
        _ -> false
    end.
aa(A,B) ->
    case ok of
        _ when A andalso B -> true;
        _ -> false
    end.
</code>```

which generates

```<code>{function, a, 2, 2}.
  {label,1}.
    {func_info,{atom,andAndAndalso},{atom,a},2}.
  {label,2}.
    {test,is_eq_exact,{f,3},[{x,0},{atom,true}]}.
    {test,is_eq_exact,{f,3},[{x,1},{atom,true}]}.
    {move,{atom,true},{x,0}}.
    return.
  {label,3}.
    {move,{atom,false},{x,0}}.
    return.

{function, aa, 2, 5}.
  {label,4}.
    {func_info,{atom,andAndAndalso},{atom,aa},2}.
  {label,5}.
    {test,is_atom,{f,7},[{x,0}]}.
    {select_val,{x,0},{f,7},{list,[{atom,true},{f,6},{atom,false},{f,9}]}}.
  {label,6}.
    {move,{x,1},{x,2}}.
    {jump,{f,8}}.
  {label,7}.
    {move,{x,0},{x,2}}.
  {label,8}.
    {test,is_eq_exact,{f,9},[{x,2},{atom,true}]}.
    {move,{atom,true},{x,0}}.
    return.
  {label,9}.
    {move,{atom,false},{x,0}}.
    return.
</code>```

I only looked into what is generated with the +to_core flag, but obviously there is a optimization step between to_core and to_asm.

Body:
Adam Lindbergs link is right. Using the comma does generate better beam code than using andalso. I compiled the following code using the +to_asm flag:

a(A,B) ->
    case ok of
        _ when A, B -> true;
        _ -> false
    end.
aa(A,B) ->
    case ok of
        _ when A andalso B -> true;
        _ -> false
    end.

which generates

{function, a, 2, 2}.
  {label,1}.
    {func_info,{atom,andAndAndalso},{atom,a},2}.
  {label,2}.
    {test,is_eq_exact,{f,3},[{x,0},{atom,true}]}.
    {test,is_eq_exact,{f,3},[{x,1},{atom,true}]}.
    {move,{atom,true},{x,0}}.
    return.
  {label,3}.
    {move,{atom,false},{x,0}}.
    return.

{function, aa, 2, 5}.
  {label,4}.
    {func_info,{atom,andAndAndalso},{atom,aa},2}.
  {label,5}.
    {test,is_atom,{f,7},[{x,0}]}.
    {select_val,{x,0},{f,7},{list,[{atom,true},{f,6},{atom,false},{f,9}]}}.
  {label,6}.
    {move,{x,1},{x,2}}.
    {jump,{f,8}}.
  {label,7}.
    {move,{x,0},{x,2}}.
  {label,8}.
    {test,is_eq_exact,{f,9},[{x,2},{atom,true}]}.
    {move,{atom,true},{x,0}}.
    return.
  {label,9}.
    {move,{atom,false},{x,0}}.
    return.

I only looked into what is generated with the +to_core flag, but obviously there is a optimization step between to_core and to_asm.


答:
You may try finding all regex matches on the pattern [A-Za-z']+|[^A-Za-z'], which matches either a word (letters or apostrophe), or a single non word character.

var regex = /[A-Za-z']+|[^A-Za-z']/g;
var input = "\"This isn't right.\"";
var m;
var matches = [];

var i = 0;
do {
    m = regex.exec(input);
    if (m) {
        matches[i] = m[0];
        ++i;
    }
} while (m);

console.log(matches);```

Note that using a direct regex find all approach is sometimes preferable to a more complicated regex splitting logic.

Title: Splitting by word boundaries including apostrophes

Body:
You may try finding all regex matches on the pattern [A-Za-z']+|[^A-Za-z'], which matches either a word (letters or apostrophe), or a single non word character.

var regex = /[A-Za-z']+|[^A-Za-z']/g;
var input = "\"This isn't right.\"";
var m;
var matches = [];

var i = 0;
do {
    m = regex.exec(input);
    if (m) {
        matches[i] = m[0];
        ++i;
    }
} while (m);

console.log(matches);

Note that using a direct regex find all approach is sometimes preferable to a more complicated regex splitting logic.


问:
useState on React Hooks not updating Array
I have tried many things and can't seem to understand why setTypes won't update the 'types' array??

```<code>import { useState, useEffect } from 'react';
import { PostList } from './post-list';
import * as api from '../utils/api';

export const PostSelector = (props) => {
  const [posts, setPosts]     = useState([]);
  const [loading, setLoading] = useState(false);
  const [type, setType]       = useState('post');
  const [types, setTypes]     = useState([]);

  const fetchTypes = async () => {
    setLoading(true);
    const response = await api.getPostTypes();
    delete response.data.attachment;
    delete response.data.wp_block;
    const postTypes = response.data;
    console.log(response.data); // {post: {…}, page: {…}, case: {…}}
    setTypes(postTypes);
    console.log(types); // []

    // Why types remain empty??
  }

const loadPosts = async (args = {}) => {
  const defaultArgs = { per_page: 10, type };
  const requestArgs = { ...defaultArgs, ...args };

  requestArgs.restBase = types[requestArgs.type].rest_base; // Cannot read property 'rest_base' of undefined

  const response = await api.getPosts(requestArgs);
  console.log(response.data);
}

useEffect(() => {
  fetchTypes();
  loadPosts();
}, []);

  return (
    <div className="filter">
      <label htmlFor="options">Post Type: </label>
      <select name="options" id="options">
        { types.length < 1 ? (<option value="">loading</option>) : Object.keys(types).map((key, index) => <option key={ index } value={ key }>{ types[key].name }</option> ) }
      </select>
    </div>
  );
}
</code>```

Please, take a look at the console.log and notice the different responses.

What I am trying to do is to load list of types, in this case 'post', 'page' and 'case' and then render a list of posts based on the current 'type'. The default type is 'post'.

If I add [types] to useEffect. I finally get the values but the component renders nonstop.

Thanks to everyone for your comments. Multiple people have pointed out the problem, being that, the fact that we set the state doesn't mean it will set right away because it it asynchronous.

How do we solve this problem then? Regardless of the reasons, how do we get it done? How do we work with our state at any point in time and perform calculations based on our state if we don't know when it will become available? How do we make sure we wait whatever we need to and then use the values we expect?

答:
useState's setTypes is an asynchronous function so the changes do not take effect immediately. You can use useEffect to check if anything changes

```<code>useEffect(()=>{
    const defaultArgs = { per_page: 10, type };
    const requestArgs = { ...defaultArgs, ...args };
    requestArgs.restBase = types;
    console.log("types updated",types)
},[types])
</code>```

You can remove loadPosts because now useEffect will run whenever types change

Body:
I have tried many things and can't seem to understand why setTypes won't update the 'types' array??

import { useState, useEffect } from 'react';
import { PostList } from './post-list';
import * as api from '../utils/api';

export const PostSelector = (props) => {
  const [posts, setPosts]     = useState([]);
  const [loading, setLoading] = useState(false);
  const [type, setType]       = useState('post');
  const [types, setTypes]     = useState([]);

  const fetchTypes = async () => {
    setLoading(true);
    const response = await api.getPostTypes();
    delete response.data.attachment;
    delete response.data.wp_block;
    const postTypes = response.data;
    console.log(response.data); // {post: {…}, page: {…}, case: {…}}
    setTypes(postTypes);
    console.log(types); // []

    // Why types remain empty??
  }

const loadPosts = async (args = {}) => {
  const defaultArgs = { per_page: 10, type };
  const requestArgs = { ...defaultArgs, ...args };

  requestArgs.restBase = types[requestArgs.type].rest_base; // Cannot read property 'rest_base' of undefined

  const response = await api.getPosts(requestArgs);
  console.log(response.data);
}

useEffect(() => {
  fetchTypes();
  loadPosts();
}, []);

  return (

      Post Type:
      <select name="options" id="options">
        { types.length < 1 ? (<option value="">loading</option>) : Object.keys(types).map((key, index) => <option key={ index } value={ key }>{ types[key].name }</option> ) }
      </select>

  );
}

Please, take a look at the console.log and notice the different responses.

What I am trying to do is to load list of types, in this case 'post', 'page' and 'case' and then render a list of posts based on the current 'type'. The default type is 'post'.

If I add [types] to useEffect. I finally get the values but the component renders nonstop.

Thanks to everyone for your comments. Multiple people have pointed out the problem, being that, the fact that we set the state doesn't mean it will set right away because it it asynchronous.

How do we solve this problem then? Regardless of the reasons, how do we get it done? How do we work with our state at any point in time and perform calculations based on our state if we don't know when it will become available? How do we make sure we wait whatever we need to and then use the values we expect?

Body:
useState's setTypes is an asynchronous function so the changes do not take effect immediately. You can use useEffect to check if anything changes

useEffect(()=>{
    const defaultArgs = { per_page: 10, type };
    const requestArgs = { ...defaultArgs, ...args };
    requestArgs.restBase = types;
    console.log("types updated",types)
},[types])

You can remove loadPosts because now useEffect will run whenever types change


问:
navigator.clipboard is undefined
Why is navigator.clipboard always undefined in the following snippet?

```<code>var clipboard = navigator.clipboard;
if (clipboard == undefined) {
    console.log('clipboard is undefined');
} else {
    clipboard.writeText('stuff to write').then(function() {
        console.log('Copied to clipboard successfully!');
    }, function() {
        console.error('Unable to write to clipboard. :-(');
    });
}
</code>```

More on the clipboard API can be found here.

Chrome Version: 68.0.3440.106.

I'm sure this was working at some point, but no longer is.  It's confusing because this table suggests that the Clipboard API is implemented in Chrome (has been for some time), but this table of specific API methods suggests that none of the methods of the API is supported??

答:
Try this:

if (typeof (navigator.clipboard) == 'undefined') {
    console.log('navigator.clipboard');
    var textArea = document.createElement("textarea");
    textArea.value = linkToGo;
    textArea.style.position = "fixed";  //avoid scrolling to bottom
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();

    try {
        var successful = document.execCommand('copy');
        var msg = successful ? 'successful' : 'unsuccessful';
        toastr.info(msg);
    } catch (err) {
        toastr.warning('Was not possible to copy te text: ', err);
    }

    document.body.removeChild(textArea)
    return;
}
navigator.clipboard.writeText(linkToGo).then(function () {
    toastr.info(`successful!`);
}, function (err) {
    toastr.warning('unsuccessful!', err);
});
```

Title: navigator.clipboard is undefined

Body:
Why is navigator.clipboard always undefined in the following snippet?

var clipboard = navigator.clipboard;
if (clipboard == undefined) {
    console.log('clipboard is undefined');
} else {
    clipboard.writeText('stuff to write').then(function() {
        console.log('Copied to clipboard successfully!');
    }, function() {
        console.error('Unable to write to clipboard. :-(');
    });
}

More on the clipboard API can be found here.

Chrome Version: 68.0.3440.106.

I'm sure this was working at some point, but no longer is.  It's confusing because this table suggests that the Clipboard API is implemented in Chrome (has been for some time), but this table of specific API methods suggests that none of the methods of the API is supported??


问:
In an MVC5 controller how do I create an IDictionary or routeValueDictionary for an HtmlHelper's htmlAttributes or routeValues?
MVC5

The ultimate objective is to create the view's links in the controller because they change based on program logic.

The following link compiles and runs:

```<code>Dim myLink = HtmlHelper.GenerateLink(Request.RequestContext, RouteTable.Routes, "edit", "Default", "Edit", "Role", Nothing, Nothing)
</code>```

The line above generates: edit.  This is then displayed in the view using html.raw and results in the link: http://localhost:53908/Role/Edit

The link displayed above navigates correctly, but won't work with the action method because I need to pass an ID parameter, so I tried to change the last parameter in the helper as follows:

```<code>Dim myLink = HtmlHelper.GenerateLink(Request.RequestContext, RouteTable.Routes, "edit", "Default", "Edit", "Role", Nothing, New With {.ID = "somedata"})
</code>```

But the line above returns a syntax warning and the code can't run:

```<code>Runtime errors might occur when converting '<anonymous type: ID As String>' to 'IDictionary(Of String, Object)'
</code>```

So then I tried to create an IDictionary as below to pass into the helper:

```<code>Dim temp As IDictionary(Of String, String)
temp.Add("ID", "somedata")
Dim myLink = HtmlHelper.GenerateLink(Request.RequestContext, RouteTable.Routes, "edit", "Default", "Edit", "Role", Nothing, temp)
</code>```

The code above satisfies the HtmlHelper, but the temp.Add line doesn't work because:

```<code>temp is used before it has been assigned a value.
</code>```

A null reference exception occurs at runtime.  I'm not particularly conversant with IDictionary and couldn't figure out what to do next.

So I have a series of questions:

Is there a way to create the IDictionary asked for by the helper 'on the fly' with the call to the helper?

Should I be using the HtmlHelper.GenerateLink method differently?

How do I create an IDictionary?

Added after the original post:

The initial question concerned creating an in-place IDictionary to make use of HtmlHelpers in the Controller so that creating links could be accomplished in code rather than in the view.  The overall intent is to allow Controller code to perform the necessary logic and calculate links rather than doing that in the view.

The initial question posed dealt with htmlAttributes by accident because in this particular case the real need was to create routeValues.  But the answer below actually serves to inform how to do both.

The key to success was using the proper keywords.  In the case of creating either a New RouteValueDictionary or a New IDictionary, the New Dictionary(Of String, Object) must be used, meaning the keyword Object is required, and the keyword From is necessary to setup the in-place record definitions.  In MVC5 the syntax New Dictionary(Of String, String) is seen as an anonymous type and can't be converted to an IDictionary, in-place or otherwise.

The final code used in the Controller to setup an equivalent ActionLink in the view, based on the answer below, was:

```<code>Dim editLink = HtmlHelper.GenerateLink(Request.RequestContext,
    RouteTable.Routes,
    "Edit",      'the link text
    "Default",   'a route name, can found in RouteConfig.vb
    "Edit",      'the target ActionResult method
    "Role",      'the target Controller
    New RouteValueDictionary(New Dictionary(Of String, Object) From {"ID", role.Id}, {"selectedDomain", selectedDomain}}),
    Nothing)
</code>```

In the case above, a second route value was added to the routeValueDictionary as needed by the ActionResult method.

If htmlAttributes are also required they can be added in place of the final Nothing show above, as specified in the answer below.

答:
The parameter is type IDictionary(Of String, Object).  That's just an interface, so you need to create an object of a type that implements that interface.  The obvious choice is Dictionary(Of String, Object), e.g.

Dim temp As IDictionary(Of String, Object) = New Dictionary(Of String, Object)
temp.Add("ID", "somedata")
Dim myLink = HtmlHelper.GenerateLink(Request.RequestContext, RouteTable.Routes, "edit", "Default", "Edit", "Role", Nothing, temp)
```

<p>I can't recall when anonymous types started being supported in such scenarios but it appears that it was later than MVC 5.  If you want to be able to use anonymous types then you would have to write your own method that accepts an anonymous type, uses Reflection to extract the data from it, builds a dictionary and then calls the existing method.  You might do that like this:</p>

<pre class="lang-vb prettyprint-override"><code>Public Module HtmlHelperExtender

    Public Function GenerateLink(requestContext As RequestContext,
                                 routeCollection As RouteCollection,
                                 linkText As String,
                                 routeName As String,
                                 actionName As String,
                                 controllerName As String,
                                 routeValues As RouteValueDictionary,
                                 htmlAttributes As Object) As String
        'Create a dictionary from the properties of the anonymously typed object.
        Dim attributesType = htmlAttributes.GetType()
        Dim properties = attributesType.GetProperties()
        Dim htmlAttributesDictionary = properties.ToDictionary(Function(p) p.Name, Function(p) p.GetValue(htmlAttributes))

        Return HtmlHelper.GenerateLink(requestContext,
                                       routeCollection,
                                       linkText,
                                       routeName,
                                       actionName,
                                       controllerName,
                                       routeValues,
                                       htmlAttributesDictionary)
    End Function

End Module
</code>```

You can then call that method much like you were originally trying to:

Dim myLink = HtmlHelperExtender.GenerateLink(Request.RequestContext,
                                             RouteTable.Routes,
                                             "edit",
                                             "Default",
                                             "Edit",
                                             "Role",
                                             Nothing,
                                             New With {.ID = "somedata"})
```

<p>Another option that just occurred to me is to stick with the dictionary but create and populate it in-place, which is possible using the <code>From</code> keyword:</p>

<pre class="lang-vb prettyprint-override"><code>Dim myLink = HtmlHelper.GenerateLink(Request.RequestContext,
                                     RouteTable.Routes,
                                     "edit",
                                     "Default",
                                     "Edit",
                                     "Role",
                                     Nothing,
                                     New Dictionary(Of String, Object) From {{"ID", "somedata"}})
</code>```

Body:
MVC5

The ultimate objective is to create the view's links in the controller because they change based on program logic.

The following link compiles and runs:

Dim myLink = HtmlHelper.GenerateLink(Request.RequestContext, RouteTable.Routes, "edit", "Default", "Edit", "Role", Nothing, Nothing)

The line above generates: edit.  This is then displayed in the view using html.raw and results in the link: http://localhost:53908/Role/Edit

The link displayed above navigates correctly, but won't work with the action method because I need to pass an ID parameter, so I tried to change the last parameter in the helper as follows:

Dim myLink = HtmlHelper.GenerateLink(Request.RequestContext, RouteTable.Routes, "edit", "Default", "Edit", "Role", Nothing, New With {.ID = "somedata"})

But the line above returns a syntax warning and the code can't run:

Runtime errors might occur when converting '<anonymous type: ID As String>' to 'IDictionary(Of String, Object)'

So then I tried to create an IDictionary as below to pass into the helper:

Dim temp As IDictionary(Of String, String)
temp.Add("ID", "somedata")
Dim myLink = HtmlHelper.GenerateLink(Request.RequestContext, RouteTable.Routes, "edit", "Default", "Edit", "Role", Nothing, temp)

The code above satisfies the HtmlHelper, but the temp.Add line doesn't work because:

temp is used before it has been assigned a value.

A null reference exception occurs at runtime.  I'm not particularly conversant with IDictionary and couldn't figure out what to do next.

So I have a series of questions:

Is there a way to create the IDictionary asked for by the helper 'on the fly' with the call to the helper?

Should I be using the HtmlHelper.GenerateLink method differently?

How do I create an IDictionary?

Added after the original post:

The initial question concerned creating an in-place IDictionary to make use of HtmlHelpers in the Controller so that creating links could be accomplished in code rather than in the view.  The overall intent is to allow Controller code to perform the necessary logic and calculate links rather than doing that in the view.

The initial question posed dealt with htmlAttributes by accident because in this particular case the real need was to create routeValues.  But the answer below actually serves to inform how to do both.

The key to success was using the proper keywords.  In the case of creating either a New RouteValueDictionary or a New IDictionary, the New Dictionary(Of String, Object) must be used, meaning the keyword Object is required, and the keyword From is necessary to setup the in-place record definitions.  In MVC5 the syntax New Dictionary(Of String, String) is seen as an anonymous type and can't be converted to an IDictionary, in-place or otherwise.

The final code used in the Controller to setup an equivalent ActionLink in the view, based on the answer below, was:

Dim editLink = HtmlHelper.GenerateLink(Request.RequestContext,
    RouteTable.Routes,
    "Edit",      'the link text
    "Default",   'a route name, can found in RouteConfig.vb
    "Edit",      'the target ActionResult method
    "Role",      'the target Controller
    New RouteValueDictionary(New Dictionary(Of String, Object) From {"ID", role.Id}, {"selectedDomain", selectedDomain}}),
    Nothing)

In the case above, a second route value was added to the routeValueDictionary as needed by the ActionResult method.

If htmlAttributes are also required they can be added in place of the final Nothing show above, as specified in the answer below.

Body:
The parameter is type IDictionary(Of String, Object).  That's just an interface, so you need to create an object of a type that implements that interface.  The obvious choice is Dictionary(Of String, Object), e.g.

Dim temp As IDictionary(Of String, Object) = New Dictionary(Of String, Object)
temp.Add("ID", "somedata")
Dim myLink = HtmlHelper.GenerateLink(Request.RequestContext, RouteTable.Routes, "edit", "Default", "Edit", "Role", Nothing, temp)

I can't recall when anonymous types started being supported in such scenarios but it appears that it was later than MVC 5.  If you want to be able to use anonymous types then you would have to write your own method that accepts an anonymous type, uses Reflection to extract the data from it, builds a dictionary and then calls the existing method.  You might do that like this:

Public Module HtmlHelperExtender

    Public Function GenerateLink(requestContext As RequestContext,
                                 routeCollection As RouteCollection,
                                 linkText As String,
                                 routeName As String,
                                 actionName As String,
                                 controllerName As String,
                                 routeValues As RouteValueDictionary,
                                 htmlAttributes As Object) As String
        'Create a dictionary from the properties of the anonymously typed object.
        Dim attributesType = htmlAttributes.GetType()
        Dim properties = attributesType.GetProperties()
        Dim htmlAttributesDictionary = properties.ToDictionary(Function(p) p.Name, Function(p) p.GetValue(htmlAttributes))

        Return HtmlHelper.GenerateLink(requestContext,
                                       routeCollection,
                                       linkText,
                                       routeName,
                                       actionName,
                                       controllerName,
                                       routeValues,
                                       htmlAttributesDictionary)
    End Function

End Module

You can then call that method much like you were originally trying to:

Dim myLink = HtmlHelperExtender.GenerateLink(Request.RequestContext,
                                             RouteTable.Routes,
                                             "edit",
                                             "Default",
                                             "Edit",
                                             "Role",
                                             Nothing,
                                             New With {.ID = "somedata"})

Another option that just occurred to me is to stick with the dictionary but create and populate it in-place, which is possible using the From keyword:

Dim myLink = HtmlHelper.GenerateLink(Request.RequestContext,
                                     RouteTable.Routes,
                                     "edit",
                                     "Default",
                                     "Edit",
                                     "Role",
                                     Nothing,
                                     New Dictionary(Of String, Object) From {{"ID", "somedata"}})


问:
Blocked by CORS policy in Chrome after enabling CORS for Lambda Function?
I've enabled CORS in the console for a Lambda function following these instructions.

The API is also an express server that enables CORS for all methods:

```<code>// Enable CORS for all methods
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*")
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
  next()
});

</code>```

However the browser is still blocking the request because it is not receiving the Access-Control-Allow-Origin header.  This is the complete message:

home:1 Access to XMLHttpRequest at 'https://szxjza7hz5.execute-api.us-east-1.amazonaws.com/loco/myendpoint' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

How do we trouble shoot this?

The testing approach in the instructions provide a curl command like this:

```<code>curl -v -X OPTIONS -H "Access-Control-Request-Method: POST" -H "Origin: http://localhost:4200" https://szxjza7hz5.execute-api.us-east-1.amazonaws.com/loco
</code>```

However this fails due to a missing authentication token:

```<code>* Connection state changed (MAX_CONCURRENT_STREAMS updated)!
< HTTP/2 403
< content-type: application/json
< content-length: 42
< date: Wed, 19 Feb 2020 01:45:47 GMT
< x-amzn-requestid: a529894d-19ff-4c95-915b-45c4098d30ea
< x-amzn-errortype: MissingAuthenticationTokenException
< x-amz-apigw-id: IHvz3Fp_IAMF43g=
< x-cache: Error from cloudfront
< via: 1.1 58e86c1faaee1b15c90e95d794e240dd.cloudfront.net (CloudFront)
< x-amz-cf-pop: ORD51-C3
< x-amz-cf-id: jyTAo6OUrhUWWVNOSdk6M0384K515YzE0V9Vgg-WhfXXkLDzLofr9Q==
<
* Connection #0 to host szxjza7hz5.execute-api.us-east-1.amazonaws.com left intact
{"message":"Missing Authentication Token"}

</code>```

答:
Try adding these fields to response header:

```<code>const response = {
    headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Credentials" : true,
    },
    body: "...",
    statusCode: 200
}
</code>```

You could also experience the same error if not redeploy the API after updating it. Try to redeploy it as below:

Body:
I've enabled CORS in the console for a Lambda function following these instructions.

The API is also an express server that enables CORS for all methods:

// Enable CORS for all methods
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*")
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
  next()
});

However the browser is still blocking the request because it is not receiving the Access-Control-Allow-Origin header.  This is the complete message:

home:1 Access to XMLHttpRequest at 'https://szxjza7hz5.execute-api.us-east-1.amazonaws.com/loco/myendpoint' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

How do we trouble shoot this?

The testing approach in the instructions provide a curl command like this:

curl -v -X OPTIONS -H "Access-Control-Request-Method: POST" -H "Origin: http://localhost:4200" https://szxjza7hz5.execute-api.us-east-1.amazonaws.com/loco

However this fails due to a missing authentication token:

* Connection state changed (MAX_CONCURRENT_STREAMS updated)!
< HTTP/2 403
< content-type: application/json
< content-length: 42
< date: Wed, 19 Feb 2020 01:45:47 GMT
< x-amzn-requestid: a529894d-19ff-4c95-915b-45c4098d30ea
< x-amzn-errortype: MissingAuthenticationTokenException
< x-amz-apigw-id: IHvz3Fp_IAMF43g=
< x-cache: Error from cloudfront
< via: 1.1 58e86c1faaee1b15c90e95d794e240dd.cloudfront.net (CloudFront)
< x-amz-cf-pop: ORD51-C3
< x-amz-cf-id: jyTAo6OUrhUWWVNOSdk6M0384K515YzE0V9Vgg-WhfXXkLDzLofr9Q==
<
* Connection #0 to host szxjza7hz5.execute-api.us-east-1.amazonaws.com left intact
{"message":"Missing Authentication Token"}

Body:
Try adding these fields to response header:

const response = {
    headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Credentials" : true,
    },
    body: "...",
    statusCode: 200
}

You could also experience the same error if not redeploy the API after updating it. Try to redeploy it as below:


问:
I can not display the encoded image (Base64) by phonegap on my iPhone
I am developing an application for iPhone using the PhoneGap and I am coding in JavaScript. What I do is that I am downloading an image from the web and encode it into Base64 to store it in my database using the:

```<code>dataURL = canvas.toDataURL("image/png");
</code>```

The stored image is of the form:

```<code>data:image/jpeg;base64,ENCODING...
</code>```

Now, I need when the user is offline, to get the image from the database and display it on the HTML5 canvas item. I have the following code for that:

```<code>var canvas = document.getElementById("draw_area");
var context = canvas.getContext('2d');
var myImage = new Image();
myImage.src = dataURL;

myImage.onload = function (){
    context.drawImage (myImage, 0, 0);
};
</code>```

BUT I get an empty canvas even though I check and am sure that the src is the exact base64 encoding I get from the database. Should I do something else first, like decoding and then display the image? If yes, how do I implement that?

答:
as my personal experience  , it's CSP  related, try add this line to your html meta or append it to your existing CSP.

<meta http-equiv="Content-Security-Policy" content="img-src 'self' data:">```

Body:
I am developing an application for iPhone using the PhoneGap and I am coding in JavaScript. What I do is that I am downloading an image from the web and encode it into Base64 to store it in my database using the:

dataURL = canvas.toDataURL("image/png");

The stored image is of the form:

data:image/jpeg;base64,ENCODING...

Now, I need when the user is offline, to get the image from the database and display it on the HTML5 canvas item. I have the following code for that:

var canvas = document.getElementById("draw_area");
var context = canvas.getContext('2d');
var myImage = new Image();
myImage.src = dataURL;

myImage.onload = function (){
    context.drawImage (myImage, 0, 0);
};

BUT I get an empty canvas even though I check and am sure that the src is the exact base64 encoding I get from the database. Should I do something else first, like decoding and then display the image? If yes, how do I implement that?


问:
Javascript count same array of object values based on two values
Let's say we have an array of object like this

```<code>const studentRecord = [
 {
   name: 'John Doe',
   gender: 'Male',
   grade: '85'
 },{
   name: 'Steve Doe',
   gender: 'Male',
   grade: '85'
 },{
   name: 'Jane Doe',
   gender: 'Male',
   grade: '90'
 },{
   name: 'Mary Jane',
   gender: 'Female',
   grade: '85'
 },
]
</code>```

I would like to count all students that are male that have the same grade and female students with the same grade something like this would be the output...

```<code> 85: {
       Male: 2,
       Female: 1,
     }
 90: {
       Female:1
     }

</code>```

I only have this code so far

```<code>    const foo = {};
    studentRecord.reduce((prevVal, currentVal) => {
      foo[currentVal['gender']] = (foo[currentVal['gender']] || 0) + 1;
    });
</code>```

Which only outputs
 {Male: 2, Female: 2}

答:
Your code has the right idea regarding the gender key, but is missing the grade keys, which is necessary to produce the desired nested object.

The approach below checks whether a grade key exists yet and adds it if it doesn't. Then, it increments the appropriate gender for that key.

const studentRecords = [{ name: 'John Doe', gender: 'Male', grade: '85' }, { name: 'Steve Doe', gender: 'Male', grade: '85' }, { name: 'Jane Doe', gender: 'Male', grade: '90' }, { name: 'Mary Jane', gender: 'Female', grade: '85' }];

const byGrade = studentRecords.reduce((a, e) => {
  if (!(e.grade in a)) {
    a[e.grade] = {};
  }

  a[e.grade][e.gender] = ++a[e.grade][e.gender] || 1;
  return a;
}, {});

console.log(byGrade);```

Body:
Let's say we have an array of object like this

const studentRecord = [
 {
   name: 'John Doe',
   gender: 'Male',
   grade: '85'
 },{
   name: 'Steve Doe',
   gender: 'Male',
   grade: '85'
 },{
   name: 'Jane Doe',
   gender: 'Male',
   grade: '90'
 },{
   name: 'Mary Jane',
   gender: 'Female',
   grade: '85'
 },
]

I would like to count all students that are male that have the same grade and female students with the same grade something like this would be the output...

 85: {
       Male: 2,
       Female: 1,
     }
 90: {
       Female:1
     }

I only have this code so far

    const foo = {};
    studentRecord.reduce((prevVal, currentVal) => {
      foo[currentVal['gender']] = (foo[currentVal['gender']] || 0) + 1;
    });

Which only outputs
 {Male: 2, Female: 2}


答:
When reducing into an object, create an object at the grade property first, if it doesn't exist. Then create an object at that grade's Male or Female property if it doesn't exist, and increment it:

const studentRecord = [
 {
   name: 'John Doe',
   gender: 'Male',
   grade: '85'
 },{
   name: 'Steve Doe',
   gender: 'Male',
   grade: '85'
 },{
   name: 'Jane Doe',
   gender: 'Male',
   grade: '90'
 },{
   name: 'Mary Jane',
   gender: 'Female',
   grade: '85'
 },
];

const results = studentRecord.reduce((a, { gender, grade }) => {
  if (!a[grade]) {
    a[grade] = {};
  }
  a[grade][gender] = (a[grade][gender] || 0) + 1;
  return a;
}, {});
console.log(results);```
</div>
</div>
</p>

<p>Or, without reduce:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const studentRecord = [
 {
   name: 'John Doe',
   gender: 'Male',
   grade: '85'
 },{
   name: 'Steve Doe',
   gender: 'Male',
   grade: '85'
 },{
   name: 'Jane Doe',
   gender: 'Male',
   grade: '90'
 },{
   name: 'Mary Jane',
   gender: 'Female',
   grade: '85'
 },
];

const results = {};
for (const { gender, grade } of studentRecord) {
  if (!results[grade]) {
    results[grade] = {};
  }
  results[grade][gender] = (results[grade][gender] || 0) + 1;
}
console.log(results);</code>```

Title: Javascript count same array of object values based on two values

Body:
When reducing into an object, create an object at the grade property first, if it doesn't exist. Then create an object at that grade's Male or Female property if it doesn't exist, and increment it:

const studentRecord = [
 {
   name: 'John Doe',
   gender: 'Male',
   grade: '85'
 },{
   name: 'Steve Doe',
   gender: 'Male',
   grade: '85'
 },{
   name: 'Jane Doe',
   gender: 'Male',
   grade: '90'
 },{
   name: 'Mary Jane',
   gender: 'Female',
   grade: '85'
 },
];

const results = studentRecord.reduce((a, { gender, grade }) => {
  if (!a[grade]) {
    a[grade] = {};
  }
  a[grade][gender] = (a[grade][gender] || 0) + 1;
  return a;
}, {});
console.log(results);

Or, without reduce:

const studentRecord = [
 {
   name: 'John Doe',
   gender: 'Male',
   grade: '85'
 },{
   name: 'Steve Doe',
   gender: 'Male',
   grade: '85'
 },{
   name: 'Jane Doe',
   gender: 'Male',
   grade: '90'
 },{
   name: 'Mary Jane',
   gender: 'Female',
   grade: '85'
 },
];

const results = {};
for (const { gender, grade } of studentRecord) {
  if (!results[grade]) {
    results[grade] = {};
  }
  results[grade][gender] = (results[grade][gender] || 0) + 1;
}
console.log(results);


问:
Only load segment of text file using numpy and itertools
I have a piece of code that initially decodes a .dat file into a .txt file using a binary chipher cycle style decoder. It results in an over 500 line text file of data points with lines 0-65 being titles and other display features and the last few lines, starting from 586, being wrongly decoded text that looks something like:

ßÅBÎheÀœaÜ;sî3TÐêM·Zì?pêI†Q’&×¥uÌˆ#ÇPËiPì¿j–hñHžíoî#ˆ[ÿ>BÿÃ@ÌhcP¿_ÔkõOˆEñlÀ‹J–>tò5Ægã_ð: yŽ6aÎ
  “uôhaù*°Dý4}Ó´Qá4wÙ
  žZôØ
  ‘~êlHí–’/mÑ=žt
  k×£QÉoû·]Ý&õC´Jœ9mû»ZÃ+]þ6ƒ[á‰¶S;Uö¥Wã
  Lè:ÂXÿ4sÈÄAïPó€Dó$EØÙ•dÐ”eïkHâN xÐj@Ø"”eë1aõÅCÒ7ùC–ñiÐCÑP‹Æ
  Ñ
  ]ô†}ÌdDñ
   Ë,WÎÄdó^ã8žDäÓ)Çq9}ùÃfÄP÷ÇzîoiÒ    ÁpìeSÖ€ÒMŒÀ“;Bö

I am using the code:

```<code>with open (file) as f:
    xpoints, ypoints, gradient = np.loadtxt(itertools.islice(f,68, 584), delimiter=',', unpack=True)
</code>```

in order to load only the lines that contain the data points I am after.

For some reason however, this causes the program to throw an error that it cant decode a byte as it maps to undefined. I have confirmed it is caused by the junk text at the bottom and seems to be thrown in the line shown above but I cannot figure out why this is the case as it shouldn't need to read those lines at all.

Full error:

File "C:\Users\brady\Desktop\Slider_All\Slide-Mobile.py", line 57, in
  module

xpoints, ypoints, gradient = np.loadtxt(IT.islice(f,68,
  500), delimiter=',',  unpack=True)   File
  "C:\Users\brady\AppData\Local\Programs\Python\Python38-32\lib\site-packag
  es\numpy\lib\npyio.py", line 1159, in loadtxt
      for x in read_data(_loadtxt_chunksize):   File "C:\Users\brady\AppData\Local\Programs\Python\Python38-32\lib\site-packag
  es\numpy\lib\npyio.py", line 1075, in read_data
      for i, line in enumerate(line_iter):   File "C:\Users\brady\AppData\Local\Programs\Python\Python38-32\lib\encodings\c
  p1252.py", line 23, in decode
      return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position
  7758: cha racter maps to undefined

Does itertools.islice or numpy.loadtxt possibly attempt to read the whole document first before it takes the slice and runs into a problem or is this something else entirely that I'm missing. I will post my entire unedited code below for completions sake, thankyou for any and all help.

```<code>import matplotlib.animation as animation
from matplotlib.widgets import Slider, Button
import matplotlib as mpl
from matplotlib import pyplot as plt
import scipy.interpolate as inter
import numpy as np
import itertools as IT
from itertools import cycle
from scipy.interpolate import interp1d
import os

file = 'example.dat'
x1 = 250    #Lower bound    Bigger bound leads to lots of lag
x2 = 300    #Upper bound    Recommended to remain close to range of 50

#=========================================================================================================================
start = []  #Stores data before given points
end = []    #Stores data after given points
files = []  #Stores text file to be removed when done

#This function decodes and re-encodes the dat files
class Decoder:
    def decode(fn_in, fn_out):
        CIPHER = cycle([0b01011100, 0b00100111, 0b10111010, 0b01111011, 0b11110010, 0b00110010, 0b10100101])
        with open(fn_in, 'rb') as fin, open(fn_out, 'wb') as fout:
            fout.write(fin.read(14))
            byte = fin.read(1)
            while byte:
                fout.write( ( int.from_bytes(byte, 'big') ^ next(CIPHER) ).to_bytes(1, 'big') )
                byte = fin.read(1)

    def to_txt(filename):
        #global files
        if filename [-3:] == "dat":
            Decoder.decode( filename, filename[:-3] + "txt" )
            filename = filename[:-3] + "txt"
        else:
            print("Extension not recognised for input filename \""+str(filename)+"\", skipping...")

        return filename

    def to_dat(filename):
        files.append(filename)
        if filename [-3:] == "txt":
                Decoder.decode( filename, tempfile[:-3]+ "dat" )
                #file.append(filename[:-3] + "dat")
        else:
            print("Extension not recognised for input filename \""+str(filename)+"\", skipping...")

if file[-3:] == "dat":
    file = Decoder.to_txt(file) #Converts .dat to .txt
    files.append(file)

#Gets all data points from file
with open (file) as f:
    xpoints, ypoints, gradient = np.loadtxt(IT.islice(f,68, 584), delimiter=',', unpack=True)

#get a list of points to fit a spline to as well
xmin = min(xpoints)
xmax = max(xpoints)

#Calculates which lines of data are required to plot
X1 = int(516*((x1 - xmin)/(xmax-xmin))) + 68
X2 = int(516*((x2 - xmin)/(xmax-xmin))) + 68

#Gets specific lines and saves the rest to copy back later
with open (file) as f:
    xp, ypoints, gradient = np.loadtxt(IT.islice(f,X1, X2), delimiter=',', unpack=True)
with open(file) as f:
    for line in IT.islice(f,0,X1):
        start.append(line)
with open (file) as f:
    for line in IT.islice(f,X2,584):
        end.append(line)

#Sets amount of data points to plot, must be multiple of point range
#The lower the number the more accurate the plot but the slower it will run
N = len(xp)

if N < 200:
    j = 1
elif N < 400:
    j = 1
else: j = 1

x = xp[::j]
yvals = ypoints[::j]
N = len(x)
xnew = xp

#spline fit
spline = inter.InterpolatedUnivariateSpline (x, yvals)

#set up a plot
fig,axes = plt.subplots(1,1,figsize=(12.0,4.0),sharex=True)
fig,axes.set_position([0.05,0.08,0.93,0.80])
ax1 = axes

pind = None #active point
epsilon = 5 #max pixel distance
#Updates plot when point is dragged
def update(val):
    global yvals
    global spline
    # update curve
    for i in np.arange(N):
      yvals[i] = sliders[i].val
    l.set_ydata(yvals)
    spline = inter.InterpolatedUnivariateSpline (x, yvals)
    m.set_ydata(spline(X))
    # redraw canvas while idle
    fig.canvas.draw_idle()

#Resets plot back to original save from when opened
def reset(event):
    global yvals
    global spline
    #reset the values
    yvals = ypoints
    for i in np.arange(N):
      sliders[i].reset()
    spline = inter.InterpolatedUnivariateSpline (x, yvals)
    l.set_ydata(yvals)
    m.set_ydata(spline(X))
    # redraw canvas while idle
    fig.canvas.draw_idle()

#Overwirtes current save with new plot
def save(event):
    f = interp1d(x, yvals, kind='cubic')
    ynew = f(xnew)
    ax1.plot(xnew,ynew)

    newfile = np.vstack((xnew,ynew, gradient)).T

    with open(file, 'w') as f:
        for item in start:
            f.write("%s" % item)
        np.savetxt(f, newfile, delimiter = ',')
        for item in end:
            f.write("%s" % item)
        #f.write('""')
    Decoder.to_dat(file) #Converts .txt to .dat

#Event handler for mouse click
def button_press_callback(event):
    'whenever a mouse button is pressed'
    global pind
    if event.inaxes is None:
        return
    if event.button != 1:
        return
    #print(pind)
    pind = get_ind_under_point(event)

#Event handler for mouse release
def button_release_callback(event):
    'whenever a mouse button is released'
    global pind
    if event.button != 1:
        return
    pind = None

#Gets clicked point number
def get_ind_under_point(event):
    'get the index of the vertex under point if within epsilon tolerance'

    # display coords
    #print('display x is: {0}; display y is: {1}'.format(event.x,event.y))
    t = ax1.transData.inverted()
    tinv = ax1.transData
    xy = t.transform([event.x,event.y])
    #print('data x is: {0}; data y is: {1}'.format(xy[0],xy[1]))
    xr = np.reshape(x,(np.shape(x)[0],1))
    yr = np.reshape(yvals,(np.shape(yvals)[0],1))
    xy_vals = np.append(xr,yr,1)
    xyt = tinv.transform(xy_vals)
    xt, yt = xyt[:, 0], xyt[:, 1]
    d = np.hypot(xt - event.x, yt - event.y)
    indseq, = np.nonzero(d == d.min())
    ind = indseq[0]

    #print(d[ind])
    if d[ind] >= epsilon:
        ind = None

    #print(ind)
    return ind

#Event handler for mosue movement
def motion_notify_callback(event):
    'on mouse movement'
    global yvals
    if pind is None:
        return
    if event.inaxes is None:
        return
    if event.button != 1:
        return

    #update yvals
    #print('motion x: {0}; y: {1}'.format(event.xdata,event.ydata))
    yvals[pind] = event.ydata

    # update curve via sliders and draw
    sliders[pind].set_val(yvals[pind])
    fig.canvas.draw_idle()

X = xp
ax1.plot (X, ypoints, 'k--', label='original')
l, = ax1.plot (x,yvals,color='k',linestyle='none',marker='o',markersize=8)
m, = ax1.plot (X, spline(X), 'r-', label='spline')

if max(ypoints) > 0:
    yheight = 0.01*max(ypoints)
    ylower =0
else:
    yheight = -0.1*max(ypoints)
    ylower = yheight

ax1.set_yscale('linear')
ax1.set_xlim(x1, x2)
ax1.set_ylim(min(ypoints)-ylower,max(ypoints)+yheight)
ax1.grid(True)
ax1.yaxis.grid(True,which='minor',linestyle='--')

sliders = []

for i in np.arange(N):

    axamp = plt.axes([0.84, -1, 0.12, 0.01])
    # Slider
    s = Slider(axamp, 'p{0}'.format(i), -100, 10, valinit=yvals[i])
    sliders.append(s)

for i in np.arange(N):
    #samp.on_changed(update_slider)
    sliders[i].on_changed(update)

axres = plt.axes([0.84, 0.90, 0.15, 0.08])
bres = Button(axres, 'Reset')
bres.on_clicked(reset)

axsave = plt.axes([0.68, 0.90, 0.15, 0.08])
bsave = Button(axsave, 'Save')
bsave.on_clicked(save)

fig.canvas.mpl_connect('button_press_event', button_press_callback)
fig.canvas.mpl_connect('button_release_event', button_release_callback)
fig.canvas.mpl_connect('motion_notify_event', motion_notify_callback)

plt.show()
for filename in files:
    os.remove(filename)
</code>```

EDIT: I know believe the error is almost definitely tied to the itertools.islice command as I have found a similar issue here: Python 3 itertools.islice continue despite UnicodeDecodeError.

Currently researching alternate way to potentially open the file as changing decode style for .dat is not possible at this stage

答:
I have solved the issue using the solution posted here: https://stackoverflow.com/a/31113251/10475989

My final code is:

```<code>types_of_encoding = ["utf8", "cp1252"]
for encoding_type in types_of_encoding:
    with open (file, 'r', encoding = encoding_type, errors='ignore') as f:
        xpoints, ypoints, gradient = np.loadtxt(IT.islice(f,65, 582), delimiter=',', unpack=True)
</code>```

Body:
I have a piece of code that initially decodes a .dat file into a .txt file using a binary chipher cycle style decoder. It results in an over 500 line text file of data points with lines 0-65 being titles and other display features and the last few lines, starting from 586, being wrongly decoded text that looks something like:

ßÅBÎheÀœaÜ;sî3TÐêM·Zì?pêI†Q’&×¥uÌˆ#ÇPËiPì¿j–hñHžíoî#ˆ[ÿ>BÿÃ@ÌhcP¿_ÔkõOˆEñlÀ‹J–>tò5Ægã_ð: yŽ6aÎ
  “uôhaù*°Dý4}Ó´Qá4wÙ
  žZôØ
  ‘~êlHí–’/mÑ=žt
  k×£QÉoû·]Ý&õC´Jœ9mû»ZÃ+]þ6ƒ[á‰¶S;Uö¥Wã
  Lè:ÂXÿ4sÈÄAïPó€Dó$EØÙ•dÐ”eïkHâN xÐj@Ø"”eë1aõÅCÒ7ùC–ñiÐCÑP‹Æ
  Ñ
  ]ô†}ÌdDñ
   Ë,WÎÄdó^ã8žDäÓ)Çq9}ùÃfÄP÷ÇzîoiÒ    ÁpìeSÖ€ÒMŒÀ“;Bö

I am using the code:

with open (file) as f:
    xpoints, ypoints, gradient = np.loadtxt(itertools.islice(f,68, 584), delimiter=',', unpack=True)

in order to load only the lines that contain the data points I am after.

For some reason however, this causes the program to throw an error that it cant decode a byte as it maps to undefined. I have confirmed it is caused by the junk text at the bottom and seems to be thrown in the line shown above but I cannot figure out why this is the case as it shouldn't need to read those lines at all.

Full error:

File "C:\Users\brady\Desktop\Slider_All\Slide-Mobile.py", line 57, in
  module

xpoints, ypoints, gradient = np.loadtxt(IT.islice(f,68,
  500), delimiter=',',  unpack=True)   File
  "C:\Users\brady\AppData\Local\Programs\Python\Python38-32\lib\site-packag
  es\numpy\lib\npyio.py", line 1159, in loadtxt
      for x in read_data(_loadtxt_chunksize):   File "C:\Users\brady\AppData\Local\Programs\Python\Python38-32\lib\site-packag
  es\numpy\lib\npyio.py", line 1075, in read_data
      for i, line in enumerate(line_iter):   File "C:\Users\brady\AppData\Local\Programs\Python\Python38-32\lib\encodings\c
  p1252.py", line 23, in decode
      return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position
  7758: cha racter maps to undefined

Does itertools.islice or numpy.loadtxt possibly attempt to read the whole document first before it takes the slice and runs into a problem or is this something else entirely that I'm missing. I will post my entire unedited code below for completions sake, thankyou for any and all help.

import matplotlib.animation as animation
from matplotlib.widgets import Slider, Button
import matplotlib as mpl
from matplotlib import pyplot as plt
import scipy.interpolate as inter
import numpy as np
import itertools as IT
from itertools import cycle
from scipy.interpolate import interp1d
import os

file = 'example.dat'
x1 = 250    #Lower bound    Bigger bound leads to lots of lag
x2 = 300    #Upper bound    Recommended to remain close to range of 50

#=========================================================================================================================
start = []  #Stores data before given points
end = []    #Stores data after given points
files = []  #Stores text file to be removed when done

#This function decodes and re-encodes the dat files
class Decoder:
    def decode(fn_in, fn_out):
        CIPHER = cycle([0b01011100, 0b00100111, 0b10111010, 0b01111011, 0b11110010, 0b00110010, 0b10100101])
        with open(fn_in, 'rb') as fin, open(fn_out, 'wb') as fout:
            fout.write(fin.read(14))
            byte = fin.read(1)
            while byte:
                fout.write( ( int.from_bytes(byte, 'big') ^ next(CIPHER) ).to_bytes(1, 'big') )
                byte = fin.read(1)

    def to_txt(filename):
        #global files
        if filename [-3:] == "dat":
            Decoder.decode( filename, filename[:-3] + "txt" )
            filename = filename[:-3] + "txt"
        else:
            print("Extension not recognised for input filename \""+str(filename)+"\", skipping...")

        return filename

    def to_dat(filename):
        files.append(filename)
        if filename [-3:] == "txt":
                Decoder.decode( filename, tempfile[:-3]+ "dat" )
                #file.append(filename[:-3] + "dat")
        else:
            print("Extension not recognised for input filename \""+str(filename)+"\", skipping...")

if file[-3:] == "dat":
    file = Decoder.to_txt(file) #Converts .dat to .txt
    files.append(file)

#Gets all data points from file
with open (file) as f:
    xpoints, ypoints, gradient = np.loadtxt(IT.islice(f,68, 584), delimiter=',', unpack=True)

#get a list of points to fit a spline to as well
xmin = min(xpoints)
xmax = max(xpoints)

#Calculates which lines of data are required to plot
X1 = int(516*((x1 - xmin)/(xmax-xmin))) + 68
X2 = int(516*((x2 - xmin)/(xmax-xmin))) + 68

#Gets specific lines and saves the rest to copy back later
with open (file) as f:
    xp, ypoints, gradient = np.loadtxt(IT.islice(f,X1, X2), delimiter=',', unpack=True)
with open(file) as f:
    for line in IT.islice(f,0,X1):
        start.append(line)
with open (file) as f:
    for line in IT.islice(f,X2,584):
        end.append(line)

#Sets amount of data points to plot, must be multiple of point range
#The lower the number the more accurate the plot but the slower it will run
N = len(xp)

if N < 200:
    j = 1
elif N < 400:
    j = 1
else: j = 1

x = xp[::j]
yvals = ypoints[::j]
N = len(x)
xnew = xp

#spline fit
spline = inter.InterpolatedUnivariateSpline (x, yvals)

#set up a plot
fig,axes = plt.subplots(1,1,figsize=(12.0,4.0),sharex=True)
fig,axes.set_position([0.05,0.08,0.93,0.80])
ax1 = axes

pind = None #active point
epsilon = 5 #max pixel distance
#Updates plot when point is dragged
def update(val):
    global yvals
    global spline
    # update curve
    for i in np.arange(N):
      yvals[i] = sliders[i].val
    l.set_ydata(yvals)
    spline = inter.InterpolatedUnivariateSpline (x, yvals)
    m.set_ydata(spline(X))
    # redraw canvas while idle
    fig.canvas.draw_idle()

#Resets plot back to original save from when opened
def reset(event):
    global yvals
    global spline
    #reset the values
    yvals = ypoints
    for i in np.arange(N):
      sliders[i].reset()
    spline = inter.InterpolatedUnivariateSpline (x, yvals)
    l.set_ydata(yvals)
    m.set_ydata(spline(X))
    # redraw canvas while idle
    fig.canvas.draw_idle()

#Overwirtes current save with new plot
def save(event):
    f = interp1d(x, yvals, kind='cubic')
    ynew = f(xnew)
    ax1.plot(xnew,ynew)

    newfile = np.vstack((xnew,ynew, gradient)).T

    with open(file, 'w') as f:
        for item in start:
            f.write("%s" % item)
        np.savetxt(f, newfile, delimiter = ',')
        for item in end:
            f.write("%s" % item)
        #f.write('""')
    Decoder.to_dat(file) #Converts .txt to .dat

#Event handler for mouse click
def button_press_callback(event):
    'whenever a mouse button is pressed'
    global pind
    if event.inaxes is None:
        return
    if event.button != 1:
        return
    #print(pind)
    pind = get_ind_under_point(event)

#Event handler for mouse release
def button_release_callback(event):
    'whenever a mouse button is released'
    global pind
    if event.button != 1:
        return
    pind = None

#Gets clicked point number
def get_ind_under_point(event):
    'get the index of the vertex under point if within epsilon tolerance'

    # display coords
    #print('display x is: {0}; display y is: {1}'.format(event.x,event.y))
    t = ax1.transData.inverted()
    tinv = ax1.transData
    xy = t.transform([event.x,event.y])
    #print('data x is: {0}; data y is: {1}'.format(xy[0],xy[1]))
    xr = np.reshape(x,(np.shape(x)[0],1))
    yr = np.reshape(yvals,(np.shape(yvals)[0],1))
    xy_vals = np.append(xr,yr,1)
    xyt = tinv.transform(xy_vals)
    xt, yt = xyt[:, 0], xyt[:, 1]
    d = np.hypot(xt - event.x, yt - event.y)
    indseq, = np.nonzero(d == d.min())
    ind = indseq[0]

    #print(d[ind])
    if d[ind] >= epsilon:
        ind = None

    #print(ind)
    return ind

#Event handler for mosue movement
def motion_notify_callback(event):
    'on mouse movement'
    global yvals
    if pind is None:
        return
    if event.inaxes is None:
        return
    if event.button != 1:
        return

    #update yvals
    #print('motion x: {0}; y: {1}'.format(event.xdata,event.ydata))
    yvals[pind] = event.ydata

    # update curve via sliders and draw
    sliders[pind].set_val(yvals[pind])
    fig.canvas.draw_idle()

X = xp
ax1.plot (X, ypoints, 'k--', label='original')
l, = ax1.plot (x,yvals,color='k',linestyle='none',marker='o',markersize=8)
m, = ax1.plot (X, spline(X), 'r-', label='spline')

if max(ypoints) > 0:
    yheight = 0.01*max(ypoints)
    ylower =0
else:
    yheight = -0.1*max(ypoints)
    ylower = yheight

ax1.set_yscale('linear')
ax1.set_xlim(x1, x2)
ax1.set_ylim(min(ypoints)-ylower,max(ypoints)+yheight)
ax1.grid(True)
ax1.yaxis.grid(True,which='minor',linestyle='--')

sliders = []

for i in np.arange(N):

    axamp = plt.axes([0.84, -1, 0.12, 0.01])
    # Slider
    s = Slider(axamp, 'p{0}'.format(i), -100, 10, valinit=yvals[i])
    sliders.append(s)

for i in np.arange(N):
    #samp.on_changed(update_slider)
    sliders[i].on_changed(update)

axres = plt.axes([0.84, 0.90, 0.15, 0.08])
bres = Button(axres, 'Reset')
bres.on_clicked(reset)

axsave = plt.axes([0.68, 0.90, 0.15, 0.08])
bsave = Button(axsave, 'Save')
bsave.on_clicked(save)

fig.canvas.mpl_connect('button_press_event', button_press_callback)
fig.canvas.mpl_connect('button_release_event', button_release_callback)
fig.canvas.mpl_connect('motion_notify_event', motion_notify_callback)

plt.show()
for filename in files:
    os.remove(filename)

EDIT: I know believe the error is almost definitely tied to the itertools.islice command as I have found a similar issue here: Python 3 itertools.islice continue despite UnicodeDecodeError.

Currently researching alternate way to potentially open the file as changing decode style for .dat is not possible at this stage

Body:
I have solved the issue using the solution posted here: https://stackoverflow.com/a/31113251/10475989

My final code is:

types_of_encoding = ["utf8", "cp1252"]
for encoding_type in types_of_encoding:
    with open (file, 'r', encoding = encoding_type, errors='ignore') as f:
        xpoints, ypoints, gradient = np.loadtxt(IT.islice(f,65, 582), delimiter=',', unpack=True)


问:
How to check if a remote server supports PHP?
I often have clients who do not know if their server supports PHP (their website is HTML web site). At the moment, I send them hello.php file, they upload it and then I check it remotely if their server supports PHP. As you see this takes day or two and it's just a waste of time.

Can I myself any how check if their server supports PHP (via web browser or console tool)? If the domain is for example www.my-client.com, what would be the syntax?

Thanks

PS. I have an access to Linux console so I could use it as well

答: The best you could do is send an HTTP request to this server http://www.my-client.com and inspect response HTTP headers. In some cases depending on the server there might be clues. For example here's how the response HTTP headers look like in FireBug for http://joomla.org:


问:
How to generate basic TypeScript interfaces from Swagger schema?
I'm looking for a way to generate simplistic TypeScript interfaces from a Swagger schema. Most solutions I find are needlessly complicated.

I would like to generate interfaces like this:

```<code>export interface IBar {
    a?: string;
    b: number;
    c: Date;
    baz?: IBaz;
}

export interface IBaz {
    d: number;
    color: Color;
}

export enum Color {
    RED = 0,
    GREEN = 1,
    BLUE = 2,
}
</code>```

From a schema like this:

```<code>    {
  "x-generator": "NSwag v11.14.0.0 (NJsonSchema v9.10.24.0 (Newtonsoft.Json v9.0.0.0))",
  "swagger": "2.0",
  "info": {
    "title": "",
    "version": ""
  },
  "schemes": [],
  "consumes": [
    "application/json"
  ],
  "produces": [
    "application/json"
  ],
  "paths": {
    "/api/Foo/GetBarDescriptions": {
      "get": {
        "tags": [
          "Foo"
        ],
        "operationId": "Foo_GetBarDescriptions",
        "parameters": [],
        "responses": {
          "200": {
            "description": "",
            "schema": {
              "type": "array",
              "items": {
                "type": "string"
              }
            },
            "x-nullable": true
          }
        }
      }
    },
    "/api/Foo/GetBar": {
      "get": {
        "tags": [
          "Foo"
        ],
        "operationId": "Foo_GetBar",
        "parameters": [
          {
            "type": "integer",
            "name": "id",
            "in": "query",
            "required": true,
            "x-nullable": false,
            "format": "int32"
          }
        ],
        "responses": {
          "200": {
            "description": "",
            "schema": {
              "$ref": "#/definitions/Bar"
            },
            "x-nullable": true
          }
        }
      }
    },
    "/api/Foo/SetBar": {
      "post": {
        "tags": [
          "Foo"
        ],
        "operationId": "Foo_SetBar",
        "parameters": [
          {
            "name": "value",
            "in": "body",
            "required": true,
            "schema": {
              "$ref": "#/definitions/Bar"
            },
            "x-nullable": true
          }
        ],
        "responses": {
          "204": {
            "description": ""
          }
        }
      }
    }
  },
  "definitions": {
    "Bar": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "B",
        "C"
      ],
      "properties": {
        "A": {
          "type": "string"
        },
        "B": {
          "type": "integer",
          "format": "int32"
        },
        "C": {
          "type": "string",
          "format": "date-time"
        },
        "Baz": {
          "$ref": "#/definitions/Baz"
        }
      }
    },
    "Baz": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "D",
        "Color"
      ],
      "properties": {
        "D": {
          "type": "number",
          "format": "decimal"
        },
        "Color": {
          "$ref": "#/definitions/Color"
        }
      }
    },
    "Color": {
      "type": "integer",
      "description": "",
      "x-enumNames": [
        "RED",
        "GREEN",
        "BLUE"
      ],
      "enum": [
        0,
        1,
        2
      ]
    }
  },
  "parameters": {},
  "responses": {},
  "securityDefinitions": {}
}
</code>```

答:
I'm using swagger-typescript-api to generate interfaces from swagger schema</p>
```<code>npx swagger-typescript-api -p PATH_TO_YOUR_SCHEMA -o ./
</code>```

Body:
I'm looking for a way to generate simplistic TypeScript interfaces from a Swagger schema. Most solutions I find are needlessly complicated.

I would like to generate interfaces like this:

export interface IBar {
    a?: string;
    b: number;
    c: Date;
    baz?: IBaz;
}

export interface IBaz {
    d: number;
    color: Color;
}

export enum Color {
    RED = 0,
    GREEN = 1,
    BLUE = 2,
}

From a schema like this:

    {
  "x-generator": "NSwag v11.14.0.0 (NJsonSchema v9.10.24.0 (Newtonsoft.Json v9.0.0.0))",
  "swagger": "2.0",
  "info": {
    "title": "",
    "version": ""
  },
  "schemes": [],
  "consumes": [
    "application/json"
  ],
  "produces": [
    "application/json"
  ],
  "paths": {
    "/api/Foo/GetBarDescriptions": {
      "get": {
        "tags": [
          "Foo"
        ],
        "operationId": "Foo_GetBarDescriptions",
        "parameters": [],
        "responses": {
          "200": {
            "description": "",
            "schema": {
              "type": "array",
              "items": {
                "type": "string"
              }
            },
            "x-nullable": true
          }
        }
      }
    },
    "/api/Foo/GetBar": {
      "get": {
        "tags": [
          "Foo"
        ],
        "operationId": "Foo_GetBar",
        "parameters": [
          {
            "type": "integer",
            "name": "id",
            "in": "query",
            "required": true,
            "x-nullable": false,
            "format": "int32"
          }
        ],
        "responses": {
          "200": {
            "description": "",
            "schema": {
              "$ref": "#/definitions/Bar"
            },
            "x-nullable": true
          }
        }
      }
    },
    "/api/Foo/SetBar": {
      "post": {
        "tags": [
          "Foo"
        ],
        "operationId": "Foo_SetBar",
        "parameters": [
          {
            "name": "value",
            "in": "body",
            "required": true,
            "schema": {
              "$ref": "#/definitions/Bar"
            },
            "x-nullable": true
          }
        ],
        "responses": {
          "204": {
            "description": ""
          }
        }
      }
    }
  },
  "definitions": {
    "Bar": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "B",
        "C"
      ],
      "properties": {
        "A": {
          "type": "string"
        },
        "B": {
          "type": "integer",
          "format": "int32"
        },
        "C": {
          "type": "string",
          "format": "date-time"
        },
        "Baz": {
          "$ref": "#/definitions/Baz"
        }
      }
    },
    "Baz": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "D",
        "Color"
      ],
      "properties": {
        "D": {
          "type": "number",
          "format": "decimal"
        },
        "Color": {
          "$ref": "#/definitions/Color"
        }
      }
    },
    "Color": {
      "type": "integer",
      "description": "",
      "x-enumNames": [
        "RED",
        "GREEN",
        "BLUE"
      ],
      "enum": [
        0,
        1,
        2
      ]
    }
  },
  "parameters": {},
  "responses": {},
  "securityDefinitions": {}
}

Body:
I'm using swagger-typescript-api to generate interfaces from swagger schema

npx swagger-typescript-api -p PATH_TO_YOUR_SCHEMA -o ./


问:
How to create properties in Ready API dynamically?
I am automating testing of Restful services using ReadyAPI.

A Test case has two GET request steps(say GETCARDS and GETCARDDETAILS).

GETCARDS returns an array of Cardnumbers (not fixed size). I need to use these card numbers in second request GETCARDDETAILS and run them one by one.

For this these i am planning to dynamically create variables/properties based on Cardnumbers arrarsize and store the values for each run. Later use these values in second step GETCARDDETAILS . Need help in creating and storing values received in the response dynamically.

答:
Not sure if this would help but you may try to come up with a Groovy Script step within your test case which dynamically create variables based on your desired scenario and transfer the property to your next test step based on the image explanation below from ReadyAPI.

ReadyAPI Property Expansion