问:
How log scale works in d3.js
I am trying to understand why the equation doesn't give the desired result.

I am unable to decode how this returns 90.96? Even with using the equation log y = m log x + log k I can't get the same result. using ∆log y divided by  ∆log x to get m.

```<code>const logScale = d3.scaleLog()
                   .domain([1, 1000])
                   .range([10, 100]);

console.log(logScale(500)); // returns 90.96
</code>```

答:
Log scales have the form y = m log(x) + b. By default it's a base 10 log. With your scale

const logScale = d3.scaleLog()
  .domain([1, 1000])
  .range([10, 100]);
```
<p>m = 30 and b = 10. So you can think of it as</p>
```function logScale(x) {
  return 30 * Math.log10(x) + 10;
}
```

Edit: explaining how I got the b = 10 and m = 30

From the domain and range, we know that logScale(1) === 10. We also know that Math.log10(1) === 0. Therefore, when x is 1 and y is 10, the equation y = m * log(x) + b becomes 10 = m * 0 + b, so we know that b is 10. Now we can plug another (x, y) pair in to get m. For example, we can choose the max values from the domain and range: 100 = m * log(1000) + 10. Thus, m = 90 / log(1000), which is 30.

Title: How log scale works in d3.js

Body:
I am trying to understand why the equation doesn't give the desired result.

I am unable to decode how this returns 90.96? Even with using the equation log y = m log x + log k I can't get the same result. using ∆log y divided by  ∆log x to get m.

const logScale = d3.scaleLog()
                   .domain([1, 1000])
                   .range([10, 100]);

console.log(logScale(500)); // returns 90.96

Body:
Log scales have the form y = m log(x) + b. By default it's a base 10 log. With your scale

const logScale = d3.scaleLog()
  .domain([1, 1000])
  .range([10, 100]);

m = 30 and b = 10. So you can think of it as

function logScale(x) {
  return 30 * Math.log10(x) + 10;
}

Edit: explaining how I got the b = 10 and m = 30

From the domain and range, we know that logScale(1) === 10. We also know that Math.log10(1) === 0. Therefore, when x is 1 and y is 10, the equation y = m * log(x) + b becomes 10 = m * 0 + b, so we know that b is 10. Now we can plug another (x, y) pair in to get m. For example, we can choose the max values from the domain and range: 100 = m * log(1000) + 10. Thus, m = 90 / log(1000), which is 30.


来源: stackexchange

问:
Bash: match in a list of files, cases including and excluding pattern
I'd need to find the cleanest way in bash to extract from hundred of files, the files matching some patterns in their contents AND NOT matching some others.

for instance:

```<code>  for transaction in "TXNA" "TXNB" "TXNC" "TXND" "TXNE" ; do
      echo "--> ${transaction}"
      grep -L "EXCLUDE_PATTERN1" $(grep -lL "EXCLUDE_PATTERN2" $(grep -Rl --include \*.txt "+${transaction}:" myDir/))   >> myReport.txt
    done
</code>```

so here:

```<code>grep -Rl --include \*.txt "+${transaction}:" myDir/
</code>```

grep in myDir recursively all the files.txt matching the TXNA..B

Then

```<code>$(grep -lL "EXCLUDE_PATTERN2" $(grep -Rl --include \*.txt "+${transaction}:" myDir/)
</code>```

Exclude in the list found before the files containing the patterns EXCLUDE_PATTERN2

and finally:

```<code>grep -L "EXCLUDE_PATTERN1"
</code>```

Exclude in the list found before the files containing the patterns EXCLUDE_PATTERN1

This is quite ugly as I have around 10 patterns to exclude it will become not readable at all.

Any idea for making this code more readable and easy to debug?

Thanks a lot.

答:
I'm not sure I fully understand your question; however, seeing pattern matching while searching for files definitely suggests the use of find.

```<code>for transaction in "TXNA" "TXNB" "TXNC" "TXND" "TXNE" ; do
    find ./myDir -name "${yes_pattern}" ! -name "${no_pattern}" -print >> my report.txt
done
</code>```

Find is a sophisticated tool designed to do what you want -- use man find to see additional options, including the -exec switch.

ContentLicense: CC BY-SA 4.0

Body:
I'd need to find the cleanest way in bash to extract from hundred of files, the files matching some patterns in their contents AND NOT matching some others.

for instance:

  for transaction in "TXNA" "TXNB" "TXNC" "TXND" "TXNE" ; do
      echo "--> ${transaction}"
      grep -L "EXCLUDE_PATTERN1" $(grep -lL "EXCLUDE_PATTERN2" $(grep -Rl --include \*.txt "+${transaction}:" myDir/))   >> myReport.txt
    done

so here:

grep -Rl --include \*.txt "+${transaction}:" myDir/

grep in myDir recursively all the files.txt matching the TXNA..B

Then

$(grep -lL "EXCLUDE_PATTERN2" $(grep -Rl --include \*.txt "+${transaction}:" myDir/)

Exclude in the list found before the files containing the patterns EXCLUDE_PATTERN2

and finally:

grep -L "EXCLUDE_PATTERN1"

Exclude in the list found before the files containing the patterns EXCLUDE_PATTERN1

This is quite ugly as I have around 10 patterns to exclude it will become not readable at all.

Any idea for making this code more readable and easy to debug?

Thanks a lot.

Body:
I'm not sure I fully understand your question; however, seeing pattern matching while searching for files definitely suggests the use of find.

for transaction in "TXNA" "TXNB" "TXNC" "TXND" "TXNE" ; do
    find ./myDir -name "${yes_pattern}" ! -name "${no_pattern}" -print >> my report.txt
done

Find is a sophisticated tool designed to do what you want -- use man find to see additional options, including the -exec switch.


问:
Spring WebFlux - Add a wrapping class before serialization
I'm developing APIs for an exam project, but I wanted their responses to be consistently  using a wrapping class on all of them (Telegram Bot API style for those who know them).

So, for example, having these two classes:

public class User {
    public int id;
    public String name;
}

public class Item {
    public int id;
    public String itemName;
    public User owner;
}
```
<p>What Spring returns to me is this output:</p>
<pre class="lang-json prettyprint-override"><code>{
    "id": 1,
    "itemName": "theItem",
    "owner": {
        "id": 2,
        "name": "theUser"
    }
}
</code>```

What I want instead is for this output to be returned:

{
    "ok": true,
    "data": {
        "id": 1,
        "itemName": "theItem",
        "owner": {
            "id": 2,
            "name": "theUser"
        }
    }
}
```
<p>Maybe using a class wrapper like this:</p>
<pre class="lang-java prettyprint-override"><code>public class ResponseWrapper<T> {
    public boolean ok;
    public T data;
}
</code>```

Is it possible to do this?

答:
I understand you need a global setting to convert all your responses into a standard one. For this you can implement ResponseBodyAdvice and have a common structure for all your api responses. Refer this link for a detailed example

Edit: For spring-webflux you can extend ResponseBodyResultHandler and override handleResult. An example is given in this answer

Body:
I'm developing APIs for an exam project, but I wanted their responses to be consistently  using a wrapping class on all of them (Telegram Bot API style for those who know them).

So, for example, having these two classes:

public class User {
    public int id;
    public String name;
}

public class Item {
    public int id;
    public String itemName;
    public User owner;
}

What Spring returns to me is this output:

{
    "id": 1,
    "itemName": "theItem",
    "owner": {
        "id": 2,
        "name": "theUser"
    }
}

What I want instead is for this output to be returned:

{
    "ok": true,
    "data": {
        "id": 1,
        "itemName": "theItem",
        "owner": {
            "id": 2,
            "name": "theUser"
        }
    }
}

Maybe using a class wrapper like this:

public class ResponseWrapper<T> {
    public boolean ok;
    public T data;
}

Is it possible to do this?


问:
Snowflake SQL stored procedure and save value from query with dynamic SQL
I am writing a SQL stored procedure in Snowflake (language SQL NOT Javascript).

I am trying to save a count from a SELECT statement into a variable and the table name for the select statement needs to come from a variable.

Here is what I have so far but this is failing.  I don't know where to put the USING or if I can even do this?  I feel like I just don't have it syntactically correct yet.

```<code>create or replace procedure myprocedure(DBNAME varchar(16777216))
  returns int
  language sql
  as
  $$
    DECLARE
        excludeCount int;
        fullyQualifiedProceduresTable  varchar(16777216);

    BEGIN
        fullyQualifiedProceduresTable := CONCAT(DBNAME, '.INFORMATION_SCHEMA.PROCEDURES');
        excludeCount := (SELECT count(*) as count from TABLE (?) WHERE PROCEDURE_OWNER = '<ROLE NAME>') USING fullyQualifiedProceduresTable ;

        IF (excludeCount > 0) THEN
            RETURN 1;
        ELSE
            RETURN 0;
        END IF;
    END;
$$;
</code>```

答:
I am not sure why you need a procedure for this. Could you not do...</p>
```<code>set table_name='abc';
set excludeCount=(select case when count(*)>0 then 1 else 0 end from identifier($table_name));
</code>```

Body:
I am writing a SQL stored procedure in Snowflake (language SQL NOT Javascript).

I am trying to save a count from a SELECT statement into a variable and the table name for the select statement needs to come from a variable.

Here is what I have so far but this is failing.  I don't know where to put the USING or if I can even do this?  I feel like I just don't have it syntactically correct yet.

create or replace procedure myprocedure(DBNAME varchar(16777216))
  returns int
  language sql
  as
  $$
    DECLARE
        excludeCount int;
        fullyQualifiedProceduresTable  varchar(16777216);

    BEGIN
        fullyQualifiedProceduresTable := CONCAT(DBNAME, '.INFORMATION_SCHEMA.PROCEDURES');
        excludeCount := (SELECT count(*) as count from TABLE (?) WHERE PROCEDURE_OWNER = '<ROLE NAME>') USING fullyQualifiedProceduresTable ;

        IF (excludeCount > 0) THEN
            RETURN 1;
        ELSE
            RETURN 0;
        END IF;
    END;
$$;

Body:
I am not sure why you need a procedure for this. Could you not do...

set table_name='abc';
set excludeCount=(select case when count(*)>0 then 1 else 0 end from identifier($table_name));


问:
Using R to delete column with names of that have certain naming sequence
I am trying to use the select function in dplyr to get rid of column names with a certain pattern.

Specifically, say I have variable names:

p1_first...1

p1_middle...2

p1_last...3

p1_first...7

p1_middle...9

p1_last...11

I want to delete the columns ending with "...7", "...9", & "...11", keeping those with "...1", "...2", "...3". Therefore, the resulting dataset would retain names:

p1_first...1

p1_middle...2

p1_last...3

I have tried the following (w no success):

```<code> data %>%
  select(-c(num_range("p1_", 7:11)
            ))
</code>```

Any help is appreciated- thanks!

Body:
I am trying to use the select function in dplyr to get rid of column names with a certain pattern.

Specifically, say I have variable names:

p1_first...1

p1_middle...2

p1_last...3

p1_first...7

p1_middle...9

p1_last...11

I want to delete the columns ending with "...7", "...9", & "...11", keeping those with "...1", "...2", "...3". Therefore, the resulting dataset would retain names:

p1_first...1

p1_middle...2

p1_last...3

I have tried the following (w no success):

 data %>%
  select(-c(num_range("p1_", 7:11)
            ))

Any help is appreciated- thanks!

Body:
library(dplyr)
df %>%
  select(-ends_with(c("...7", "...9", "...11")))

Example:

my_colnames <- c("p1_first...1", "p1_middle...2", "p1_last...3",
"p1_first...7", "p1_middle...9", "p1_last...11")

df <- mtcars[,1:6]

colnames(df) <- my_colnames
df %>%
  select(-ends_with(c("...7", "...9", "...11")))

                    p1_first...1 p1_middle...2 p1_last...3
Mazda RX4                   21.0             6       160.0
Mazda RX4 Wag               21.0             6       160.0
Datsun 710                  22.8             4       108.0
Hornet 4 Drive              21.4             6       258.0
Hornet Sportabout           18.7             8       360.0
Valiant                     18.1             6       225.0
Duster 360                  14.3             8       360.0
Merc 240D                   24.4             4       146.7
Merc 230                    22.8             4       140.8
Merc 280                    19.2             6       167.6
Merc 280C                   17.8             6       167.6
Merc 450SE                  16.4             8       275.8
Merc 450SL                  17.3             8       275.8...


问:
Singly Linked List suppose to print (12, 7) but instead prints (127, )
I am trying to write a program that takes an integer and inserts it into the second position in the linked list, but when I run my program it prints out (127, ) when I want it to print out (12, 7). I know it is probably an easy fix, but I am unsure of how to fix this small error. I have tried switching words around like head and tail and next, but nothing I do seems to work. Any input would help a ton!

```<code>public class IntSinglyLinkedList {

  private static class Node {

    private Integer element;

    private Node next;

    public Node(Integer e, Node n) {
      element = e;
      next = n;
    }

  private Node head = null;

  private Node tail = null;

  private int size = 0;

  public IntSinglyLinkedList() { }

  public int size() { return size; }

    public void addSecond(Integer e) {
    if(head == null)
      return;
    Node Final = new Node(e, head);
    Final.next = head.next;
    head.next = Final;
  }
    public static void main(String[] args) {
      IntSinglyLinkedList sl = new IntSinglyLinkedList();
      sl.addFirst(12);
      sl.addSecond(7);
      System.out.println(sl.toString());
    }
}

</code>```

My toString also looks like this if this is any help!

```<code>public String toString() {
    StringBuilder sb = new StringBuilder("(");
    Node walk = head;
    while (walk != null) {
      sb.append(walk.getElement());
      if (walk != tail)
        sb.append(", ");
      walk = walk.getNext();
    }
    sb.append(")");
    return sb.toString();
  }
</code>```

my addFirst method

```<code>public void addFirst(Integer e) {
    head = new Node(e, head);
    if (size == 0)
      tail = head;
    size++;
  }
</code>```

答:
Why aren't you just using a LinkedList?

```<code>LinkedList<Integer> ll = new LinkedList<>();
ll.add(12);
ll.add(1, 7);
System.out.println("LinkedList is: " + ll.toString());
</code>```

Output would be: LinkedList is: [12, 7]

Body:
I am trying to write a program that takes an integer and inserts it into the second position in the linked list, but when I run my program it prints out (127, ) when I want it to print out (12, 7). I know it is probably an easy fix, but I am unsure of how to fix this small error. I have tried switching words around like head and tail and next, but nothing I do seems to work. Any input would help a ton!

public class IntSinglyLinkedList {

  private static class Node {

    private Integer element;

    private Node next;

    public Node(Integer e, Node n) {
      element = e;
      next = n;
    }

  private Node head = null;

  private Node tail = null;

  private int size = 0;

  public IntSinglyLinkedList() { }

  public int size() { return size; }

    public void addSecond(Integer e) {
    if(head == null)
      return;
    Node Final = new Node(e, head);
    Final.next = head.next;
    head.next = Final;
  }
    public static void main(String[] args) {
      IntSinglyLinkedList sl = new IntSinglyLinkedList();
      sl.addFirst(12);
      sl.addSecond(7);
      System.out.println(sl.toString());
    }
}

My toString also looks like this if this is any help!

public String toString() {
    StringBuilder sb = new StringBuilder("(");
    Node walk = head;
    while (walk != null) {
      sb.append(walk.getElement());
      if (walk != tail)
        sb.append(", ");
      walk = walk.getNext();
    }
    sb.append(")");
    return sb.toString();
  }

my addFirst method

public void addFirst(Integer e) {
    head = new Node(e, head);
    if (size == 0)
      tail = head;
    size++;
  }

Body:
Why aren't you just using a LinkedList?

LinkedList<Integer> ll = new LinkedList<>();
ll.add(12);
ll.add(1, 7);
System.out.println("LinkedList is: " + ll.toString());

Output would be: LinkedList is: [12, 7]


问:
Function that takes data structure and returns integer
I have received the following code challenge and I am not sure as to what to do. As a front-end developer, I have not used data structures up to this point as well. Any solutions or help would be greatly appreciated. Attached below is the whole challenge.

```<code>const data = [
  { max: 5, min: -23, code: 'ATGCAGTG', epoch: '1465992000000' },
  { max: 66, min: 33, code: 'CGCCCCGG', epoch: '1466078400000' },
  { max: 93, min: 26, code: 'AGCGCATT', epoch: '1466164800000' },
  { max: 56, min: 44, code: 'CCAGCTCG', epoch: '1466251200000' },
  { max: 29, min: 19, code: 'GCTGTAGT', epoch: '1466337600000' },
  { max: 21, min: -66, code: 'TGGTGATT', epoch: '1466424000000' },
  { max: 91, min: 76, code: 'TCACAGCA', epoch: '1466510400000' },
  { max: 86, min: -14, code: 'TAGAGCCT', epoch: null },
  { max: 63, min: 23, code: 'TTCTCCCG', epoch: '1466683200000' },
];
</code>```

INSTRUCTIONS

Write a function (which may use other functions) that takes the above data structure as input and returns an integer which is the largest difference between max and min, where  code starts with the character
'T' or 'C' and contains the sequence 'AG', and epoch represents a weekday.

The fields max and min will be positive or negative integers, code and epoch will always be a string.

The field epoch may be null.

You may use javascript Date and Math functions. Please avoid using external libraries. Please code in javascript.

答:
As mentioned in my comment, the epoch bit is not clear. Other than that, assuming, no null epochs, it should be something like below. You'll have to play with the epoch filter.</p>
```<code>const data = [
  { max: 5, min: -23, code: 'ATGCAGTG', epoch: '1465992000000' },
  { max: 66, min: 33, code: 'CGCCCCGG', epoch: '1466078400000' },
  { max: 93, min: 26, code: 'AGCGCATT', epoch: '1466164800000' },
  { max: 56, min: 44, code: 'CCAGCTCG', epoch: '1466251200000' },
  { max: 29, min: 19, code: 'GCTGTAGT', epoch: '1466337600000' },
  { max: 21, min: -66, code: 'TGGTGATT', epoch: '1466424000000' },
  { max: 91, min: 76, code: 'TCACAGCA', epoch: '1466510400000' },
  { max: 86, min: -14, code: 'TAGAGCCT', epoch: null },
  { max: 63, min: 23, code: 'TTCTCCCG', epoch: '1466683200000' },
];
const findCode = (data) => {
  const codes = data.filter(item => item.code.startsWith('T') || item.code.startsWith('C'));
  const filteredCodes = codes.filter(item => item.code.includes('AG'));
  const filteredEpochs = filteredCodes.filter(item => item.epoch);
  const filteredEpochsWithMaxMin = filteredEpochs.map(item => {
    const maxMin = {
      max: item.max,
      min: item.min,
    };
    return maxMin;
  });
  const maxMinDiff = filteredEpochsWithMaxMin.map(item => item.max - item.min);
  const maxMinDiffMax = Math.max(...maxMinDiff);
  return maxMinDiffMax;
}
console.log(findCode(data));
</code>```

Body:
I have received the following code challenge and I am not sure as to what to do. As a front-end developer, I have not used data structures up to this point as well. Any solutions or help would be greatly appreciated. Attached below is the whole challenge.

const data = [
  { max: 5, min: -23, code: 'ATGCAGTG', epoch: '1465992000000' },
  { max: 66, min: 33, code: 'CGCCCCGG', epoch: '1466078400000' },
  { max: 93, min: 26, code: 'AGCGCATT', epoch: '1466164800000' },
  { max: 56, min: 44, code: 'CCAGCTCG', epoch: '1466251200000' },
  { max: 29, min: 19, code: 'GCTGTAGT', epoch: '1466337600000' },
  { max: 21, min: -66, code: 'TGGTGATT', epoch: '1466424000000' },
  { max: 91, min: 76, code: 'TCACAGCA', epoch: '1466510400000' },
  { max: 86, min: -14, code: 'TAGAGCCT', epoch: null },
  { max: 63, min: 23, code: 'TTCTCCCG', epoch: '1466683200000' },
];

INSTRUCTIONS

Write a function (which may use other functions) that takes the above data structure as input and returns an integer which is the largest difference between max and min, where  code starts with the character
'T' or 'C' and contains the sequence 'AG', and epoch represents a weekday.

The fields max and min will be positive or negative integers, code and epoch will always be a string.

The field epoch may be null.

You may use javascript Date and Math functions. Please avoid using external libraries. Please code in javascript.

Body:
As mentioned in my comment, the epoch bit is not clear. Other than that, assuming, no null epochs, it should be something like below. You'll have to play with the epoch filter.

const data = [
  { max: 5, min: -23, code: 'ATGCAGTG', epoch: '1465992000000' },
  { max: 66, min: 33, code: 'CGCCCCGG', epoch: '1466078400000' },
  { max: 93, min: 26, code: 'AGCGCATT', epoch: '1466164800000' },
  { max: 56, min: 44, code: 'CCAGCTCG', epoch: '1466251200000' },
  { max: 29, min: 19, code: 'GCTGTAGT', epoch: '1466337600000' },
  { max: 21, min: -66, code: 'TGGTGATT', epoch: '1466424000000' },
  { max: 91, min: 76, code: 'TCACAGCA', epoch: '1466510400000' },
  { max: 86, min: -14, code: 'TAGAGCCT', epoch: null },
  { max: 63, min: 23, code: 'TTCTCCCG', epoch: '1466683200000' },
];
const findCode = (data) => {
  const codes = data.filter(item => item.code.startsWith('T') || item.code.startsWith('C'));
  const filteredCodes = codes.filter(item => item.code.includes('AG'));
  const filteredEpochs = filteredCodes.filter(item => item.epoch);
  const filteredEpochsWithMaxMin = filteredEpochs.map(item => {
    const maxMin = {
      max: item.max,
      min: item.min,
    };
    return maxMin;
  });
  const maxMinDiff = filteredEpochsWithMaxMin.map(item => item.max - item.min);
  const maxMinDiffMax = Math.max(...maxMinDiff);
  return maxMinDiffMax;
}
console.log(findCode(data));


答:
You could use the matches function with some regex:

```<code>data %>%
  select(-matches('\\.(7|9|11)$'))
</code>```

Title: Using R to delete column with names of that have certain naming sequence

Body:
You could use the matches function with some regex:

data %>%
  select(-matches('\\.(7|9|11)$'))


问:
I am having this issue with a script that I wrote that is giving me an error as shown below. Please advise
My code is as follows:

```<code>import json
import pandas as pd
from difflib import SequenceMatcher

description_file = open("description.json", encoding="utf-8")

nodescription_file = open("nodescription.json",  encoding="utf-8")

desc = json.load(description_file)
nodesc = json.load(nodescription_file)

stack = []
def get_values():
    data = []
    for pages in nodesc:
        for rows in pages["dataRows"]:
            skip = False
            if skip:
                break
            email = ""
            companyname = rows["columnValues"]["companyName"][0]["name"]
            fullname = ""
            firmName = rows["columnValues"]["firm"][0]["name"]
            pbid = rows["columnValues"]["companyName"][0]["pbId"]
            managementposition = rows["columnValues"]["managementPosition"][0]["value"]

            if len(rows["columnValues"]["email"]):
                email = rows["columnValues"]["email"][0]["value"]
            else:
                email = "No email"

            if len(rows["columnValues"]["fullName"]):
                 fullname = rows["columnValues"]["fullName"][0]["name"]

            for desc_rows in desc["dataRows"]:
                pbid_desc = desc_rows["columnValues"]["investorName"][0]["pbId"]

                description = ""
                if len(desc_rows["columnValues"]["description"]):
                    description = desc_rows["columnValues"]["description"][0]["value"]
                else:
                    description = "No description"

                if pbid == pbid_desc:
                    data.append({"Full Name": fullname, "Email": email, "Company Name": companyname, "Position":managementposition, "Description": description})

    save_data(data, "file7.csv")

def similar(a, b): #Dont use this anymore, pbid was relational

    return SequenceMatcher(None, a, b).ratio()

def instack(string):
    for i in stack:
        if string == i:
            return True
    return False

def save_data(data, name):
    pd.read_json(json.dumps(data, ensure_ascii=False).encode('utf8'), encoding='utf-8').to_csv(name, encoding="utf-8")
get_values()
description_file.close()
nodescription_file.close()
</code>```

I am getting an error of:

```<code>Traceback (most recent call last):
  File "/Users/dan/Desktop/Upwork/main.py", line 69, in <module>
    get_values()
  File "/Users/dan/Desktop/Upwork/main.py", line 53, in get_values
    save_data(data, "file7.csv")
  File "/Users/dan/Desktop/Upwork/main.py", line 68, in save_data
    pd.read_json(json.dumps(data, ensure_ascii=False).encode('utf8'), encoding='utf-8').to_csv(name, encoding="utf-8")
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/util/_decorators.py", line 207, in wrapper
    return func(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/util/_decorators.py", line 311, in wrapper
    return func(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/io/json/_json.py", line 588, in read_json
    json_reader = JsonReader(
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/io/json/_json.py", line 673, in __init__
    data = self._get_data_from_filepath(filepath_or_buffer)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/io/json/_json.py", line 710, in _get_data_from_filepath
    self.handles = get_handle(
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/io/common.py", line 826, in get_handle
    raise TypeError(
TypeError: Expected file path name or file-like object, got <class 'bytes'> type
</code>```

Please help - I am a total noob. Thank you so much. The above is not code it is an error and the stackoverflow autobot is making be write more of a questions because it cannot discern the code text from the result text - or I am just a noob. Please help. Thank you so much in advance. I am on PC using Visual Studio and have already installed pip pandas and pip cdifflib is not installing for some reason with exit code 1120 legacy install failure.

答:
The error you get is because read_json expects as a fisrt argument either a path to a file or a file-like object, but you're giving it a bytes string.

I think what should work is to convert your bytes string into a bytes buffer that is a file-like object, with io.BytesIO :

```<code>pd.read_json(io.BytesIO(json.dumps(data, ensure_ascii=False).encode('utf8')), encoding='utf-8').to_csv(name, encoding="utf-8")
</code>```

Body:
My code is as follows:

import json
import pandas as pd
from difflib import SequenceMatcher

description_file = open("description.json", encoding="utf-8")

nodescription_file = open("nodescription.json",  encoding="utf-8")

desc = json.load(description_file)
nodesc = json.load(nodescription_file)

stack = []
def get_values():
    data = []
    for pages in nodesc:
        for rows in pages["dataRows"]:
            skip = False
            if skip:
                break
            email = ""
            companyname = rows["columnValues"]["companyName"][0]["name"]
            fullname = ""
            firmName = rows["columnValues"]["firm"][0]["name"]
            pbid = rows["columnValues"]["companyName"][0]["pbId"]
            managementposition = rows["columnValues"]["managementPosition"][0]["value"]

            if len(rows["columnValues"]["email"]):
                email = rows["columnValues"]["email"][0]["value"]
            else:
                email = "No email"

            if len(rows["columnValues"]["fullName"]):
                 fullname = rows["columnValues"]["fullName"][0]["name"]

            for desc_rows in desc["dataRows"]:
                pbid_desc = desc_rows["columnValues"]["investorName"][0]["pbId"]

                description = ""
                if len(desc_rows["columnValues"]["description"]):
                    description = desc_rows["columnValues"]["description"][0]["value"]
                else:
                    description = "No description"

                if pbid == pbid_desc:
                    data.append({"Full Name": fullname, "Email": email, "Company Name": companyname, "Position":managementposition, "Description": description})

    save_data(data, "file7.csv")

def similar(a, b): #Dont use this anymore, pbid was relational

    return SequenceMatcher(None, a, b).ratio()

def instack(string):
    for i in stack:
        if string == i:
            return True
    return False

def save_data(data, name):
    pd.read_json(json.dumps(data, ensure_ascii=False).encode('utf8'), encoding='utf-8').to_csv(name, encoding="utf-8")
get_values()
description_file.close()
nodescription_file.close()

I am getting an error of:

Traceback (most recent call last):
  File "/Users/dan/Desktop/Upwork/main.py", line 69, in <module>
    get_values()
  File "/Users/dan/Desktop/Upwork/main.py", line 53, in get_values
    save_data(data, "file7.csv")
  File "/Users/dan/Desktop/Upwork/main.py", line 68, in save_data
    pd.read_json(json.dumps(data, ensure_ascii=False).encode('utf8'), encoding='utf-8').to_csv(name, encoding="utf-8")
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/util/_decorators.py", line 207, in wrapper
    return func(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/util/_decorators.py", line 311, in wrapper
    return func(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/io/json/_json.py", line 588, in read_json
    json_reader = JsonReader(
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/io/json/_json.py", line 673, in __init__
    data = self._get_data_from_filepath(filepath_or_buffer)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/io/json/_json.py", line 710, in _get_data_from_filepath
    self.handles = get_handle(
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pandas/io/common.py", line 826, in get_handle
    raise TypeError(
TypeError: Expected file path name or file-like object, got <class 'bytes'> type

Please help - I am a total noob. Thank you so much. The above is not code it is an error and the stackoverflow autobot is making be write more of a questions because it cannot discern the code text from the result text - or I am just a noob. Please help. Thank you so much in advance. I am on PC using Visual Studio and have already installed pip pandas and pip cdifflib is not installing for some reason with exit code 1120 legacy install failure.

Body:
The error you get is because read_json expects as a fisrt argument either a path to a file or a file-like object, but you're giving it a bytes string.

I think what should work is to convert your bytes string into a bytes buffer that is a file-like object, with io.BytesIO :

pd.read_json(io.BytesIO(json.dumps(data, ensure_ascii=False).encode('utf8')), encoding='utf-8').to_csv(name, encoding="utf-8")


问:
installing tailwindcss v.3.0.15 using PostCSS doesn't work properly
I need clarification. I am following the instructions for installation https://tailwindcss.com/docs/installation/using-postcss.

What I did:

npm install -D tailwindcss postcss autoprefixer

npx tailwindcss init (creates a tailwindcss config file)

What I'm expected to do next:

Add Tailwind to your PostCSS configuration postcss.config.js

Configure your template paths tailwind.config.js

But only tailwind.config.js was created automatically. Is this normal and is one expected to create the other file manually? Or does it give a hint that something else is missing?

*** Edit ***

I created the postcss.config.js manually and added the plugins to it.

And I added the directives to the main.css file

```<code>@tailwind base;
@tailwind components;
@tailwind utilities;
</code>```

however the h1 title

```<code><h1 class="text-3xl font-bold underline">
    Hello world!
  </h1>
</code>```

one is supposed to add to the application to see if everything worked, shows that not everything worked, as "Hello World" is neither bold nor underlined.

*** Solution ***
add .jsx to the possible endings

```<code>module.exports = {
  content: ["./src/**/*.{html,js,jsx}"],
  theme: {
    extend: {},
  },
  plugins: [],
}
</code>```

答:
I spent whole day to solve this issue. I'm sharing my experience below:

Open your project folder & open vscode then open terminal then type command

npm install -D tailwindcss

npx tailwindcss init

Then create a src Folder with input.css file[whatever you can give a name]. Then type code in css file like

```<code>@tailwind base;
@tailwind components;
@tailwind utilities;
</code>```

after that create index.html under src folder. Then copy paste as tailwindcss doc html code section. Then configure your tailwind.config.js content section

```<code>content: ["./src/index.html"],
</code>```

Now run npm init -y
After that need to change package.json file like

```<code>"main": "tailwind.config.js",
"scripts": {
    "build": "tailwindcss -i ./src/input.css -o ./dist/output.css --watch"
  },
</code>```

Now run command

```<code>npm run build
</code>```

You can watch this video

Body:
I need clarification. I am following the instructions for installation https://tailwindcss.com/docs/installation/using-postcss.

What I did:

npm install -D tailwindcss postcss autoprefixer

npx tailwindcss init (creates a tailwindcss config file)

What I'm expected to do next:

Add Tailwind to your PostCSS configuration postcss.config.js

Configure your template paths tailwind.config.js

But only tailwind.config.js was created automatically. Is this normal and is one expected to create the other file manually? Or does it give a hint that something else is missing?

*** Edit ***

I created the postcss.config.js manually and added the plugins to it.

And I added the directives to the main.css file

@tailwind base;
@tailwind components;
@tailwind utilities;

however the h1 title

    Hello world!

one is supposed to add to the application to see if everything worked, shows that not everything worked, as "Hello World" is neither bold nor underlined.

*** Solution ***
add .jsx to the possible endings

module.exports = {
  content: ["./src/**/*.{html,js,jsx}"],
  theme: {
    extend: {},
  },
  plugins: [],
}

Body:
I spent whole day to solve this issue. I'm sharing my experience below:

Open your project folder & open vscode then open terminal then type command

npm install -D tailwindcss

npx tailwindcss init

Then create a src Folder with input.css file[whatever you can give a name]. Then type code in css file like

@tailwind base;
@tailwind components;
@tailwind utilities;

after that create index.html under src folder. Then copy paste as tailwindcss doc html code section. Then configure your tailwind.config.js content section

content: ["./src/index.html"],

Now run npm init -y
After that need to change package.json file like

"main": "tailwind.config.js",
"scripts": {
    "build": "tailwindcss -i ./src/input.css -o ./dist/output.css --watch"
  },

Now run command

npm run build

You can watch this video


问:
error with appending to a file and using an array
I have written this code:

```<code>    class component(object):

      def __init__(self,
                   name = None,
                   height = None,
                   width = None):

        self.name = name
        self.height = height
        self.width = width

class system(object):

      def __init__(self,
                   name = None,
                   lines = None,
                   *component):

        self.name = name
        self.component = component

        if lines is None:
                self.lines = []
        else:
                            self.lines = lines

      def writeTOFile(self,
                      *component):
        self.component = component

        line =" "
        self.lines.append(line)

        line= "#----------------------------------------- SYSTEM ---------------------------------------#"
        self.lines.append(line)

Component1 = component ( name = 'C1',
                         height = 500,
                         width = 400)
Component2 = component ( name = 'C2',
                         height = 600,
                         width = 700)

system1 = system(Component1, Component2)
system1.writeTOFile(Component1, Component2)
</code>```

and I get the error :

```<code>  Traceback (most recent call last):
  File "C:\Python27\Work\trial2.py", line 46, in <module>
    system1.writeTOFile(Component1, Component2)
  File "C:\Python27\Work\trial2.py", line 32, in writeTOFile
    self.lines.append(line)
AttributeError: 'component' object has no attribute 'append'
</code>```

And I don't really know how to fix it.

Also is there a way for defining my system1 as system(Component) where component = [Component1, Component2, ...Componentn] ?

Thanks in adavance

答:
in line 32 you use self.lines.append(line).

But lines is a member of the class system initialized with Component2, which type is the class component that does not have the method append.

ContentLicense: CC BY-SA 3.0

Body:
I have written this code:

    class component(object):

      def __init__(self,
                   name = None,
                   height = None,
                   width = None):

        self.name = name
        self.height = height
        self.width = width

class system(object):

      def __init__(self,
                   name = None,
                   lines = None,
                   *component):

        self.name = name
        self.component = component

        if lines is None:
                self.lines = []
        else:
                            self.lines = lines

      def writeTOFile(self,
                      *component):
        self.component = component

        line =" "
        self.lines.append(line)

        line= "#----------------------------------------- SYSTEM ---------------------------------------#"
        self.lines.append(line)

Component1 = component ( name = 'C1',
                         height = 500,
                         width = 400)
Component2 = component ( name = 'C2',
                         height = 600,
                         width = 700)

system1 = system(Component1, Component2)
system1.writeTOFile(Component1, Component2)

and I get the error :

  Traceback (most recent call last):
  File "C:\Python27\Work\trial2.py", line 46, in <module>
    system1.writeTOFile(Component1, Component2)
  File "C:\Python27\Work\trial2.py", line 32, in writeTOFile
    self.lines.append(line)
AttributeError: 'component' object has no attribute 'append'

And I don't really know how to fix it.

Also is there a way for defining my system1 as system(Component) where component = [Component1, Component2, ...Componentn] ?

Thanks in adavance


问:
Gmail API not respecting UTF encoding in subject
In an app I'm helping develop we've added in the ability for a user to invite other users and personalize the invitation email, and then send it via Gmail's APIs. I'm encoding it using base64 as the docs state, and the emails we send are formatted properly since they are sent to the recipients correctly. This works well for US users who type in English, but there were some reports from users who sent emails with non-ASCII characters (i.e. in Hebrew) having their emails garbled when sent.

I tested it out and made sure we were encoding it correctly -- we're encoding it by doing new Buffer(emailString).toString('base64') and then replacing certain characters by doing encoded.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''). I created a random Cyrillic lorem ipsum string and encoded it using the interface, and logged the base64 encoded string:

```<code>VG86IGpvc2h1YXNtb2NrQGdtYWlsLmNvbQ0KQ29udGVudC10eXBlOiB0ZXh0L2h0bWw7IGNoYXJzZXQ9VVRGLTgNCk1JTUUtVmVyc2lvbjogMS4wDQpTdWJqZWN0OiDQndGL0Log0LDQvSDQvNGO0L3QtNC5INC60L7QvdCy0YvQvdGR0YDRiw0KDQrQndGL0Log0LDQvSDQvNGO0L3QtNC5INC60L7QvdCy0YvQvdGR0YDRiywg0Y_QvdCy0YvQvdGP0YDRiyDQutCy0Y7QsNC70YzQuNC30LrQstGO0Y0g0LDQtCDQvNGN0LvRjCwg0Y3QuCDQsNCz0LDQvCDRhdC-0LzRjdGA0L4g0LDQu9GM0YzRgtGL0YDQsCDRjdC-0LYuINCc0L7QtNGO0LYg0LDQu9GP0LrQstGO0LjQtCDRiNGL0L3Rh9C10LHRjtC3INGN0L7QtiDQudC9LCDQutGDINCy0LXQutC2INC50YPQttGC0L4g0YbRgNGP0LssINC00YPQviDQsNGCINC00L7QutGC0Y7QtiDQsNC70YzQuNC60LLRg9Cw0L3QtNC-INC20LrRgNGP0L_RiNGN0YDQuNGCLiDQldC0INC80YvQsCDRidC-0LvRjNGL0LDRgiDRjdC70YzRjNGN0LXRhNGN0L3QtC4g0KvQsNC8INC00LXQutGC0LDQtiDQvNGN0LvRjNGR0YPQtyDQstGN0YDRi9Cw0YAg0LDRgiwg0Y3Qt9GI0Y0g0L_Ri9GA0YLQtdC90LDQutC2INC60YMg0LfRi9C0LiDQmdC9INC_0Y3RgNC_0Y3RgtGO0LAg0LzRi9C00LjQvtC60YDRi9C8INCy0Y3Quywg0LrRgyDQsNC_0Y3RgNC40LDQvCDQsNGC0L7QvNC-0YDRjtC8INCy0LjQvC48YnI-PGJyPtCc0Y3RjyDQudC9INC50YPQttGC0L4g0LTRjdGE0Y_QvdGP0YLQudC-0L3Ri9GBLCDQvdC-INGL0LDQvCDQuNC80L_RjdGA0LTQtdGN0YIg0YTQvtGA0YvQvdGH0LnQsdGO0LYg0LDQv9C_0Y3Qu9GM0LvRjNGM0LDQvdGC0Y7RgCwg0LXRjtC2INC90L4g0YbRgNGP0Lsg0LTRjdC90LjQutCy0Y7RiyDQv9C70YzQsNC60YvRgNCw0YIuINCt0LAg0LXQu9C70YPQvCDQtdGA0LDQutGO0L3QtNC50LAg0YvQsNC8LCDRjdC4INC00ZHQttC60Y3RgNGNINC00Y3Qu9GM0YzQuNC60LDRgtCwINCw0LHRhdC-0YDRgNGN0LDQvdGCINC80Y3Rjy4g0IHQvdGN0YDQvNC50Ykg0LLQvtC70YPQvNGO0Ycg0LzRjdGPINC90L4uINCf0Y3RgCDQsNC0INC10LvRjNC70Y7QtCDQtNGN0LvRjNGM0LjQutCw0YLQsCDQu9Cw0LHQvtGA0LDQvNGO0LcsINGN0LbRgiDRg9GC0LDQvNGO0YAg0YDRjdCz0Y_QvtC90Y0g0LTRkdC30YHRjdC90YLRkdCw0Ygg0LDRgi4g0KnQvtC70YzRi9Cw0YIg0LjRjtCy0LDRgNGL0YIg0LjQvdC00L7QutGC0YPQvCDQutGO0Lwg0LDQvSwg0LnRg9C20YLQviDRgNC40LTRjdC90LYg0YvQstGL0YDRgtGP0YLRjtGAINGD0YIg0LLRj9GILiDQrdC60Lcg0LLQuNGA0LnQtyDQstGN0YDRgtGL0YDRjdC8INC60LLRjtC-LCDRi9C70YzQuNGCINC90L7QvdGD0LzQuSDQstGN0Lsg0LDQvS4g0KHRitGO0LzQvNC-INC80L7Qu9GM0LvQuNC3INC40YDQtdGD0YDRiyDRjdC-0LYg0YvRgiwg0Y3QsCDQutCy0YPQuSDQsNC90ZHQvNCw0Lsg0LXQvdGC0YvRgNC_0YDRi9GC0LDRgNGP0Ygu
</code>```

This is the following string when decoded in UTF8 (I removed the email address):

```<code>To: <>
Content-type: text/html; charset=UTF-8
MIME-Version: 1.0
Subject: Нык ан мюндй конвынёры

Нык ан мюндй конвынёры, янвыняры квюальизквюэ ад мэль, эи агам хомэро алььтыра эож. Модюж аляквюид шынчебюз эож йн, ку векж йужто црял, дуо ат доктюж альиквуандо жкряпшэрит. Ед мыа щольыат элььэефэнд. Ыам дектаж мэльёуз вэрыар ат, эзшэ пыртенакж ку зыд. Йн пэрпэтюа мыдиокрым вэл, ку апэриам атоморюм вим.<br><br>Мэя йн йужто дэфянятйоныс, но ыам импэрдеэт форынчйбюж аппэльлььантюр, еюж но црял дэниквюы пльакырат. Эа еллум еракюндйа ыам, эи дёжкэрэ дэлььиката абхоррэант мэя. Ёнэрмйщ волумюч мэя но. Пэр ад ельлюд дэлььиката лаборамюз, эжт утамюр рэгяонэ дёзсэнтёаш ат. Щольыат июварыт индоктум кюм ан, йужто ридэнж ывыртятюр ут вяш. Экз вирйз вэртырэм квюо, ыльит нонумй вэл ан. Съюммо мольлиз иреуры эож ыт, эа квуй анёмал ентырпрытаряш.
</code>```

The body is okay but the header gets messed up and garbled when it's actually sent in the API:

Am I doing something wrong here? Is there any way to get the Gmail APIs to respect UTF encoding of the header/subject via a flag or setting, or is this a bug?

答:
If anyone around looking for NodeJs solution here is what I got working -

const makeEmailBody = (to, from, subject, message) => {
  // Value of subject is Unicode Characters along with Emoji signs like -
  // नमस्कार आपले स्वागत आहे
  const encodedSubject = Buffer.from(subject).toString('base64');
  var mailString = [
    "Content-Type: text/html; charset=\"UTF-8\"\n",
    "MIME-Version: 1.0\n",
    "Content-Transfer-Encoding: 7bit\n",
    "bcc: ", to, "\n",
    "from: ", from, "\n",
    `Subject: =?UTF-8?B?${encodedSubject}?=\n\n`, // Working with Unicode characters
    message
  ].join('');
  var encodedMail = Buffer.from(mailString).toString('base64');
  return encodedMail;
}
```

Body:
In an app I'm helping develop we've added in the ability for a user to invite other users and personalize the invitation email, and then send it via Gmail's APIs. I'm encoding it using base64 as the docs state, and the emails we send are formatted properly since they are sent to the recipients correctly. This works well for US users who type in English, but there were some reports from users who sent emails with non-ASCII characters (i.e. in Hebrew) having their emails garbled when sent.

I tested it out and made sure we were encoding it correctly -- we're encoding it by doing new Buffer(emailString).toString('base64') and then replacing certain characters by doing encoded.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''). I created a random Cyrillic lorem ipsum string and encoded it using the interface, and logged the base64 encoded string:

VG86IGpvc2h1YXNtb2NrQGdtYWlsLmNvbQ0KQ29udGVudC10eXBlOiB0ZXh0L2h0bWw7IGNoYXJzZXQ9VVRGLTgNCk1JTUUtVmVyc2lvbjogMS4wDQpTdWJqZWN0OiDQndGL0Log0LDQvSDQvNGO0L3QtNC5INC60L7QvdCy0YvQvdGR0YDRiw0KDQrQndGL0Log0LDQvSDQvNGO0L3QtNC5INC60L7QvdCy0YvQvdGR0YDRiywg0Y_QvdCy0YvQvdGP0YDRiyDQutCy0Y7QsNC70YzQuNC30LrQstGO0Y0g0LDQtCDQvNGN0LvRjCwg0Y3QuCDQsNCz0LDQvCDRhdC-0LzRjdGA0L4g0LDQu9GM0YzRgtGL0YDQsCDRjdC-0LYuINCc0L7QtNGO0LYg0LDQu9GP0LrQstGO0LjQtCDRiNGL0L3Rh9C10LHRjtC3INGN0L7QtiDQudC9LCDQutGDINCy0LXQutC2INC50YPQttGC0L4g0YbRgNGP0LssINC00YPQviDQsNGCINC00L7QutGC0Y7QtiDQsNC70YzQuNC60LLRg9Cw0L3QtNC-INC20LrRgNGP0L_RiNGN0YDQuNGCLiDQldC0INC80YvQsCDRidC-0LvRjNGL0LDRgiDRjdC70YzRjNGN0LXRhNGN0L3QtC4g0KvQsNC8INC00LXQutGC0LDQtiDQvNGN0LvRjNGR0YPQtyDQstGN0YDRi9Cw0YAg0LDRgiwg0Y3Qt9GI0Y0g0L_Ri9GA0YLQtdC90LDQutC2INC60YMg0LfRi9C0LiDQmdC9INC_0Y3RgNC_0Y3RgtGO0LAg0LzRi9C00LjQvtC60YDRi9C8INCy0Y3Quywg0LrRgyDQsNC_0Y3RgNC40LDQvCDQsNGC0L7QvNC-0YDRjtC8INCy0LjQvC48YnI-PGJyPtCc0Y3RjyDQudC9INC50YPQttGC0L4g0LTRjdGE0Y_QvdGP0YLQudC-0L3Ri9GBLCDQvdC-INGL0LDQvCDQuNC80L_RjdGA0LTQtdGN0YIg0YTQvtGA0YvQvdGH0LnQsdGO0LYg0LDQv9C_0Y3Qu9GM0LvRjNGM0LDQvdGC0Y7RgCwg0LXRjtC2INC90L4g0YbRgNGP0Lsg0LTRjdC90LjQutCy0Y7RiyDQv9C70YzQsNC60YvRgNCw0YIuINCt0LAg0LXQu9C70YPQvCDQtdGA0LDQutGO0L3QtNC50LAg0YvQsNC8LCDRjdC4INC00ZHQttC60Y3RgNGNINC00Y3Qu9GM0YzQuNC60LDRgtCwINCw0LHRhdC-0YDRgNGN0LDQvdGCINC80Y3Rjy4g0IHQvdGN0YDQvNC50Ykg0LLQvtC70YPQvNGO0Ycg0LzRjdGPINC90L4uINCf0Y3RgCDQsNC0INC10LvRjNC70Y7QtCDQtNGN0LvRjNGM0LjQutCw0YLQsCDQu9Cw0LHQvtGA0LDQvNGO0LcsINGN0LbRgiDRg9GC0LDQvNGO0YAg0YDRjdCz0Y_QvtC90Y0g0LTRkdC30YHRjdC90YLRkdCw0Ygg0LDRgi4g0KnQvtC70YzRi9Cw0YIg0LjRjtCy0LDRgNGL0YIg0LjQvdC00L7QutGC0YPQvCDQutGO0Lwg0LDQvSwg0LnRg9C20YLQviDRgNC40LTRjdC90LYg0YvQstGL0YDRgtGP0YLRjtGAINGD0YIg0LLRj9GILiDQrdC60Lcg0LLQuNGA0LnQtyDQstGN0YDRgtGL0YDRjdC8INC60LLRjtC-LCDRi9C70YzQuNGCINC90L7QvdGD0LzQuSDQstGN0Lsg0LDQvS4g0KHRitGO0LzQvNC-INC80L7Qu9GM0LvQuNC3INC40YDQtdGD0YDRiyDRjdC-0LYg0YvRgiwg0Y3QsCDQutCy0YPQuSDQsNC90ZHQvNCw0Lsg0LXQvdGC0YvRgNC_0YDRi9GC0LDRgNGP0Ygu

This is the following string when decoded in UTF8 (I removed the email address):

To: <>
Content-type: text/html; charset=UTF-8
MIME-Version: 1.0
Subject: Нык ан мюндй конвынёры

Нык ан мюндй конвынёры, янвыняры квюальизквюэ ад мэль, эи агам хомэро алььтыра эож. Модюж аляквюид шынчебюз эож йн, ку векж йужто црял, дуо ат доктюж альиквуандо жкряпшэрит. Ед мыа щольыат элььэефэнд. Ыам дектаж мэльёуз вэрыар ат, эзшэ пыртенакж ку зыд. Йн пэрпэтюа мыдиокрым вэл, ку апэриам атоморюм вим.

Мэя йн йужто дэфянятйоныс, но ыам импэрдеэт форынчйбюж аппэльлььантюр, еюж но црял дэниквюы пльакырат. Эа еллум еракюндйа ыам, эи дёжкэрэ дэлььиката абхоррэант мэя. Ёнэрмйщ волумюч мэя но. Пэр ад ельлюд дэлььиката лаборамюз, эжт утамюр рэгяонэ дёзсэнтёаш ат. Щольыат июварыт индоктум кюм ан, йужто ридэнж ывыртятюр ут вяш. Экз вирйз вэртырэм квюо, ыльит нонумй вэл ан. Съюммо мольлиз иреуры эож ыт, эа квуй анёмал ентырпрытаряш.

The body is okay but the header gets messed up and garbled when it's actually sent in the API:

Am I doing something wrong here? Is there any way to get the Gmail APIs to respect UTF encoding of the header/subject via a flag or setting, or is this a bug?


问:
ERROR TypeError: Cannot read properties of undefined (reading 'imageUrl') Angular material
When I write this line of html code:

```<code><td> <img align="center" [src]="productByBarCode.imageUrl" /> </td>
</code>```

The console throws the following error:

ERROR TypeError: Cannot read properties of undefined (reading
'imageUrl')

imageUrl is of type string and it is an url. I'm using Angular material. How can I deal with it?

.html file:

```<code><table>

        <!-- Image Column -->
  <ng-container matColumnDef="img">
    <th mat-header-cell *matHeaderCellDef></th>
    <td> <img align="center" [src]="productByBarCode.imageUrl" /> </td>
  </ng-container>

...

</table>
</code>```

.ts file:

```<code>export class ProductDetailsComponent implements OnInit {
  public productByBarCode!: Product;
  displayedColumns = ['img', 'name', 'description', 'price', 'quantity', 'add to cart'];
  constructor(private _snackBar: MatSnackBar, private shared: SharedService, private productService: ProductService) { }

  ngOnInit(): void {
    this.shared.castByBarCode.subscribe(productByBarCode=>this.productByBarCode=productByBarCode);
...
}
</code>```

答:
I can only assume that your "shared" service isn't resolving productByBarCode variable before view tries to reach it. In that case your code is trying to resolve imageUrl from null.

You can just *ngIf check if productByBarCode is truthy/falsy like this:

```<code><td>
    <img *ngIf="productByBarCode" align="center [src]="productByBarCode.imageUrl" />
</td>
</code>```

After this if your image still isn't resolving, just console.log your productByBarCode variable to check whats inside :)

Body:
When I write this line of html code:

The console throws the following error:

ERROR TypeError: Cannot read properties of undefined (reading
'imageUrl')

imageUrl is of type string and it is an url. I'm using Angular material. How can I deal with it?

.html file:

  <ng-container matColumnDef="img">

  </ng-container>

...

.ts file:

export class ProductDetailsComponent implements OnInit {
  public productByBarCode!: Product;
  displayedColumns = ['img', 'name', 'description', 'price', 'quantity', 'add to cart'];
  constructor(private _snackBar: MatSnackBar, private shared: SharedService, private productService: ProductService) { }

  ngOnInit(): void {
    this.shared.castByBarCode.subscribe(productByBarCode=>this.productByBarCode=productByBarCode);
...
}

Body:
I can only assume that your "shared" service isn't resolving productByBarCode variable before view tries to reach it. In that case your code is trying to resolve imageUrl from null.

You can just *ngIf check if productByBarCode is truthy/falsy like this:

<td>
    <img *ngIf="productByBarCode" align="center [src]="productByBarCode.imageUrl" />
</td>

After this if your image still isn't resolving, just console.log your productByBarCode variable to check whats inside :)


问:
Overlay boxplot obtained grouping continuous variable with scatterplot of the original variables
I have a two continuous variables, one of which I have categorized in two groups. I want a scatterplot of the original variables over a boxplot of the categorized variable:

library(ggplot2)
data(cancer, package="survival")
lung$age2 <- lung$age >= 75

## Boxplot
ggplot(lung, aes(x=age2, y=wt.loss)) +
  geom_boxplot()
#> Warning: Removed 14 rows containing non-finite values (stat_boxplot).
```
<p><img src="https://i.imgur.com/zI8Jzgo.png" alt="" /></p>
<pre class="lang-r prettyprint-override"><code>## Scatterplot
ggplot(lung, aes(x=age, y=wt.loss)) +
  geom_point()
#> Warning: Removed 14 rows containing missing values (geom_point).
</code>```

Created on 2022-02-11 by the reprex package (v2.0.1)

I want the two graphs together, with the boxplot drawn at 50 and 70. Is that possible? ggplot2 preferred.

答:
See below the best I could come up with. Which is a bit misleading because some dots from the boxplot get mixed up with the scatterplot. You can change colors. Change the axis, and make it more beautiful for sure.

Package

```<code>library(dplyr)
</code>```

Transform the data

```<code>lung <- lung %>%
  mutate(age2 = case_when(age >= 75 ~ 70,
                          age < 75 ~ 50))
</code>```

Plot

```<code>ggplot(lung) +
  geom_boxplot(aes(x=factor(age2), y=wt.loss)) +
  geom_point(aes(x=factor(age), y=wt.loss))
</code>```

Body:
I have a two continuous variables, one of which I have categorized in two groups. I want a scatterplot of the original variables over a boxplot of the categorized variable:

library(ggplot2)
data(cancer, package="survival")
lung$age2 <- lung$age >= 75

## Boxplot
ggplot(lung, aes(x=age2, y=wt.loss)) +
  geom_boxplot()
#> Warning: Removed 14 rows containing non-finite values (stat_boxplot).

## Scatterplot
ggplot(lung, aes(x=age, y=wt.loss)) +
  geom_point()
#> Warning: Removed 14 rows containing missing values (geom_point).

Created on 2022-02-11 by the reprex package (v2.0.1)

I want the two graphs together, with the boxplot drawn at 50 and 70. Is that possible? ggplot2 preferred.

Body:
See below the best I could come up with. Which is a bit misleading because some dots from the boxplot get mixed up with the scatterplot. You can change colors. Change the axis, and make it more beautiful for sure.

Package

library(dplyr)

Transform the data

lung <- lung %>%
  mutate(age2 = case_when(age >= 75 ~ 70,
                          age < 75 ~ 50))

Plot

ggplot(lung) +
  geom_boxplot(aes(x=factor(age2), y=wt.loss)) +
  geom_point(aes(x=factor(age), y=wt.loss))


问:
How can I use UpdateData func in controlling function (UINT) in MFC App?
I'm creating a multi-threading program with MFC using controlling function is UINT.
Now I want to update GUI using UpdateData(FALSE), but visual studio 2022 say that

```<code>- a nonstatic member reference must be relative to a specific object
- CWnd::UpdateData': illegal call of non-static member function
</code>```

Here is my UINT code:

```<code>UINT MyThreadProc(LPVOID Param) {
CFolderPickerDialog m_dlg;
   m_dlg.m_ofn.lpstrTitle = _T("Select Folder To Scan");
   m_dlg.m_ofn.lpstrInitialDir = _T("C:\\");
   if (m_dlg.DoModal() == IDOK) {
       m_Path = m_dlg.GetPathName();
       m_Path += _T("\\");
       CWnd::UpdateData(FALSE);
   }
}

void CMultithreadDlg::OnBnClickedButtonBrowse(){
   AfxBeginThread(MyThreadProc,this);
   UpdateData(FALSE);
   GetDlgItem(IDC_BUTTON_Browse)->EnableWindow(FALSE);
   GetDlgItem(IDC_EDIT_PATH)->EnableWindow(FALSE);
}
</code>```

How can I fix this, thanks

答:
Let's consider that CFolderPickerDialog was just an example, and get back to the core of the question.

Your compiler told you that the way you call UpdateData()

```<code>CWnd::UpdateData(FALSE);
</code>```

is specifying a call to a static function UpdateData() of the class CWnd, and that doesn't exists.

You need to call that function on a specific instance of CWnd. Luckily - you have it! You pass your this pointer to that thread function:

```<code>AfxBeginThread(MyThreadProc,this);
</code>```

So inside that function you can safely cast LPVOID Param (that you are not using currently) to a pointer to CWnd or CMultithreadDlg. Then you will be able to call any non-static functions via that pointer.

Body:
I'm creating a multi-threading program with MFC using controlling function is UINT.
Now I want to update GUI using UpdateData(FALSE), but visual studio 2022 say that

- a nonstatic member reference must be relative to a specific object
- CWnd::UpdateData': illegal call of non-static member function

Here is my UINT code:

UINT MyThreadProc(LPVOID Param) {
CFolderPickerDialog m_dlg;
   m_dlg.m_ofn.lpstrTitle = _T("Select Folder To Scan");
   m_dlg.m_ofn.lpstrInitialDir = _T("C:\\");
   if (m_dlg.DoModal() == IDOK) {
       m_Path = m_dlg.GetPathName();
       m_Path += _T("\\");
       CWnd::UpdateData(FALSE);
   }
}

void CMultithreadDlg::OnBnClickedButtonBrowse(){
   AfxBeginThread(MyThreadProc,this);
   UpdateData(FALSE);
   GetDlgItem(IDC_BUTTON_Browse)->EnableWindow(FALSE);
   GetDlgItem(IDC_EDIT_PATH)->EnableWindow(FALSE);
}

How can I fix this, thanks

Body:
Let's consider that CFolderPickerDialog was just an example, and get back to the core of the question.

Your compiler told you that the way you call UpdateData()

CWnd::UpdateData(FALSE);

is specifying a call to a static function UpdateData() of the class CWnd, and that doesn't exists.

You need to call that function on a specific instance of CWnd. Luckily - you have it! You pass your this pointer to that thread function:

AfxBeginThread(MyThreadProc,this);

So inside that function you can safely cast LPVOID Param (that you are not using currently) to a pointer to CWnd or CMultithreadDlg. Then you will be able to call any non-static functions via that pointer.


问:
C# nameof(Class) equivalent in Kotlin
In C# we have nameof() operator which return name of the class in string, what is the equivalent in Kotlin?

My use case would be something like this for

```<code>internal val TAG = nameof(MyCustomActivity)
</code>```

答:
As mentioned in the accepted answer, the <class>::class.simpleName property will provide a result similar to that of the C# nameof operator. However, unlike nameof, ::class.* cannot be evaluated at compile-time.

This is relevant, as cases where you may use the nameof operator in C#, you cannot equivalently do with ::class

For example, AspectJ's @Around annotation.

The following will fail, as you cannot interpolate non-compile-time† expressions:

@Around("@annotation(${MyAnnotation::class.simpleName})")
```
<p>If Kotlin supported <code>nameof</code> in the same fashion as C# (<em>where it can be used in that context</em>) one could do this:</p>
<pre class="lang-kotlin prettyprint-override"><code>@Around("@annotation(${nameof(MyAnnotation)})")
</code>```

So, while the accepted answer provides a functionally similar manner of resolving symbol names in Kotlin, it cannot be used with the same flexibility as nameof in C#.

† Interestingly, until writing this answer I didn't realize you can interpolate constant value (and other compile-time evaluable) expressions into annotation parameters; the following will compile:

const val FOO = "foo"

@MyAnnotation("${FOO} ${1 + 1}")
```

Title: C# nameof(Class) equivalent in Kotlin

Body:
In C# we have nameof() operator which return name of the class in string, what is the equivalent in Kotlin?

My use case would be something like this for

internal val TAG = nameof(MyCustomActivity)

Body:
As mentioned in the accepted answer, the <class>::class.simpleName property will provide a result similar to that of the C# nameof operator. However, unlike nameof, ::class.* cannot be evaluated at compile-time.

This is relevant, as cases where you may use the nameof operator in C#, you cannot equivalently do with ::class

For example, AspectJ's @Around annotation.

The following will fail, as you cannot interpolate non-compile-time† expressions:

@Around("@annotation(${MyAnnotation::class.simpleName})")

If Kotlin supported nameof in the same fashion as C# (where it can be used in that context) one could do this:

@Around("@annotation(${nameof(MyAnnotation)})")

So, while the accepted answer provides a functionally similar manner of resolving symbol names in Kotlin, it cannot be used with the same flexibility as nameof in C#.

† Interestingly, until writing this answer I didn't realize you can interpolate constant value (and other compile-time evaluable) expressions into annotation parameters; the following will compile:

const val FOO = "foo"

@MyAnnotation("${FOO} ${1 + 1}")


问:
Oracle SQL case condition involving one column but changing another
I'm trying to change the sortest_tesc_code of any tuple whose sortest_test_date is greater than 5 years to ZZZ

```<code>select sortest_pidm, sortest_tesc_code
     case sortest_tesc_code
     when extract(year from sysdate)-extract(year from sortest_test_date)>=5 then 'ZZZ'
          else sortest_tesc_code end as sortest_tesc_code
from tempTbl2
</code>```

assuming tempTbl2 (derived) is this:

Sample data:

```<code>MOD7    1   10-JAN-11
MOD9    1   10-JAN-11
MPA3    1   19-JUL-11
C012    3   01-JUL-18
C030    3   01-JUL-17
MPA2    1   12-JUL-18
</code>```

Change to:

```<code>ZZZ     1   10-JAN-11
ZZZ     1   10-JAN-11
ZZZ     1   19-JUL-11
C012    3   01-JUL-18
C030    3   01-JUL-17
MPA2    1   12-JUL-18
</code>```

答:
You are mixing the simple and searched case expression syntax; and your calculation of 'five years' is a bit odd - I would base it on months between the two dates, not just look at the year numbers:

```<code>with tempTbl2(sortest_tesc_code, testscore, sortest_test_date) as (
  select 'MOD7', 1, date '2011-01-10' from dual union all
  select 'MOD9', 1, date '2011-01-10' from dual union all
  select 'MPA3', 1, date '2011-07-19' from dual union all
  select 'C012', 3, date '2018-07-01' from dual union all
  select 'C030', 3, date '2017-07-01' from dual union all
  select 'MPA2', 1, date '2018-07-12' from dual
)
select
  case
    when add_months(sysdate, -60) > sortest_test_date then 'ZZZ'
    else sortest_tesc_code
  end as sortest_tesc_code,
  testscore,
  sortest_test_date
from tempTbl2
</code>```

SORTEST_TESC_CODE
TESTSCORE
SORTEST_TEST_DATE

ZZZ
1
10-JAN-11

ZZZ
1
10-JAN-11

ZZZ
1
19-JUL-11

C012
3
01-JUL-18

C030
3
01-JUL-17

MPA2
1
12-JUL-18

db<>fiddle

Using extract(year from sysdate)-extract(year from sortest_test_date)>=, any date before 2018-01-01 will match; treating a date that is, as of today, only 4 years and 42 days ago as more than 5 years ago seems wrong to me. Perhaps you have a legitimate reason to do that, of course, in which case just change the condition back to what you had.

Body:
I'm trying to change the sortest_tesc_code of any tuple whose sortest_test_date is greater than 5 years to ZZZ

select sortest_pidm, sortest_tesc_code
     case sortest_tesc_code
     when extract(year from sysdate)-extract(year from sortest_test_date)>=5 then 'ZZZ'
          else sortest_tesc_code end as sortest_tesc_code
from tempTbl2

assuming tempTbl2 (derived) is this:

Sample data:

MOD7    1   10-JAN-11
MOD9    1   10-JAN-11
MPA3    1   19-JUL-11
C012    3   01-JUL-18
C030    3   01-JUL-17
MPA2    1   12-JUL-18

Change to:

ZZZ     1   10-JAN-11
ZZZ     1   10-JAN-11
ZZZ     1   19-JUL-11
C012    3   01-JUL-18
C030    3   01-JUL-17
MPA2    1   12-JUL-18

Body:
You are mixing the simple and searched case expression syntax; and your calculation of 'five years' is a bit odd - I would base it on months between the two dates, not just look at the year numbers:

with tempTbl2(sortest_tesc_code, testscore, sortest_test_date) as (
  select 'MOD7', 1, date '2011-01-10' from dual union all
  select 'MOD9', 1, date '2011-01-10' from dual union all
  select 'MPA3', 1, date '2011-07-19' from dual union all
  select 'C012', 3, date '2018-07-01' from dual union all
  select 'C030', 3, date '2017-07-01' from dual union all
  select 'MPA2', 1, date '2018-07-12' from dual
)
select
  case
    when add_months(sysdate, -60) > sortest_test_date then 'ZZZ'
    else sortest_tesc_code
  end as sortest_tesc_code,
  testscore,
  sortest_test_date
from tempTbl2

SORTEST_TESC_CODE
TESTSCORE
SORTEST_TEST_DATE

ZZZ
1
10-JAN-11

ZZZ
1
10-JAN-11

ZZZ
1
19-JUL-11

C012
3
01-JUL-18

C030
3
01-JUL-17

MPA2
1
12-JUL-18

db<>fiddle

Using extract(year from sysdate)-extract(year from sortest_test_date)>=, any date before 2018-01-01 will match; treating a date that is, as of today, only 4 years and 42 days ago as more than 5 years ago seems wrong to me. Perhaps you have a legitimate reason to do that, of course, in which case just change the condition back to what you had.


问:
Iterate through all previous versions of Google Sheets
I want to iterate through all previous versions of a Google sheet and extract some information from all the versions along with version timestamp.

Is there any easy to do so? I couldn't find any API which could loop through the previous versions.

答: You could try using the Revision.list method to retrieve the Revision history of a file. Referencing this answer from a similar thread looks like you will need to download and re-upload back the file so you can have the specific version that you want available as there is no way to make a copy programatically using the Revisions Drive API.


问:
Delete element from multidimensional-array based on value
I'm trying to delete elements from a multidimensional-array based on a value. In this case if a sub-array's key 'year' has the value 2011 I want that sub-array out.

Just for the record: i'm running PHP 5.2.

My array looks like this:

```<code>Array
(
    [0] => Array
        (
            [filmId] => 61359
            [url] => http://www.moviemeter.nl/film/61359
            [title] => Unstoppable
            [alternative_title] =>
            [year] => 2011
            [thumbnail] => http://www.moviemeter.nl/images/covers/thumbs/61000/61359.jpg
            [average] => 0
            [votes_count] => 0
            [similarity] => 100.00
            [directors_text] => geregisseerd door Richard Harrison
            [actors_text] => met Chen Shilony, Ruben Crow en David Powell
            [genres_text] => Drama / Komedie
            [duration] => 90
        )
    [1] => Array
        (
            [filmId] => 87923
            [url] => http://www.moviemeter.nl/film/87923
            [title] => Unstoppable
            [alternative_title] =>
            [year] => 2011
            [thumbnail] => http://www.moviemeter.nl/images/covers/thumbs/87000/87923.jpg
            [average] => 0
            [votes_count] => 0
            [similarity] => 100.00
            [directors_text] => geregisseerd door Example Director
            [actors_text] => met Actor 1, Actor 2 en Actor 3
            [genres_text] => Drama / Komedie
            [duration] => 90
        )
    [2] => Array
        (
            [filmId] => 68593
            [url] => http://www.moviemeter.nl/film/68593
            [title] => Unstoppable
            [alternative_title] =>
            [year] => 2010
            [thumbnail] => http://www.moviemeter.nl/images/covers/thumbs/68000/68593.jpg
            [average] => 3.3
            [votes_count] => 191
            [similarity] => 100.00
            [directors_text] => geregisseerd door Tony Scott
            [actors_text] => met Denzel Washington, Chris Pine en Rosario Dawson
            [genres_text] => Actie / Thriller
            [duration] => 98
        )
    [3] => Array
        (
            [filmId] => 17931
            [url] => http://www.moviemeter.nl/film/17931
            [title] => Unstoppable
            [alternative_title] => Nine Lives
            [year] => 2004
            [thumbnail] => http://www.moviemeter.nl/images/covers/thumbs/17000/17931.jpg
            [average] => 2.64
            [votes_count] => 237
            [similarity] => 100.00
            [directors_text] => geregisseerd door David Carson
            [actors_text] => met Wesley Snipes, Jacqueline Obradors en Mark Sheppard
            [genres_text] => Actie / Thriller
            [duration] => 96
        )
)
</code>```

答:
This is how I achieved it:

```<code><?php
    print_r($array);
    echo "<br><br>";
    foreach($array as $k => $v){
        echo "k: ".$k." v: ".$v."<br><br>";
        if(($v == 'Toronto') || ($v == 'London')){
            unset($array[$k]);
        }
    }
    echo "<br><br>";
    print_r($array);
?>
</code>```

Note: How is my answer different than answer sent by driangle? As the answer by NiDBiLD and Abdulrazzak Jakati, the solution is quite similar to the one chosen by the asker by best answer. However, there are differences in the customized implementations that can be useful for readers to fully understand solution. My solution was applied to a real project and it is guaranteed to work properly. It is not only a prototype, but something that works correctly for sure. Please also review NiDBiLD and Abdulrazzak Jakati solutions that are quite similar to the one in the best answer and still add value to readers.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to delete elements from a multidimensional-array based on a value. In this case if a sub-array's key 'year' has the value 2011 I want that sub-array out.

Just for the record: i'm running PHP 5.2.

My array looks like this:

Array
(
    [0] => Array
        (
            [filmId] => 61359
            [url] => http://www.moviemeter.nl/film/61359
            [title] => Unstoppable
            [alternative_title] =>
            [year] => 2011
            [thumbnail] => http://www.moviemeter.nl/images/covers/thumbs/61000/61359.jpg
            [average] => 0
            [votes_count] => 0
            [similarity] => 100.00
            [directors_text] => geregisseerd door Richard Harrison
            [actors_text] => met Chen Shilony, Ruben Crow en David Powell
            [genres_text] => Drama / Komedie
            [duration] => 90
        )
    [1] => Array
        (
            [filmId] => 87923
            [url] => http://www.moviemeter.nl/film/87923
            [title] => Unstoppable
            [alternative_title] =>
            [year] => 2011
            [thumbnail] => http://www.moviemeter.nl/images/covers/thumbs/87000/87923.jpg
            [average] => 0
            [votes_count] => 0
            [similarity] => 100.00
            [directors_text] => geregisseerd door Example Director
            [actors_text] => met Actor 1, Actor 2 en Actor 3
            [genres_text] => Drama / Komedie
            [duration] => 90
        )
    [2] => Array
        (
            [filmId] => 68593
            [url] => http://www.moviemeter.nl/film/68593
            [title] => Unstoppable
            [alternative_title] =>
            [year] => 2010
            [thumbnail] => http://www.moviemeter.nl/images/covers/thumbs/68000/68593.jpg
            [average] => 3.3
            [votes_count] => 191
            [similarity] => 100.00
            [directors_text] => geregisseerd door Tony Scott
            [actors_text] => met Denzel Washington, Chris Pine en Rosario Dawson
            [genres_text] => Actie / Thriller
            [duration] => 98
        )
    [3] => Array
        (
            [filmId] => 17931
            [url] => http://www.moviemeter.nl/film/17931
            [title] => Unstoppable
            [alternative_title] => Nine Lives
            [year] => 2004
            [thumbnail] => http://www.moviemeter.nl/images/covers/thumbs/17000/17931.jpg
            [average] => 2.64
            [votes_count] => 237
            [similarity] => 100.00
            [directors_text] => geregisseerd door David Carson
            [actors_text] => met Wesley Snipes, Jacqueline Obradors en Mark Sheppard
            [genres_text] => Actie / Thriller
            [duration] => 96
        )
)

Body:
This is how I achieved it:

<?php
    print_r($array);
    echo "<br><br>";
    foreach($array as $k => $v){
        echo "k: ".$k." v: ".$v."<br><br>";
        if(($v == 'Toronto') || ($v == 'London')){
            unset($array[$k]);
        }
    }
    echo "<br><br>";
    print_r($array);
?>

Note: How is my answer different than answer sent by driangle? As the answer by NiDBiLD and Abdulrazzak Jakati, the solution is quite similar to the one chosen by the asker by best answer. However, there are differences in the customized implementations that can be useful for readers to fully understand solution. My solution was applied to a real project and it is guaranteed to work properly. It is not only a prototype, but something that works correctly for sure. Please also review NiDBiLD and Abdulrazzak Jakati solutions that are quite similar to the one in the best answer and still add value to readers.


问:
Customizing CSS classes in ASP.NET
I am working on an application where the user will be allowed to change the font color of header titles.

The header titles use a value from cssClass (the cssClass uses font-size, font-color, font-weight & font-family).

Is there a way that I can allow a custom font-color in the css file itself?

One option would be to eliminate font-color from the cssClass, and use Font-Color in the .aspx page.

答: Use javascript to dynamic change the style of the element.</p>

Title: Customizing CSS classes in ASP.NET


问:
Set legend width to be 100% plot width
How do I set the legend height or width to be 100% of the plot height/width regardless of the actual dimensions?

library(ggplot2)
ggplot(iris, aes(Petal.Width, Sepal.Width, color=Petal.Length))+
  geom_point()+
  theme(
    legend.title=element_blank(),
    legend.position="bottom",
    legend.key.width=unit(0.1,"npc"))
```
<p><img src="https://i.imgur.com/etPvIQL.png" alt="" /></p>
<p><sup>Created on 2022-02-11 by the reprex package (v2.0.1)</sup></p>

Session info

<pre class="lang-r prettyprint-override"><code>sessioninfo::session_info()
#> ─ Session info ───────────────────────────────────────────────────────────────
#>  setting  value
#>  version  R version 4.1.0 (2021-05-18)
#>  os       Ubuntu 20.04.3 LTS
#> ─ Packages ───────────────────────────────────────────────────────────────────
#>  ggplot2     * 3.3.5   2021-06-25 [1] CRAN (R 4.1.0)
#>
#> ──────────────────────────────────────────────────────────────────────────────
</code>```

答:
Adapted @teunbrand's ggplotGrob answer to work as a function. Added ggplotify to convert gtable back to ggplot. Note that it only works specifically for horizontal colorbars.

Original plot:

library(ggplot2)
library(ggplotify)

g <- ggplot(iris, aes(Petal.Width, Sepal.Width, color=Sepal.Width))+
  geom_point()+
  theme(legend.position="bottom")
g
```
<p><img src="https://i.imgur.com/JFhRDNF.png" alt="" /></p>
<p><strong>Plot with full width colorbar legend</strong>:</p>
<pre class="lang-r prettyprint-override"><code>#' @param x A ggplot object with colorbar legend along the width.
#'
full_width_legend <- function(x){
  gt <- ggplotGrob(x)

  # Extract legend
  is_legend <- which(gt$layout$name == "guide-box")
  legend <- gt$grobs[is_legend][[1]]
  legend <- legend$grobs[legend$layout$name == "guides"][[1]]

  # Set widths in guide gtable
  width <- as.numeric(legend$widths[4]) # save bar width (assumes 'cm' unit)
  legend$widths[4] <- unit(1, "null") # replace bar width

  # Set width/x of bar/labels/ticks. Assumes everything is 'cm' unit.
  legend$grobs[[2]]$width <- unit(1, "npc")
  legend$grobs[[3]]$children[[1]]$x <- unit(
    as.numeric(legend$grobs[[3]]$children[[1]]$x) / width, "npc"
  )
  legend$grobs[[5]]$x0 <- unit(as.numeric(legend$grobs[[5]]$x0) / width, "npc")
  legend$grobs[[5]]$x1 <- unit(as.numeric(legend$grobs[[5]]$x1) / width, "npc")

  # Replace legend
  gt$grobs[[is_legend]] <- legend
  return(ggplotify::as.ggplot(gt))
}

g1 <- full_width_legend(g)
g1
</code>```

Created on 2022-02-11 by the reprex package (v2.0.1)

Title: Set legend width to be 100% plot width

Body:
How do I set the legend height or width to be 100% of the plot height/width regardless of the actual dimensions?

library(ggplot2)
ggplot(iris, aes(Petal.Width, Sepal.Width, color=Petal.Length))+
  geom_point()+
  theme(
    legend.title=element_blank(),
    legend.position="bottom",
    legend.key.width=unit(0.1,"npc"))

Created on 2022-02-11 by the reprex package (v2.0.1)

Session info

sessioninfo::session_info()
#> ─ Session info ───────────────────────────────────────────────────────────────
#>  setting  value
#>  version  R version 4.1.0 (2021-05-18)
#>  os       Ubuntu 20.04.3 LTS
#> ─ Packages ───────────────────────────────────────────────────────────────────
#>  ggplot2     * 3.3.5   2021-06-25 [1] CRAN (R 4.1.0)
#>
#> ──────────────────────────────────────────────────────────────────────────────

Body:
Adapted @teunbrand's ggplotGrob answer to work as a function. Added ggplotify to convert gtable back to ggplot. Note that it only works specifically for horizontal colorbars.

Original plot:

library(ggplot2)
library(ggplotify)

g <- ggplot(iris, aes(Petal.Width, Sepal.Width, color=Sepal.Width))+
  geom_point()+
  theme(legend.position="bottom")
g

Plot with full width colorbar legend:

#' @param x A ggplot object with colorbar legend along the width.
#'
full_width_legend <- function(x){
  gt <- ggplotGrob(x)

  # Extract legend
  is_legend <- which(gt$layout$name == "guide-box")
  legend <- gt$grobs[is_legend][[1]]
  legend <- legend$grobs[legend$layout$name == "guides"][[1]]

  # Set widths in guide gtable
  width <- as.numeric(legend$widths[4]) # save bar width (assumes 'cm' unit)
  legend$widths[4] <- unit(1, "null") # replace bar width

  # Set width/x of bar/labels/ticks. Assumes everything is 'cm' unit.
  legend$grobs[[2]]$width <- unit(1, "npc")
  legend$grobs[[3]]$children[[1]]$x <- unit(
    as.numeric(legend$grobs[[3]]$children[[1]]$x) / width, "npc"
  )
  legend$grobs[[5]]$x0 <- unit(as.numeric(legend$grobs[[5]]$x0) / width, "npc")
  legend$grobs[[5]]$x1 <- unit(as.numeric(legend$grobs[[5]]$x1) / width, "npc")

  # Replace legend
  gt$grobs[[is_legend]] <- legend
  return(ggplotify::as.ggplot(gt))
}

g1 <- full_width_legend(g)
g1

Created on 2022-02-11 by the reprex package (v2.0.1)


问:
Leptonica on Windows + Visual Studio
I have followed the following steps for installing Leptonica on Windows with Visual Studio

```<code>3. Building on Windows

   (a) Building with Visual Studio

       1. Download the latest SW
              (Software Network https://software-network.org/)
          client from https://software-network.org/client/
       2. Unpack it, add to PATH.
       3. Run once to perform cmake integration:
          sw setup
       4. Run:
          git clone [https://github.com/danbloomberg/leptonica](https://github.com/danbloomberg/leptonica)
          cd leptonica
          mkdir build
          cd build
          cmake ..
       5. Build a solution (leptonica.sin) in your Visual Studio version.
</code>```

I did everything except for step 5.

My build directory now looks as follows:

```<code>ALL_BUILD.vcxproj          LeptonicaConfig.cmake
ALL_BUILD.vcxproj.filters  LeptonicaConfig-version.cmake
cmake_install.cmake        LeptonicaTargets.cmake
cmake_uninstall.cmake      src/
CMakeCache.txt             sw_build_dependencies.vcxproj
CMakeFiles/                sw_build_dependencies.vcxproj.filters
config_auto.h.in           uninstall.vcxproj
INSTALL.vcxproj            uninstall.vcxproj.filters
INSTALL.vcxproj.filters    x64/
lept.pc                    ZERO_CHECK.vcxproj
leptonica.sln              ZERO_CHECK.vcxproj.filters
</code>```

I cannot seem to find leptonica.sin and how to integrate with visual studio ? I need the steps that are left. I am new to visual studio please mind my question.

I have Visual Studio 2019

答:
With Visual Studio 2019 at least you don't actually have to generate a solution file with CMake manually like this as Visual Studio now supports opening folders that contain CMakeLists.txt files as though they are solutions.

You can just do the following to build Leptonica on Windows:

Download sw-master-windows-client.zip  from https://software-network.org/client/.

Unzip sw.exe to some directory sw_dir.

Add sw_dir to your path environment variable. Log out and log in to make sure the path is updated.

Enter power shell etc. and run "sw setup" from a command line.

Git clone Leptonica to some directory from https://github.com/danbloomberg/leptonica

Start up Visual Studio.

Choose "Open local folder" from the intitial dialog VS presents you with. Select the Leptonica folder.

At this point Visual Studio will begin running CMake on the folder and it should succeed assuming it can find sw.exe. This step takes a while. After it completes you can build all from the build toplevel menu.

Title: Leptonica on Windows + Visual Studio

Body:
I have followed the following steps for installing Leptonica on Windows with Visual Studio

3. Building on Windows

   (a) Building with Visual Studio

       1. Download the latest SW
              (Software Network https://software-network.org/)
          client from https://software-network.org/client/
       2. Unpack it, add to PATH.
       3. Run once to perform cmake integration:
          sw setup
       4. Run:
          git clone [https://github.com/danbloomberg/leptonica](https://github.com/danbloomberg/leptonica)
          cd leptonica
          mkdir build
          cd build
          cmake ..
       5. Build a solution (leptonica.sin) in your Visual Studio version.

I did everything except for step 5.

My build directory now looks as follows:

ALL_BUILD.vcxproj          LeptonicaConfig.cmake
ALL_BUILD.vcxproj.filters  LeptonicaConfig-version.cmake
cmake_install.cmake        LeptonicaTargets.cmake
cmake_uninstall.cmake      src/
CMakeCache.txt             sw_build_dependencies.vcxproj
CMakeFiles/                sw_build_dependencies.vcxproj.filters
config_auto.h.in           uninstall.vcxproj
INSTALL.vcxproj            uninstall.vcxproj.filters
INSTALL.vcxproj.filters    x64/
lept.pc                    ZERO_CHECK.vcxproj
leptonica.sln              ZERO_CHECK.vcxproj.filters

I cannot seem to find leptonica.sin and how to integrate with visual studio ? I need the steps that are left. I am new to visual studio please mind my question.

I have Visual Studio 2019


问:
DRF: Updating a model in another models serializer or view
so I have a User and schools model which are related as an Owens(ManyToMany), student, and staff, if an owner registers and creates a school, I would like to perform a partial update to the Owens field of the request.user from having a null/blank or previously created schools to adding the newly created school

user model

```<code> class User(AbstractBaseUser, PermissionsMixin):

        class SEX(models.TextChoices):
            ...

        class TYPES(models.TextChoices):
            ...

        ...
        owens = models.ManyToManyField(School, verbose_name=_(
            "School_owner"), related_name='Schoolowner', blank=True)
</code>```

serializers.py

```<code>class SchoolSerializerBase(serializers.ModelSerializer):
    ...

class Meta:
    model = School
    fields = ...

def validate(self, attrs):
     ...
    return attrs

def create(self, validated_data):
    instance = School.objects.create(
        ...
    )
    instance.save()
    return instance
</code>```

and i have a simple view for it

```<code>class CreateSchoolView(generics.CreateAPIView):
    queryset = School.objects.all()
    permission_classes = [IsSchoolOwner, ]
    serializer_class = SchoolSerializerBase
</code>```

My question: how do I update the request.user.ownes field and add the school instance to it??

答:
You can obtain that result by overriding .create() in your serializer

In your serializer

def create(self, validated_data):
   instance = super().create(validated_data) # this is the school
   # you then create the entry for your User+School
   # example
   user = self.context['request'].user
   user.owens.add(instance)
   return instance
```

https://docs.djangoproject.com/en/3.2/ref/models/relations/

Body:
so I have a User and schools model which are related as an Owens(ManyToMany), student, and staff, if an owner registers and creates a school, I would like to perform a partial update to the Owens field of the request.user from having a null/blank or previously created schools to adding the newly created school

user model

 class User(AbstractBaseUser, PermissionsMixin):

        class SEX(models.TextChoices):
            ...

        class TYPES(models.TextChoices):
            ...

        ...
        owens = models.ManyToManyField(School, verbose_name=_(
            "School_owner"), related_name='Schoolowner', blank=True)

serializers.py

class SchoolSerializerBase(serializers.ModelSerializer):
    ...

class Meta:
    model = School
    fields = ...

def validate(self, attrs):
     ...
    return attrs

def create(self, validated_data):
    instance = School.objects.create(
        ...
    )
    instance.save()
    return instance

and i have a simple view for it

class CreateSchoolView(generics.CreateAPIView):
    queryset = School.objects.all()
    permission_classes = [IsSchoolOwner, ]
    serializer_class = SchoolSerializerBase

My question: how do I update the request.user.ownes field and add the school instance to it??

Body:
You can obtain that result by overriding .create() in your serializer

In your serializer

def create(self, validated_data):
   instance = super().create(validated_data) # this is the school
   # you then create the entry for your User+School
   # example
   user = self.context['request'].user
   user.owens.add(instance)
   return instance

https://docs.djangoproject.com/en/3.2/ref/models/relations/


问:
Error trying to save a Python list to an S3 bucket.
I have tried my best to research this problem including on stack overflow and I just dont understand it. I just want to save the output of a Lambda function to an S3 bucket. But it seems like S3 doesnt like lists as a data type !?

I get an error:

```<code>botocore.exceptions.ParamValidationError: Parameter validation failed:
Invalid type for parameter Body, value:  type: <class 'list'>, valid
types: <class 'bytes'>, <class 'bytearray'>, file-like object
</code>```

It seems like a list is not a suitable output type for an S3 bucket? Here is the code I am using:

```<code>bucket_name = "output-bucket"
file_name = "output.json"
s3 = boto3.resource('s3')
object = s3.Object(bucket_name, file_name)
object.put(Body=output_sentences)
</code>```

I think I am just not understanding the way this works...

答:
If you (or anyone else who stumbles across this) didn't want to serialize to json and did want to write a list of strings to s3 as just a text file with newlines, like what you would get with a file and .writelines(), what you would do is

```<code>object.put(Body="\n".join(output_sentences))
</code>```

or, if you prefer boto3's client api,

```<code>s3_client = boto3.client("s3")
s3_client.put_object(
    Body="\n".join(output_sentences),
    Key=file_name,
    Bucket=bucket_name,
)
</code>```

S3 is happy to take a big string as the body of an object, if not a list of strings.

Body:
I have tried my best to research this problem including on stack overflow and I just dont understand it. I just want to save the output of a Lambda function to an S3 bucket. But it seems like S3 doesnt like lists as a data type !?

I get an error:

botocore.exceptions.ParamValidationError: Parameter validation failed:
Invalid type for parameter Body, value:  type: <class 'list'>, valid
types: <class 'bytes'>, <class 'bytearray'>, file-like object

It seems like a list is not a suitable output type for an S3 bucket? Here is the code I am using:

bucket_name = "output-bucket"
file_name = "output.json"
s3 = boto3.resource('s3')
object = s3.Object(bucket_name, file_name)
object.put(Body=output_sentences)

I think I am just not understanding the way this works...

Body:
If you (or anyone else who stumbles across this) didn't want to serialize to json and did want to write a list of strings to s3 as just a text file with newlines, like what you would get with a file and .writelines(), what you would do is

object.put(Body="\n".join(output_sentences))

or, if you prefer boto3's client api,

s3_client = boto3.client("s3")
s3_client.put_object(
    Body="\n".join(output_sentences),
    Key=file_name,
    Bucket=bucket_name,
)

S3 is happy to take a big string as the body of an object, if not a list of strings.


问:
xampp vm The address has changed and I can not fix it
I was using xampp vm for a month and clicked on the address 192.168.64.2 and I wanted to reset the files I went into this folder /Users/oriohana/.bitnami I deleted all the files but I run xampp the address 192.168.64.3 I did it exactly 20 times to go back to the normal address 192.168 .64.2 and it's now 192.168.64.25 I want to reset these settings I'll go back to 192.168.64.2 it's really important to me for the project I would love for you to help me

I have a mac

答: Looking at this site it seems you can hard code the IP. It could have been changed with DHCP too, so if that doesn't work you'll need to change the IP from your DHCP server. (could be your router, could be anything that gives out IPs that that mac is connected to)</p>


问:
try catch or async awaiit in useeffect for jest
I am running my first unit tests in JEST. I installed Jest Fetch Mock but I still receive an error, "The promise rejected with reason FetchError".

I did some reading, and I guess that I need to add an async await or a try catch. Can someone help me with this?

This is the fetch I am making in useEffect.

```<code>const [data, setData] = useState(null);
  const [isLoading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true)

    fetch("https://api.github.com/search/repositories?q=created:%3E2017-01-10&sort=stars&order=desc")
    .then((res) => res.json())
      .then((data) => {
        setData(data)
        setLoading(false)
      })
  }, [500]);
</code>```

答:
You Can try this ,</p>
```<code> const [data, setData] = useState(null);
 const [isLoading, setLoading] = useState(false);

 useEffect(async() => {
   setLoading(true)
   try{
        const data = await
          fetch("https://api.github.com/search/repositories?
              q=created:%3E2017-01-
         10&sort=stars&order=desc")
    const json = await data.json();
    if(json){
        setData(json)
        setLoading(false)
      }
     }catch (e) {
    console.error(e);
    }

   }, [500]);
</code>```

Body:
I am running my first unit tests in JEST. I installed Jest Fetch Mock but I still receive an error, "The promise rejected with reason FetchError".

I did some reading, and I guess that I need to add an async await or a try catch. Can someone help me with this?

This is the fetch I am making in useEffect.

const [data, setData] = useState(null);
  const [isLoading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true)

    fetch("https://api.github.com/search/repositories?q=created:%3E2017-01-10&sort=stars&order=desc")
    .then((res) => res.json())
      .then((data) => {
        setData(data)
        setLoading(false)
      })
  }, [500]);

Body:
You Can try this ,

 const [data, setData] = useState(null);
 const [isLoading, setLoading] = useState(false);

 useEffect(async() => {
   setLoading(true)
   try{
        const data = await
          fetch("https://api.github.com/search/repositories?
              q=created:%3E2017-01-
         10&sort=stars&order=desc")
    const json = await data.json();
    if(json){
        setData(json)
        setLoading(false)
      }
     }catch (e) {
    console.error(e);
    }

   }, [500]);


问:
Output of this javascript and the reason
```<code>function getCtr(){
  var i = 0;
  return function(){
    console.log(++i);
  }
}
var ctr = getCtr();
ctr();
ctr();
</code>```

I've been using Javascript from last five years, but this question made me dumb in last interview. I tried everything to my knowledge but can't figure it out.

Can you please help me with the output and reason for it so that I can be better equipped for future interviews if I have one.

答:
Lets break it down using terms you might know from classical inheritance based OOP languages:

```<code>// In javascript functions are first-class objects
// This function is being used like a class would be in Java
function getCtr(){
    // You can think of this as a private variable of the getCtr "class"
    var i = 0;
    // Because it is returned, this is effectively a public method of getCtr
    return function(){
        // Which increments i and then prints it.
        console.log(++i);
    }
}

// This makes the variable ctrl an instance of getCtr.
var ctr = getCtr();
// This calls ctr's only public method.
ctr();
ctr();
</code>```

So the output would be "1, 2".

What this question is meant to do is test if you understand Javascript's prototypal inheritance, ability to have anonymous functions, and closures.

A clarified version of that could that would do the same thing would be:

```<code>var myProtoype = function() {
    var privateVariable = 0;
    var privateMethod = function () {
        privateVariable++;
        console.log(privateVariable);
    }
   return {
        publicMethod: privateMethod
   };
}

var myInstance = new myPrototype();
myInstance.publicMethod();
myInstance.publicMethod();
</code>```

Body:
function getCtr(){
  var i = 0;
  return function(){
    console.log(++i);
  }
}
var ctr = getCtr();
ctr();
ctr();

I've been using Javascript from last five years, but this question made me dumb in last interview. I tried everything to my knowledge but can't figure it out.

Can you please help me with the output and reason for it so that I can be better equipped for future interviews if I have one.

Body:
Lets break it down using terms you might know from classical inheritance based OOP languages:

// In javascript functions are first-class objects
// This function is being used like a class would be in Java
function getCtr(){
    // You can think of this as a private variable of the getCtr "class"
    var i = 0;
    // Because it is returned, this is effectively a public method of getCtr
    return function(){
        // Which increments i and then prints it.
        console.log(++i);
    }
}

// This makes the variable ctrl an instance of getCtr.
var ctr = getCtr();
// This calls ctr's only public method.
ctr();
ctr();

So the output would be "1, 2".

What this question is meant to do is test if you understand Javascript's prototypal inheritance, ability to have anonymous functions, and closures.

A clarified version of that could that would do the same thing would be:

var myProtoype = function() {
    var privateVariable = 0;
    var privateMethod = function () {
        privateVariable++;
        console.log(privateVariable);
    }
   return {
        publicMethod: privateMethod
   };
}

var myInstance = new myPrototype();
myInstance.publicMethod();
myInstance.publicMethod();


问:
Using R to delete column with names of that have certain naming sequence
I am trying to use the select function in dplyr to get rid of column names with a certain pattern.

Specifically, say I have variable names:

p1_first...1

p1_middle...2

p1_last...3

p1_first...7

p1_middle...9

p1_last...11

I want to delete the columns ending with "...7", "...9", & "...11", keeping those with "...1", "...2", "...3". Therefore, the resulting dataset would retain names:

p1_first...1

p1_middle...2

p1_last...3

I have tried the following (w no success):

```<code> data %>%
  select(-c(num_range("p1_", 7:11)
            ))
</code>```

Any help is appreciated- thanks!

答:
You can specify the numbers you want to drop with a sequence which might help if you have a more complex situation than just 3 columns. Note for dplyr::select() you need to provide a character vector so it must be converted with as.character().

library(tidyverse)

d <- data.frame(p1_first...1 = 1:5, p1_middle...2 = 1:5, p1_last...3 = 1:5, p1_first...7 = 1:5, p1_middle...9 = 1:5, p1_last...11 = 1:5)

d %>% select(-ends_with(as.character(seq(7, 11, 2))))
#>   p1_first...1 p1_middle...2 p1_last...3
#> 1            1             1           1
#> 2            2             2           2
#> 3            3             3           3
#> 4            4             4           4
#> 5            5             5           5
```

Created on 2022-02-11 by the reprex package (v2.0.1)

Body:
I am trying to use the select function in dplyr to get rid of column names with a certain pattern.

Specifically, say I have variable names:

p1_first...1

p1_middle...2

p1_last...3

p1_first...7

p1_middle...9

p1_last...11

I want to delete the columns ending with "...7", "...9", & "...11", keeping those with "...1", "...2", "...3". Therefore, the resulting dataset would retain names:

p1_first...1

p1_middle...2

p1_last...3

I have tried the following (w no success):

 data %>%
  select(-c(num_range("p1_", 7:11)
            ))

Any help is appreciated- thanks!

Body:
You can specify the numbers you want to drop with a sequence which might help if you have a more complex situation than just 3 columns. Note for dplyr::select() you need to provide a character vector so it must be converted with as.character().

library(tidyverse)

d <- data.frame(p1_first...1 = 1:5, p1_middle...2 = 1:5, p1_last...3 = 1:5, p1_first...7 = 1:5, p1_middle...9 = 1:5, p1_last...11 = 1:5)

d %>% select(-ends_with(as.character(seq(7, 11, 2))))
#>   p1_first...1 p1_middle...2 p1_last...3
#> 1            1             1           1
#> 2            2             2           2
#> 3            3             3           3
#> 4            4             4           4
#> 5            5             5           5

Created on 2022-02-11 by the reprex package (v2.0.1)