问:
ggplot2 position='dodge' producing bars that are too wide
I'm interested in producing a histogram with position='dodge' and fill=some factor (i.e. side-by-side bars for different subgroups within each bar/group), but ggplot2 gives me something like the first plot here, which has a rightmost bar that's too wide and reserves no space for the empty group, which I would like.

Here's a simple case:

```<code>df = data.frame(a=c('o','x','o','o'), b=c('a','b','a','b'))
qplot(a, data=df, fill=b, position='dodge')
</code>```

From ggplot geom_bar - bars too wide I got this idea, and while it technically produces a bar of the same width, but preserves no space for the empty group:

```<code>ggplot(df, aes(x=a, fill=a))+
geom_bar(aes(y=..count../sum(..count..))) +
facet_grid(~b,scales="free",space="free")
</code>```

How do I achieve what I want? Thanks in advance.

答:
The default options in ggplot produces what I think you describe.  The scales="free" and space="free" options does the opposite of what you want, so simply remove these from the code.  Also, the default stat for geom_bar is to aggregate by counting, so you don't have to specify your stat explicitly.

```<code>ggplot(df, aes(x=a, fill=a)) + geom_bar() + facet_grid(~b)
</code>```

Body:
I'm interested in producing a histogram with position='dodge' and fill=some factor (i.e. side-by-side bars for different subgroups within each bar/group), but ggplot2 gives me something like the first plot here, which has a rightmost bar that's too wide and reserves no space for the empty group, which I would like.

Here's a simple case:

df = data.frame(a=c('o','x','o','o'), b=c('a','b','a','b'))
qplot(a, data=df, fill=b, position='dodge')

From ggplot geom_bar - bars too wide I got this idea, and while it technically produces a bar of the same width, but preserves no space for the empty group:

ggplot(df, aes(x=a, fill=a))+
geom_bar(aes(y=..count../sum(..count..))) +
facet_grid(~b,scales="free",space="free")

How do I achieve what I want? Thanks in advance.

Body:
The default options in ggplot produces what I think you describe.  The scales="free" and space="free" options does the opposite of what you want, so simply remove these from the code.  Also, the default stat for geom_bar is to aggregate by counting, so you don't have to specify your stat explicitly.

ggplot(df, aes(x=a, fill=a)) + geom_bar() + facet_grid(~b)


来源: stackexchange

问:
Where is the 'Tests Output Pane'?

Unexpected error detected. Check the Tests Output Pane for details.

Where is the 'Tests Output Pane'? I can't find it anywhere in Visual Studio. I found 'Test Explorer' but it doesn't show any details.

答:
So for me , I resolved it by just deleting the root folder on this path.

C:\Windows\Microsoft.NET\Frameworks64\v4.0.30319\Temporary ASP.NET Files\root

Just delete this root folder & you should be good to go :)

ContentLicense: CC BY-SA 4.0

Title: Where is the 'Tests Output Pane'?


问:
Longest word in file
My program needs to print longest word which contains only letters from a file.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int checkString(const char s[]) {
  unsigned char c;
  while ((c = *s) && (isalpha(c) || isblank(c)))
    ++s;
  return *s == '\0';
}
int main() {
  char file_name[]="document.txt";
  FILE *fp = fopen(file_name, "r");
  char *largest = str;
  int largest_len = 0;
  while (fgets(file_name, 1000, fp) != NULL) {
    char *temp = strtok(file_name, " ");
    while (temp != NULL) {
      if (strlen(temp) > largest_len) {
        strcpy(largest, temp);
        largest_len = strlen(largest);
      }
      temp = strtok(NULL, "\",.,1,2,4,5,6,7,8,9 ");
    }
  }
  if(checkString(largest))
  printf("%s", largest);
  fclose(fp);
  return 0;
}
</code>```

In my code, if the largest word contains only letters it will be printed. How to modify this code to check next words if the largest doesn't contain only letters?

答:
First of all, you cannot store the pointer to longest word like that. You re-use str for the next line and so the pointer is not likely to point to something useful.

Second, while strtok() appears simple, initially, I tend to apply a straightforward approach to a straightforward problem.
The problem is O(n) (where n is the length of the document). You just need to go through it character by character. Of course, since every line is ended by a \n, you can use the line based approach in this case.

So, instead of strtok, simply check each character, if it is a legal word character (an alphanumeric character, that is). You can easily do so with the standard library function isalpha() from header ctype.h.

Below is the program, copying the longest string into a dedicated buffer, using isalpha() and doing the line based reading of the file, just like the code in the original question did.

Of course, this code assumes, no line is ever longer than 999 characters.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <ctype.h>

static size_t gulp(const char* line, size_t istart, size_t len) {
  size_t n = 0;
  for (size_t i = istart; i < len; i++, n++) {
    if (!isalpha(line[i])) {
      break;
    }
  }
  return n;
}

int main(int argc, const char * argv[]) {
  FILE* f = fopen("document.txt","r");
  char line[1000];
  char longest_word[1000];
  size_t longest_word_length = 0;
  while (fgets(line, sizeof(line), f) != NULL) {
    size_t i0 = 0;
    size_t line_length = strlen(line);
    while (i0 < line_length) {
      if (isalpha(line[i0])) {
        size_t n = gulp(line, i0, line_length);
        if (n > longest_word_length) {
          strncpy(longest_word, &line[i0], n);
          longest_word[n] = '\0';
          longest_word_length = n;
        }
        i0 = i0 + n;
      } else {
        i0++;
      }
    }
  }
  fclose(f);
  f = NULL;
  if (longest_word_length > 0) {
    printf("longest word: %s (%lu characters)\n",
       longest_word, longest_word_length);
  }
  return 0;
}
</code>```

Title: Longest word in file

Body:
My program needs to print longest word which contains only letters from a file.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int checkString(const char s[]) {
  unsigned char c;
  while ((c = *s) && (isalpha(c) || isblank(c)))
    ++s;
  return *s == '\0';
}
int main() {
  char file_name[]="document.txt";
  FILE *fp = fopen(file_name, "r");
  char *largest = str;
  int largest_len = 0;
  while (fgets(file_name, 1000, fp) != NULL) {
    char *temp = strtok(file_name, " ");
    while (temp != NULL) {
      if (strlen(temp) > largest_len) {
        strcpy(largest, temp);
        largest_len = strlen(largest);
      }
      temp = strtok(NULL, "\",.,1,2,4,5,6,7,8,9 ");
    }
  }
  if(checkString(largest))
  printf("%s", largest);
  fclose(fp);
  return 0;
}

In my code, if the largest word contains only letters it will be printed. How to modify this code to check next words if the largest doesn't contain only letters?

Body:
First of all, you cannot store the pointer to longest word like that. You re-use str for the next line and so the pointer is not likely to point to something useful.

Second, while strtok() appears simple, initially, I tend to apply a straightforward approach to a straightforward problem.
The problem is O(n) (where n is the length of the document). You just need to go through it character by character. Of course, since every line is ended by a \n, you can use the line based approach in this case.

So, instead of strtok, simply check each character, if it is a legal word character (an alphanumeric character, that is). You can easily do so with the standard library function isalpha() from header ctype.h.

Below is the program, copying the longest string into a dedicated buffer, using isalpha() and doing the line based reading of the file, just like the code in the original question did.

Of course, this code assumes, no line is ever longer than 999 characters.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <ctype.h>

static size_t gulp(const char* line, size_t istart, size_t len) {
  size_t n = 0;
  for (size_t i = istart; i < len; i++, n++) {
    if (!isalpha(line[i])) {
      break;
    }
  }
  return n;
}

int main(int argc, const char * argv[]) {
  FILE* f = fopen("document.txt","r");
  char line[1000];
  char longest_word[1000];
  size_t longest_word_length = 0;
  while (fgets(line, sizeof(line), f) != NULL) {
    size_t i0 = 0;
    size_t line_length = strlen(line);
    while (i0 < line_length) {
      if (isalpha(line[i0])) {
        size_t n = gulp(line, i0, line_length);
        if (n > longest_word_length) {
          strncpy(longest_word, &line[i0], n);
          longest_word[n] = '\0';
          longest_word_length = n;
        }
        i0 = i0 + n;
      } else {
        i0++;
      }
    }
  }
  fclose(f);
  f = NULL;
  if (longest_word_length > 0) {
    printf("longest word: %s (%lu characters)\n",
       longest_word, longest_word_length);
  }
  return 0;
}


问:
Create Postgres Policy for Row Level Security on foreign key attribute
I'm trying to create a Policy on Postgres to enable Row Level Security but I'm having a bit of trouble. Many examples I've found have a direct FK on the table, but I'm trying to do it on an attribute on the foreign table.

The context here is that I'm trying to have users only be able to see other users from the same organization. The user is set on a configuration parameter organization.current_tenant, which takes on the value of the Organization.key

Setup:

```<code>CREATE TABLE organization (id serial primary key, name text, key text);
CREATE TABLE myuser (id serial primary key, name text, user_organization_id integer);

INSERT INTO organization (name, key) values ('org1', 'org1-key');
INSERT INTO organization (name, key) values ('org2', 'org2-key');

INSERT INTO myuser (name, user_organization_id) values ('org1_agent1', 1);
INSERT INTO myuser (name, user_organization_id) values ('org2_agent1', 2);
INSERT INTO myuser (name, user_organization_id) values ('org2_agent2', 2);

ALTER TABLE myuser ENABLE ROW LEVEL SECURITY;
ALTER TABLE myuser FORCE ROW LEVEL SECURITY;
</code>```

When using a direct FK, organization_id:

```<code>CREATE POLICY access_tenant_data ON myuser
USING (user_organization_id::TEXT = current_setting('organization.current_tenant'));
</code>```

This works since user_organization_id is the foreign key available on the user table.

However, what I want to use is instead something like user.organization.key.

```<code>CREATE POLICY access_tenant_data ON myuser
USING (
    key IN (
        SELECT key FROM
        myuser U INNER JOIN organization O
        ON U.organization_id = O.id
    )::TEXT = current_setting('organization.current_tenant')
);
</code>```

But this obviously doesn't work. I'm not sure how to proceed from here.

Testing it out:

```<code>SET organization.current_tenant = "org1-key";
SELECT * from myuser;

</code>```

答:
That should be fairly simple:

```<code>CREATE POLICY access_tenant_data ON myuser
USING (
   EXISTS (SELECT 1 FROM organization AS o
           WHERE myuser.user_organization_id = o.id
             AND o.key = current_setting('organization.current_tenant')
          )
);
</code>```

That can be fairly efficient, since PostgreSQL can compute the resulting query using a semi-join.

Body:
I'm trying to create a Policy on Postgres to enable Row Level Security but I'm having a bit of trouble. Many examples I've found have a direct FK on the table, but I'm trying to do it on an attribute on the foreign table.

The context here is that I'm trying to have users only be able to see other users from the same organization. The user is set on a configuration parameter organization.current_tenant, which takes on the value of the Organization.key

Setup:

CREATE TABLE organization (id serial primary key, name text, key text);
CREATE TABLE myuser (id serial primary key, name text, user_organization_id integer);

INSERT INTO organization (name, key) values ('org1', 'org1-key');
INSERT INTO organization (name, key) values ('org2', 'org2-key');

INSERT INTO myuser (name, user_organization_id) values ('org1_agent1', 1);
INSERT INTO myuser (name, user_organization_id) values ('org2_agent1', 2);
INSERT INTO myuser (name, user_organization_id) values ('org2_agent2', 2);

ALTER TABLE myuser ENABLE ROW LEVEL SECURITY;
ALTER TABLE myuser FORCE ROW LEVEL SECURITY;

When using a direct FK, organization_id:

CREATE POLICY access_tenant_data ON myuser
USING (user_organization_id::TEXT = current_setting('organization.current_tenant'));

This works since user_organization_id is the foreign key available on the user table.

However, what I want to use is instead something like user.organization.key.

CREATE POLICY access_tenant_data ON myuser
USING (
    key IN (
        SELECT key FROM
        myuser U INNER JOIN organization O
        ON U.organization_id = O.id
    )::TEXT = current_setting('organization.current_tenant')
);

But this obviously doesn't work. I'm not sure how to proceed from here.

Testing it out:

SET organization.current_tenant = "org1-key";
SELECT * from myuser;

Body:
That should be fairly simple:

CREATE POLICY access_tenant_data ON myuser
USING (
   EXISTS (SELECT 1 FROM organization AS o
           WHERE myuser.user_organization_id = o.id
             AND o.key = current_setting('organization.current_tenant')
          )
);

That can be fairly efficient, since PostgreSQL can compute the resulting query using a semi-join.


问:
Combining data from multiple tables when using Group By
I have data in about 20 different tables. Each table has a column EnterDateTime for the data / time the data in those tables was added. I'm already using a combination of DATEPART (ISO_WEEK) and GROUP BY to view how much data was added for each week using the following query:

```<code>SELECT DATEPART (ISO_WEEK, EnterDateTime) WeekNum, COUNT (*) as COUNT
FROM TABLE 1
GROUP BY DATEPART (ISO_WEEK, EnterDateTime)
ORDER BY WeekNum
</code>```

Which is giving results like this, for the data in Table 1:

```<code>WeekNum | Count
1       | 1084
2       | 5257
3       | 2152
4       | 5172
</code>```

I am then doing the same query on Table 2:

```<code>WeekNum | Count
1       | 362
2       | 153
3       | 78
4       | 216
</code>```

And so on, and so on, for each of the 20 tables. This is time consuming.

Ideally, I'd like to see this in a single output, like this, so I only have to run one query, instead of about 20:

```<code>WeekNum | Table 1 Count  | Table 2 Count | Table 3 Count
1       | 1084           | 362           |  x
2       | 5257           | 153           |  x
3       | 2152           | 78            |  x
4       | 5172           | 216           |  x
</code>```

Is this possible? Thank you for your help.

答:
You can do this via UNION</p>
```<code>SELECT DATEPART (ISO_WEEK, EnterDateTime) WeekNum, COUNT (*) as COUNT_TABLE1, count(0) as COUNT_TABLE2, ...
FROM TABLE 1
UNION
SELECT DATEPART (ISO_WEEK, EnterDateTime) WeekNum, COUNT (0) as COUNT_TABLE1, ...
FROM TABLE 2
</code>```

Body:
I have data in about 20 different tables. Each table has a column EnterDateTime for the data / time the data in those tables was added. I'm already using a combination of DATEPART (ISO_WEEK) and GROUP BY to view how much data was added for each week using the following query:

SELECT DATEPART (ISO_WEEK, EnterDateTime) WeekNum, COUNT (*) as COUNT
FROM TABLE 1
GROUP BY DATEPART (ISO_WEEK, EnterDateTime)
ORDER BY WeekNum

Which is giving results like this, for the data in Table 1:

WeekNum | Count
1       | 1084
2       | 5257
3       | 2152
4       | 5172

I am then doing the same query on Table 2:

WeekNum | Count
1       | 362
2       | 153
3       | 78
4       | 216

And so on, and so on, for each of the 20 tables. This is time consuming.

Ideally, I'd like to see this in a single output, like this, so I only have to run one query, instead of about 20:

WeekNum | Table 1 Count  | Table 2 Count | Table 3 Count
1       | 1084           | 362           |  x
2       | 5257           | 153           |  x
3       | 2152           | 78            |  x
4       | 5172           | 216           |  x

Is this possible? Thank you for your help.

Body:
You can do this via UNION

SELECT DATEPART (ISO_WEEK, EnterDateTime) WeekNum, COUNT (*) as COUNT_TABLE1, count(0) as COUNT_TABLE2, ...
FROM TABLE 1
UNION
SELECT DATEPART (ISO_WEEK, EnterDateTime) WeekNum, COUNT (0) as COUNT_TABLE1, ...
FROM TABLE 2


问:
running flutter app got Execution failed for task ':bluetoothadapter:compileDebugJavaWithJavac'
I didn't change anything in my Flutter application and it was running perfectly but when i tried running on real device i got this exception
FAILURE: Build failed with an exception.</p>
```<code>* What went wrong:
Execution failed for task ':bluetoothadapter:compileDebugJavaWithJavac'.
> Could not find tools.jar. Please check that C:\Program Files\Java\jre1.8.0_321 contains a valid JDK installation.
</code>```
```<code>BUILD FAILED in 13s
Exception: Gradle task assembleDebug failed with exit code 1
</code>```

答:
Check out this post for a workaround:

tools.jar seems to be not in Android Studio classpath on Windows 8

It seems, the tools.jar is not present on every version of Java 8 anymore. Also make sure to use a JDK and not a pure JRE for development.

Maybe it is worth downloading a current version of the JDK from https://adoptopenjdk.net

Body:
I didn't change anything in my Flutter application and it was running perfectly but when i tried running on real device i got this exception
FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':bluetoothadapter:compileDebugJavaWithJavac'.
> Could not find tools.jar. Please check that C:\Program Files\Java\jre1.8.0_321 contains a valid JDK installation.

BUILD FAILED in 13s
Exception: Gradle task assembleDebug failed with exit code 1


问:
luxon get local date string with GMT from YYYY-MM-DD
I am using luxon for my app. I have simple date string like this 2022-02-10 and I want to convert them into Thu Feb 10 2022 00:00:00 GMT+0200 (Eastern European Standard Time). But don't know how to do it in luxon.

const { DateTime } = require("luxon");

const date = "2022-02-10";

const dateTimeWithGMT = DateTime.fromISO(date);

console.log(dateTimeWithGMT);

// expected output

// Thu Feb 10 2022 00:00:00 GMT+0200 (Eastern European Standard Time)```

答:
Your desired format seem to be the one returned by JavaScript Date toString, so you can simply convert luxon's DateTime object to native JavaScript Date using toJSDate()

const DateTime = luxon.DateTime;

const date = "2022-02-10";
const dateTimeWithGMT = DateTime.fromISO(date);
console.log(dateTimeWithGMT.toJSDate().toString());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/luxon@2.3.0/build/global/luxon.js"></script></code>```

Formatting section of the docs properly describes how to format Luxon DateTime objects. Luxon supports ISO 8601 formats (see toISO()), human readable formats (see toLocaleString) and custom formats (see toFormat)

Body:
Your desired format seem to be the one returned by JavaScript Date toString, so you can simply convert luxon's DateTime object to native JavaScript Date using toJSDate()

const DateTime = luxon.DateTime;

const date = "2022-02-10";
const dateTimeWithGMT = DateTime.fromISO(date);
console.log(dateTimeWithGMT.toJSDate().toString());

<script src="https://cdn.jsdelivr.net/npm/luxon@2.3.0/build/global/luxon.js"></script>

Formatting section of the docs properly describes how to format Luxon DateTime objects. Luxon supports ISO 8601 formats (see toISO()), human readable formats (see toLocaleString) and custom formats (see toFormat)


问:
Unable to resolve cloudformation template using !Sub
I am trying to keep apigateway DNS values in ssm parameter section. The way I used the function Select it is just printing in SSM. apiEndpoint is another resources which is working fine.

I need to change something in Value section so that I can keep the DNS name in ssm parameter.

```<code>  APIGWEndpointSSM:
    Type: AWS::SSM::Parameter
    Properties :
      Description : vpc endpoint for the nextgen apigateway.
      Name : /vpc/apigwvpcendpoint
      Type : String
      Value : https://!Sub(!Select [1, !Split [":", !Select [ 0, !GetAtt apiEndpoint.DnsEntries ]]])
</code>```

答:
You can use array form of Sub:</p>
```<code>Name: !Sub
  - "https://${dns}"
  - { dns: !Select [1, !Split [":", !Select [ 0, !GetAtt apiEndpoint.DnsEntries]]] }
</code>```

Body:
I am trying to keep apigateway DNS values in ssm parameter section. The way I used the function Select it is just printing in SSM. apiEndpoint is another resources which is working fine.

I need to change something in Value section so that I can keep the DNS name in ssm parameter.

  APIGWEndpointSSM:
    Type: AWS::SSM::Parameter
    Properties :
      Description : vpc endpoint for the nextgen apigateway.
      Name : /vpc/apigwvpcendpoint
      Type : String
      Value : https://!Sub(!Select [1, !Split [":", !Select [ 0, !GetAtt apiEndpoint.DnsEntries ]]])

Body:
You can use array form of Sub:

Name: !Sub
  - "https://${dns}"
  - { dns: !Select [1, !Split [":", !Select [ 0, !GetAtt apiEndpoint.DnsEntries]]] }


问:
Does "auto" keyword always evaluates floating point value as double?
Continuing the question, which was closed:
C++: "auto" keyword affects math calculations?

As people suggested I modified the code by adding "f" suffix to floating-point values.

```<code>#include <cmath>
unsigned int nump=12u;
auto inner=2.5f;
auto outer=6.0f;
auto single=2.f*3.14159265359f/nump;
auto avg=0.5f*inner+0.5f*outer;
for (auto i=0u;i<nump;++i){
    auto theta=i*single;
    auto px=avg*sin(theta);
    auto py=avg*cos(theta);
    auto tw=17.f;
    int v1=std::round(1.f+px-tw/2.0f);
    int v2=std::round(2.f+py-tw/2.0f);
    std::cout<<"#"<<i<<":"<<v1<<";"<<v2<<std::endl;
}
</code>```

versus

```<code>#include <cmath>
unsigned int nump=12u;
float inner=2.5f;
float outer=6.0f;
float single=2.f*3.14159265359f/nump;
float avg=0.5f*inner+0.5f*outer;
for (unsigned int i=0u;i<nump;++i){
    float theta=i*single;
    float px=avg*sin(theta);
    float py=avg*cos(theta);
    float tw=17.f;
    int v1=std::round(1.f+px-tw/2.0f);
    int v2=std::round(2.f+py-tw/2.0f);
    std::cout<<"#"<<i<<":"<<v1<<";"<<v2<<std::endl;
}
</code>```

The result is exactly the same - output differs between two versions.
So does it mean that "auto" always evaluates floating point value to "double" type?

答:
When you use the literal 2.5f you are already suggesting that the value is a float.

You'll see that if you try using 2.5 as literal when assigning value to an auto variable, it deduces this as double.

auto var1 = 2.5   // deduced as type double
auto var2 = 2.5f  // deduced as type float as suggested in literal
```

Body:
Continuing the question, which was closed:
C++: "auto" keyword affects math calculations?

As people suggested I modified the code by adding "f" suffix to floating-point values.

#include <cmath>
unsigned int nump=12u;
auto inner=2.5f;
auto outer=6.0f;
auto single=2.f*3.14159265359f/nump;
auto avg=0.5f*inner+0.5f*outer;
for (auto i=0u;i<nump;++i){
    auto theta=i*single;
    auto px=avg*sin(theta);
    auto py=avg*cos(theta);
    auto tw=17.f;
    int v1=std::round(1.f+px-tw/2.0f);
    int v2=std::round(2.f+py-tw/2.0f);
    std::cout<<"#"<<i<<":"<<v1<<";"<<v2<<std::endl;
}

versus

#include <cmath>
unsigned int nump=12u;
float inner=2.5f;
float outer=6.0f;
float single=2.f*3.14159265359f/nump;
float avg=0.5f*inner+0.5f*outer;
for (unsigned int i=0u;i<nump;++i){
    float theta=i*single;
    float px=avg*sin(theta);
    float py=avg*cos(theta);
    float tw=17.f;
    int v1=std::round(1.f+px-tw/2.0f);
    int v2=std::round(2.f+py-tw/2.0f);
    std::cout<<"#"<<i<<":"<<v1<<";"<<v2<<std::endl;
}

The result is exactly the same - output differs between two versions.
So does it mean that "auto" always evaluates floating point value to "double" type?


问:
Add all files to a commit except a single file?
I have a bunch of files in a changeset, but I want to specifically ignore a single modified file. Looks like this after git status:

```<code># modified:   main/dontcheckmein.txt
# deleted:    main/plzcheckmein.c
# deleted:    main/plzcheckmein2.c
...
</code>```

Is there a way I can do git add but just ignore the one text file I don't want to touch? Something like:

```<code>git add -u -except main/dontcheckmein.txt
</code>```

答:
add all files

git add .

get file path to paste below

git status

remove from the commit

git reset -- file/to/path/file-to-ignore.txt

ContentLicense: CC BY-SA 3.0

Body:
I have a bunch of files in a changeset, but I want to specifically ignore a single modified file. Looks like this after git status:

# modified:   main/dontcheckmein.txt
# deleted:    main/plzcheckmein.c
# deleted:    main/plzcheckmein2.c
...

Is there a way I can do git add but just ignore the one text file I don't want to touch? Something like:

git add -u -except main/dontcheckmein.txt


问:
What is the best way to tell the compiler to differentiate between two types which hold the same kind of data
Suppose we have two types which are basically ints:

```<code>alias UserID = int;
alias ItemID = int;
</code>```

And suppose we have two functions which take arguments of the two types:

```<code>void add_user(UserID id) { std::cout << "Adding user with id " << id << '\n'; }
void add_item(ItemID id) { std::cout << "Adding item with id " << id << '\n'; }
</code>```

The problem is that we can do:

```<code>UserID uid {5};
add_item(uid);
</code>```

And the compiler will not be able to protect me from passing the wrong type because both types alias the same underlying type.

What is the least boilerplate I need to add to make the compiler differentiate between the two types?

My current solution is to define the types as structs like this:

```<code>struct UserID
{
  int val;
  operator int() { return val; }
};

struct ItemID
{
  int val;
  operator int() { return val; }
};
</code>```

The operator int() is to allow for an implicit conversion to the base type.

One problem with this approach is that sometimes I need to do arithmetic operations on the types, like for example:

```<code>UserID uid {5};
++uid;
</code>```

Another problem is when these types are passed to a template and a template-argument deduction takes place where the correct type to deduce is int but the compiler is not able to see through the conversion operator.

I'm wondering if there's a more elegant solution where both types would seamlessly convert to their base type when the base type is required but would still be different when the wrapping type is required.
What I want is the following:

```<code>add_user(UserID{1}); //compiles
add_item(ItemID{2}); //compiles
add_user(ItemID{3}); //doesn't compile
UserID uid = UserID{4} + 1; //compiles
++uid; //compiles
UserID uid2 = ItemID{5} + 1; //doesn't compile
</code>```

By 'the least boilerplate' I mean the total boilerplate code I need to write both in the definition of the types as well as in the user code.

答:
You should use some ready library, here is an example of NamedType:

#include <NamedType/named_type.hpp>
#include <iostream>

using UserID = fluent::NamedType<int, struct UserIDTag, fluent::PreIncrementable, fluent::Addable, fluent::Printable>;
using ItemID = fluent::NamedType<int, struct ItemIDTag, fluent::PreIncrementable, fluent::Addable, fluent::Printable>;

void add_user(UserID id) { std::cout << "Adding user with id " << id << '\n'; }
void add_item(ItemID id) { std::cout << "Adding item with id " << id << '\n'; }

int main()
{
    UserID uid { 5 };
    // add_item(uid); // fails to compile
    add_user(uid);

    add_user(UserID { 1 }); // compiles
    add_item(ItemID { 2 }); // compiles
    // add_user(ItemID { 3 }); // doesn't compile
    // UserID uid2 = UserID { 4 } + 1; // should compile - feature not supported
    ++uid; // compiles
    // UserID uid2 = ItemID { 5 } + 1; // doesn't compile

    return 0;
}
```

Live demo. Cool godbolt supports that library :).

Body:
Suppose we have two types which are basically ints:

alias UserID = int;
alias ItemID = int;

And suppose we have two functions which take arguments of the two types:

void add_user(UserID id) { std::cout << "Adding user with id " << id << '\n'; }
void add_item(ItemID id) { std::cout << "Adding item with id " << id << '\n'; }

The problem is that we can do:

UserID uid {5};
add_item(uid);

And the compiler will not be able to protect me from passing the wrong type because both types alias the same underlying type.

What is the least boilerplate I need to add to make the compiler differentiate between the two types?

My current solution is to define the types as structs like this:

struct UserID
{
  int val;
  operator int() { return val; }
};

struct ItemID
{
  int val;
  operator int() { return val; }
};

The operator int() is to allow for an implicit conversion to the base type.

One problem with this approach is that sometimes I need to do arithmetic operations on the types, like for example:

UserID uid {5};
++uid;

Another problem is when these types are passed to a template and a template-argument deduction takes place where the correct type to deduce is int but the compiler is not able to see through the conversion operator.

I'm wondering if there's a more elegant solution where both types would seamlessly convert to their base type when the base type is required but would still be different when the wrapping type is required.
What I want is the following:

add_user(UserID{1}); //compiles
add_item(ItemID{2}); //compiles
add_user(ItemID{3}); //doesn't compile
UserID uid = UserID{4} + 1; //compiles
++uid; //compiles
UserID uid2 = ItemID{5} + 1; //doesn't compile

By 'the least boilerplate' I mean the total boilerplate code I need to write both in the definition of the types as well as in the user code.

Body:
You should use some ready library, here is an example of NamedType:

#include <NamedType/named_type.hpp>
#include <iostream>

using UserID = fluent::NamedType<int, struct UserIDTag, fluent::PreIncrementable, fluent::Addable, fluent::Printable>;
using ItemID = fluent::NamedType<int, struct ItemIDTag, fluent::PreIncrementable, fluent::Addable, fluent::Printable>;

void add_user(UserID id) { std::cout << "Adding user with id " << id << '\n'; }
void add_item(ItemID id) { std::cout << "Adding item with id " << id << '\n'; }

int main()
{
    UserID uid { 5 };
    // add_item(uid); // fails to compile
    add_user(uid);

    add_user(UserID { 1 }); // compiles
    add_item(ItemID { 2 }); // compiles
    // add_user(ItemID { 3 }); // doesn't compile
    // UserID uid2 = UserID { 4 } + 1; // should compile - feature not supported
    ++uid; // compiles
    // UserID uid2 = ItemID { 5 } + 1; // doesn't compile

    return 0;
}

Live demo. Cool godbolt supports that library :).


问:
Laravel Passport routes missing in route:list - 404 error on oauth/token
I have followed the Laravel 5.5 documentation to require, install and configure Laravel Passport on our application. We are ONLY using the password grant functionality as we aren't intending to use this as a social login tool. However, after following all the instructions, I am getting a 404 error when attempting to POST the form data into the application using Postman.

I have run php artisan route:list and there is no mention in there of oauth at all. I'd share the output but it's quite long as we have a large application.

I have ensured that Passport::routes() is in the AuthServiceProvider as shown below:

```<code><?php

namespace App\Providers;

use Laravel\Passport\Passport;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();
        Passport::routes();
        //
    }
}
</code>```

The documentation on 5.5 does not say anything about adding a line to the config/app.php file as previous versions of Laravel do. After getting the 404 errors I decided to try adding that line just to see if it helps. It does not.

I did in fact run php artisan passport:install and then php artisan migrate which resulted in the creation of 2 clients: (ID = 1: Personal Access Client) and ID 2: Password Grant Client) and the various oauth tables being created in our database.

The resulting 404 error IS in fact coming from the site and not some generic message as it has our theme wrapped around it so I know it's hitting the application.

I have searched for references to the 404 error on oauth/token and Laravel Passport but have come up dry on solutions.

Any suggestions are greatly appreciated.

答: I had also the same problem and fixed with clearing the caches php artisan o:c

Body:
I have followed the Laravel 5.5 documentation to require, install and configure Laravel Passport on our application. We are ONLY using the password grant functionality as we aren't intending to use this as a social login tool. However, after following all the instructions, I am getting a 404 error when attempting to POST the form data into the application using Postman.

I have run php artisan route:list and there is no mention in there of oauth at all. I'd share the output but it's quite long as we have a large application.

I have ensured that Passport::routes() is in the AuthServiceProvider as shown below:

<?php

namespace App\Providers;

use Laravel\Passport\Passport;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();
        Passport::routes();
        //
    }
}

The documentation on 5.5 does not say anything about adding a line to the config/app.php file as previous versions of Laravel do. After getting the 404 errors I decided to try adding that line just to see if it helps. It does not.

I did in fact run php artisan passport:install and then php artisan migrate which resulted in the creation of 2 clients: (ID = 1: Personal Access Client) and ID 2: Password Grant Client) and the various oauth tables being created in our database.

The resulting 404 error IS in fact coming from the site and not some generic message as it has our theme wrapped around it so I know it's hitting the application.

I have searched for references to the 404 error on oauth/token and Laravel Passport but have come up dry on solutions.

Any suggestions are greatly appreciated.


问:
Does/will pact.io provide support for testNG test framework?
I can see from documentation that pact.io tool can integrate well with junit4 and junit5 to execute tests.

https://docs.pact.io/implementation_guides/jvm/readme

https://github.com/pact-foundation/pact-jvm/tree/master/consumer

Are there any plans to support testNG too?

答:
There are no current plans that I'm aware of.

I would suggest raising a feature request in our public roadmap to raise awareness and see if any of the maintainers/community are willing to contribute.

Of course, you are free to create a project that supports testng and I'm sure we could find a home to link to it in our documentation for others who use the framework.


问:
how can I fix "build failed" after I run react-native run-android in windows 10
I have created the project very well and I have also installed the android studio and all the required sdks. but still I am still facing a problem of the emulator not starting. below is error in the terminal.

'$ react-native run-android
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier"
flag.
(node:8368) Warning: Accessing non-existent property 'padLevels' of module exports inside circular dependency
(Use node --trace-warnings ... to show where the warning was created)
Jetifier found 866 file(s) to forward-jetify. Using 6 workers...
info Starting JS server...
'adb' is not recognized as an internal or external command,
operable program or batch file.
info Launching emulator...
error Failed to launch emulator. Reason: No emulators found as an output of emulator -list-avds.
warn Please launch an emulator manually or connect a device. Otherwise app may fail to launch.
info Installing the app...
Starting a Gradle Daemon, 3 stopped Daemons could not be reused, use --status for details

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See https://docs.gradle.org/7.2/userguide/command_line_interface.html#sec:command_line_warnings

FAILURE: Build failed with an exception.

What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.

SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at 'C:\Users\jayde\Desktop\KYC\Zipcomply\android\local.properties'.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 38s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.

SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at 'C:\Users\jayde\Desktop\KYC\Zipcomply\android\local.properties'.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 38s

```<code>at makeError (C:\Users\jayde\Desktop\KYC\Zipcomply\node_modules\execa\index.js:174:9)
at C:\Users\jayde\Desktop\KYC\Zipcomply\node_modules\execa\index.js:278:16
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async runOnAllDevices (C:\Users\jayde\Desktop\KYC\Zipcomply\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:109:5)
at async Command.handleAction (C:\Users\jayde\Desktop\KYC\Zipcomply\node_modules\react-native\node_modules\@react-native-community\cli\build\index.js:192:9)
</code>```

info Run CLI with --verbose flag for more details.`

答:
ANDROID_HOME is Deprecated (in Android Studio), use ANDROID_SDK_ROOT instead.

Configure the ANDROID_SDK_ROOT environment variable

Open the Windows Control Panel.

Click on User Accounts, then click
User Accounts again

Click on Change my environment variables

Click on New... to create a new ANDROID_SDK_ROOT user variable that points to the path to your Android SDK:

The SDK is installed, by default, at the following location:

```<code>%LOCALAPPDATA%\Android\Sdk
</code>```

You can find the actual location of the SDK in the Android Studio "Settings" dialog, under Appearance & Behavior → System Settings → Android SDK.

Body:
I have created the project very well and I have also installed the android studio and all the required sdks. but still I am still facing a problem of the emulator not starting. below is error in the terminal.

'$ react-native run-android
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier"
flag.
(node:8368) Warning: Accessing non-existent property 'padLevels' of module exports inside circular dependency
(Use node --trace-warnings ... to show where the warning was created)
Jetifier found 866 file(s) to forward-jetify. Using 6 workers...
info Starting JS server...
'adb' is not recognized as an internal or external command,
operable program or batch file.
info Launching emulator...
error Failed to launch emulator. Reason: No emulators found as an output of emulator -list-avds.
warn Please launch an emulator manually or connect a device. Otherwise app may fail to launch.
info Installing the app...
Starting a Gradle Daemon, 3 stopped Daemons could not be reused, use --status for details

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See https://docs.gradle.org/7.2/userguide/command_line_interface.html#sec:command_line_warnings

FAILURE: Build failed with an exception.

What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.

SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at 'C:\Users\jayde\Desktop\KYC\Zipcomply\android\local.properties'.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 38s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.

SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at 'C:\Users\jayde\Desktop\KYC\Zipcomply\android\local.properties'.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 38s

at makeError (C:\Users\jayde\Desktop\KYC\Zipcomply\node_modules\execa\index.js:174:9)
at C:\Users\jayde\Desktop\KYC\Zipcomply\node_modules\execa\index.js:278:16
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async runOnAllDevices (C:\Users\jayde\Desktop\KYC\Zipcomply\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:109:5)
at async Command.handleAction (C:\Users\jayde\Desktop\KYC\Zipcomply\node_modules\react-native\node_modules\@react-native-community\cli\build\index.js:192:9)

info Run CLI with --verbose flag for more details.`

Body:
ANDROID_HOME is Deprecated (in Android Studio), use ANDROID_SDK_ROOT instead.

Configure the ANDROID_SDK_ROOT environment variable

Open the Windows Control Panel.

Click on User Accounts, then click
User Accounts again

Click on Change my environment variables

Click on New... to create a new ANDROID_SDK_ROOT user variable that points to the path to your Android SDK:

The SDK is installed, by default, at the following location:

%LOCALAPPDATA%\Android\Sdk

You can find the actual location of the SDK in the Android Studio "Settings" dialog, under Appearance & Behavior → System Settings → Android SDK.


问:
address already in use error in mosquitto
I have installed mosquitto server and client packages in my ubuntu machine. When I run command "mosquitto" to run the mosquitto server I am getting an error "Error:address already in use". Why am I getting this error? How can I resolve this?</p>

答:
I've discovered that if you have :

```<code>socket_domain ipv4
</code>```

before :

```<code>listener 1883 yourhostname
</code>```

in your config,
it results in "Address already in use",
you just have to invert the order...

Body:
I've discovered that if you have :

socket_domain ipv4

before :

listener 1883 yourhostname

in your config,
it results in "Address already in use",
you just have to invert the order...


问:
ServiceBusReceiver PeekMessageAsync only returns maximum of 250 dlq-messages?
I am reading from a deadletter queue on servicebus using the ServiceBusReceiver(which I want to continue using).

However, the receiver.PeekMessagesAsync(550) only fetches a maximum of 250 messages from deadletter queue???
How can I change this? I already have it set to fetch 550 messages so not sure how to do it.

```<code>        string topic = "myTopic";
        string subscriptionAndDeadletterPath = @"mySubscription/$deadletterqueue";
        var paginationSize = 1000;
        var dlqCount = 0;
        var numberOfMessagesToFetchFromDlq = 550;

        try
        {
            await using var client = new ServiceBusClient(connectionString);
            var receiver = client.CreateReceiver(topic, subscriptionAndDeadletterPath, new ServiceBusReceiverOptions() { ReceiveMode = ServiceBusReceiveMode.PeekLock, PrefetchCount = paginationSize });

            var messagesFromDlq = await receiver.PeekMessagesAsync(numberOfMessagesToFetchFromDlq);
            dlqCount = messagesFromDlq.Count();

</code>```

dlqCount will not exceed 250 for some reason? The int maxMessages parameter doesn't seem to work above this number?

答:
This is how I solved it for now:</p>
```<code>        string topic = "myTopic";
        string subscriptionAndDeadletterPath = @"mySubscription/$deadletterqueue";
        var sequence = 0;
        var continueWithNextIteration = true;
        var paginationSize = 100;
        var numberOfMessagesToFetchFromDlq = 250

            await using var client = new ServiceBusClient(connectionString);
            var receiver = client.CreateReceiver(topic, subscriptionAndDeadletterPath, new ServiceBusReceiverOptions() { ReceiveMode = ServiceBusReceiveMode.PeekLock, PrefetchCount = paginationSize });

            do
            {
                var messagesFromDlq = await receiver.PeekMessagesAsync(numberOfMessagesToFetchFromDlq, sequence);
                if (messagesFromDlq.Count() > 249)
                {
                    var nextSequenceSetting = await receiver.PeekMessagesAsync(2, Convert.ToInt32(messagesFromDlq.Last().SequenceNumber));
                    sequence = Convert.ToInt32(nextSequenceSetting.Last().SequenceNumber);
                    continueWithNextIteration = nextSequenceSetting.Count() > 1 ? true : false;
                }

            } while (continueWithNextIteration);
</code>```

Body:
I am reading from a deadletter queue on servicebus using the ServiceBusReceiver(which I want to continue using).

However, the receiver.PeekMessagesAsync(550) only fetches a maximum of 250 messages from deadletter queue???
How can I change this? I already have it set to fetch 550 messages so not sure how to do it.

        string topic = "myTopic";
        string subscriptionAndDeadletterPath = @"mySubscription/$deadletterqueue";
        var paginationSize = 1000;
        var dlqCount = 0;
        var numberOfMessagesToFetchFromDlq = 550;

        try
        {
            await using var client = new ServiceBusClient(connectionString);
            var receiver = client.CreateReceiver(topic, subscriptionAndDeadletterPath, new ServiceBusReceiverOptions() { ReceiveMode = ServiceBusReceiveMode.PeekLock, PrefetchCount = paginationSize });

            var messagesFromDlq = await receiver.PeekMessagesAsync(numberOfMessagesToFetchFromDlq);
            dlqCount = messagesFromDlq.Count();

dlqCount will not exceed 250 for some reason? The int maxMessages parameter doesn't seem to work above this number?

Body:
This is how I solved it for now:

        string topic = "myTopic";
        string subscriptionAndDeadletterPath = @"mySubscription/$deadletterqueue";
        var sequence = 0;
        var continueWithNextIteration = true;
        var paginationSize = 100;
        var numberOfMessagesToFetchFromDlq = 250

            await using var client = new ServiceBusClient(connectionString);
            var receiver = client.CreateReceiver(topic, subscriptionAndDeadletterPath, new ServiceBusReceiverOptions() { ReceiveMode = ServiceBusReceiveMode.PeekLock, PrefetchCount = paginationSize });

            do
            {
                var messagesFromDlq = await receiver.PeekMessagesAsync(numberOfMessagesToFetchFromDlq, sequence);
                if (messagesFromDlq.Count() > 249)
                {
                    var nextSequenceSetting = await receiver.PeekMessagesAsync(2, Convert.ToInt32(messagesFromDlq.Last().SequenceNumber));
                    sequence = Convert.ToInt32(nextSequenceSetting.Last().SequenceNumber);
                    continueWithNextIteration = nextSequenceSetting.Count() > 1 ? true : false;
                }

            } while (continueWithNextIteration);


问:
Angular custom form control not updating form value
I have a password input component, which is a custom form control.

The problem is, when I type into the input, the form value (created with FormGroup) is not being updated.

However, when I use form.get('key').setValue('value here'), the form value as well as the component are updated correctly.

What might be the issue?

Using Angular v13.2.1 • Whole source code • component with the form • password input component

Wanted to upload it to Stackblitz, but was getting many unrelated errors.

答:
writeValue function is called by angular when the input in the ui gets updated.
onChange should be called by the component whenever an internal change should be reflected in the ui.
So it's not quite right to call onChange whenever writeValue gets called by angular. Instead, you should set the form control value in onChange.
Also, by putting [value] = "value" on the input, and calling onInput(), you're calling on change with an outdated value of the value variable.
Try using 2 way binding using [(ngModel)] = "value" and (ngModelChange) instead.</p>


问:
C# - Binary reader in Big Endian?
I'm trying to improve my understanding of the STFS file format by using a program to read all the different bits of information. Using a website with a reference of which offsets contain what information, I wrote some code that has a binary reader go through the file and place the values in the correct variables.

The problem is that all the data is SUPPOSED to be Big Endian, and everything the binary reader read is Little Endian. So, what's the best way to go about fixing this?

Can I create a mimic class of Binary reader that returns a reversed array of bytes? Is there something I can change in class instance that will make it read in big endian so I don't have to rewrite everything?

Any help is appreciated.

edit: I tried adding Encoding.BigEndianUnicode as a parameter, but it still reads little endian.

答:
You better to use BinaryPrimitives class

        public override double ReadDouble()
        {
            return BinaryPrimitives.ReadDoubleBigEndian(ReadBytes(8));
        }

        public override short ReadInt16()
        {
            return BinaryPrimitives.ReadInt16BigEndian(ReadBytes(2));
        }

        public override int ReadInt32()
        {
            return BinaryPrimitives.ReadInt32BigEndian(ReadBytes(4));
        }

        public override long ReadInt64()
        {
            return BinaryPrimitives.ReadInt64BigEndian(ReadBytes(8));
        }

        public override float ReadSingle()
        {
            return BinaryPrimitives.ReadSingleBigEndian(ReadBytes(4));
        }

        public override ushort ReadUInt16()
        {
            return BinaryPrimitives.ReadUInt16BigEndian(ReadBytes(2));
        }

        public override uint ReadUInt32()
        {
            return BinaryPrimitives.ReadUInt32BigEndian(ReadBytes(4));
        }

        public override ulong ReadUInt64()
        {
            return BinaryPrimitives.ReadUInt64BigEndian(ReadBytes(8));
        }
```

Title: C# - Binary reader in Big Endian?


问:
Apply a function that takes two vectors as input to two matrices across their corresponding columns (in R)
I have a function in R that takes two vectors and an integer like this:

```<code>MyFunction<-function(MyLoot, DungeonLoot, DungeonOrder)
{

  # Perfect Match
  PerfectMatch = MyLoot[1]==DungeonLoot[1]

  # Group Match
  GroupandClassMatch = (MyLoot[2]==DungeonLoot[2])&(MyLoot[3]>=DungeonLoot[3])

  # Order Match
  OrderMatch = MyLoot[5]==DungeonOrder

  # Order Match +1
  OrderMatchPlusOne = (OrderMatch)&(MyLoot[8]==1)

  # Final Score
  Score = PerfectMatch*1 + GroupandClassMatch*1 + OrderMatch*2 + OrderMatchPlusOne*1

  return(Score)
}
</code>```

Now I want to apply MyFunction to two matrices Matrix1 and Matrix2 across their rows so that I have a vector that looks something like:

```<code>c(MyFunction(Matrix1[1,],Matrix2[1,],12),MyFunction(Matrix1[2,],Matrix2[2,],12),...,MyFunction[Matrix1[n,],Matrix2[n,],12)
</code>```

What is the best (and most efficient) way of doing this? I could use a for loop but wondering if there is a better way e.g. using one of apply, sapply, mapply, lappy functions

答:
An example data along with expected output would have helped to better understand the question. However, I think you don't need any loop or apply functions to do this. If you have input as matrix then you should be able to do this directly.

Try,

```<code>rowSums(Matrix1 == Matrix2)
#For only specific columns
#rowSums(Matrix1[, 1:2] == Matrix2[, 1:2])
</code>```

Body:
I have a function in R that takes two vectors and an integer like this:

MyFunction<-function(MyLoot, DungeonLoot, DungeonOrder)
{

  # Perfect Match
  PerfectMatch = MyLoot[1]==DungeonLoot[1]

  # Group Match
  GroupandClassMatch = (MyLoot[2]==DungeonLoot[2])&(MyLoot[3]>=DungeonLoot[3])

  # Order Match
  OrderMatch = MyLoot[5]==DungeonOrder

  # Order Match +1
  OrderMatchPlusOne = (OrderMatch)&(MyLoot[8]==1)

  # Final Score
  Score = PerfectMatch*1 + GroupandClassMatch*1 + OrderMatch*2 + OrderMatchPlusOne*1

  return(Score)
}

Now I want to apply MyFunction to two matrices Matrix1 and Matrix2 across their rows so that I have a vector that looks something like:

c(MyFunction(Matrix1[1,],Matrix2[1,],12),MyFunction(Matrix1[2,],Matrix2[2,],12),...,MyFunction[Matrix1[n,],Matrix2[n,],12)

What is the best (and most efficient) way of doing this? I could use a for loop but wondering if there is a better way e.g. using one of apply, sapply, mapply, lappy functions

Body:
An example data along with expected output would have helped to better understand the question. However, I think you don't need any loop or apply functions to do this. If you have input as matrix then you should be able to do this directly.

Try,

rowSums(Matrix1 == Matrix2)
#For only specific columns
#rowSums(Matrix1[, 1:2] == Matrix2[, 1:2])


问:
Finding all the number of ip addresses used in eks with fargate
I am trying to understand the usage of the ip addresses from my vpc in the eks with fargate environment. I can see that each pod has its own private ip address, which seems to be the same ip address for fargate node as well. It seems that the ENI allocates a single primary address for a EC2 node and many ip address as secondary based on the size, but I cannot find the same information on fargate. Does that mean it does not have any secondary ip addresses allocated ?

Extending on the question, it seems that a network load balancer requires a minimum of 8 free ip addressses to be created, Does that mean it blocks all the 8 ?

答:
...Does that mean it does not have any secondary ip addresses allocated ?

Correct, since you can only run 1 pod on each Fargate instance, while on EC2 node you can run many pods.

...Does that mean it blocks all the 8 ?

The LB controller won't block subnet IP. When you make request to create NLB in a subnet that has insufficient IP, you will see error message like: ..."error":"InvalidSubnet: Not enough IP space available in subnet-.... ELB requires at least 8 free IP addresses in each subnet. Note this is a requirement of ELB and not EKS.


问:
Truncation error SQL server 2005 Delete/Insert
So I am trying to do a bulk insert with SSIS and continually get:

"Microsoft SQL Native Client"  Hresult: 0x80004005  Description: "String or binary data would be truncated."

Even though I already have a data conversion for every column into the exact same type as the table that the rows are getting inserted into. I used a view and the data looks like it supposed to just before the DB insert step. Still get the error.

Next I went into sql server management studio and setup an insert query into that damned table and still get the same truncation error. I then did a set ANSI_WARNINGS  OFF and the insert works data looks good in the table. Now when I try to delete this row I get the Truncation error.

My question besides any basic input to the situation is how can I turn off the ANSI_WARNINGS within SSIS so that the bulk load can go though?

答:
Turns out that in SSIS you can setup the OLE DB Destination with "Data Access Mode > Table or view: Fast Mode". When I chose this setting the bulk insert went through without any warnings or errors and the data looks perfect in the database. Not sure what this change did exactly but it worked and after 16hours on one SSIS insert I'm happy with results.

Thanks for the suggestions.

OwnerDisplayName: Andrew Jahn

ContentLicense: CC BY-SA 2.5


问:
Let image size be relative to sibling flex element

How can the height of the image be relative to the height of the elements on the left?

I'm trying to create the following layout:

What I tried

I'm trying to achieve this with flexbox. My html looks like this. I have display:flex on the container
. That container houses two children containers:
 and
. The first has an h1, p and a. The second the img.

I gave both children a width of 48%, and I want my image to occupy as much vertical space as possible, but not more than the height of
.

HTML

```<code><section class="intro">
  <div class="split">
     <div class="intro__primary">
        <h1></h1>
        <p></p>
        <a class="btn"></a>
     </div>
     <div class="intro__secondary">
        <img>
     </div>
</div>
</code>```

CSS

```<code>.split {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
}

.intro__primary {
        width: 48%;
        align-self: flex-start;
}

.intro__secondary {
    width: 48%;
    height: 100%;
    align-self: flex-end;
}

.intro__secondary > img {
    max-width: 100%;
    height: 100%;
}
</code>```

The code above results in an image that has a way larger height than the container with the text on the left. I played a lot with all the properties but can't fix it. What am I overlooking?

答:
.split {
  max-height: 100px;
  display: flex;
}
.intro__secondary {
  max-height: 100%;
}
.intro__secondary img {
  height: 100%;
  width: 100%;
  object-fit: cover; /* you can also use object-fit: contain; */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="intro">
  <div class="split">
     <div class="intro__primary">
        <h1>Heading</h1>
        <p>paragraph</p>

     </div>
     <div class="intro__secondary">
        <img src="https://source.unsplash.com/random" alt="random-image">
     </div>
  </div>
</section></code>```

Body:
How can the height of the image be relative to the height of the elements on the left?

I'm trying to create the following layout:

What I tried

I'm trying to achieve this with flexbox. My html looks like this. I have display:flex on the container
. That container houses two children containers:
 and
. The first has an h1, p and a. The second the img.

I gave both children a width of 48%, and I want my image to occupy as much vertical space as possible, but not more than the height of
.

HTML

CSS

.split {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
}

.intro__primary {
        width: 48%;
        align-self: flex-start;
}

.intro__secondary {
    width: 48%;
    height: 100%;
    align-self: flex-end;
}

.intro__secondary > img {
    max-width: 100%;
    height: 100%;
}

The code above results in an image that has a way larger height than the container with the text on the left. I played a lot with all the properties but can't fix it. What am I overlooking?

Body:
.split {
  max-height: 100px;
  display: flex;
}
.intro__secondary {
  max-height: 100%;
}
.intro__secondary img {
  height: 100%;
  width: 100%;
  object-fit: cover; /* you can also use object-fit: contain; */
}

<section class="intro">
  <div class="split">
     <div class="intro__primary">
        <h1>Heading</h1>
        <p>paragraph</p>
        <a class="btn"></a>
     </div>
     <div class="intro__secondary">
        <img src="https://source.unsplash.com/random" alt="random-image">
     </div>
  </div>
</section>


问:
CSRF token mismatch Laravel sanctum and Angular http
I have been trying to implement Laravel sanctum, but I am having this error "CSRF token mismatch" even though I followed everything that is said in the Laravel Sanctum documentation

cors.php config file

'paths' => [
    'api/*',
    'login',
    'logout',
    'sanctum/csrf-cookie'
],
'supports_credentials' => true,
```

<p>kernal is added as per the documentation, so not wasting space by adding its code here</p>

<p><code>.env</code> file</p>

```SESSION_DRIVER=cookie
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost
```

<p>I am using Angular 9 as my frontend here</p>

<p>This is my interceptor </p>

<pre class="lang-js prettyprint-override"><code>request = request.clone({
    withCredentials: true
})
</code>```

This is how I send the request to Laravel

this.http.get<any>(url('sanctum/csrf-cookie')).subscribe(() => {
     this.http.post<any>(url('login'), { this.username, this.password })
         .subscribe(success => console.log(success), error => console.log(error))
})
```

Once the first route is hit I can confirm the creation of cookies, but the issue is with the second route ('/login')

答: I have a similar problem in my case but only some users are having this problem. I solved my problem by changing SESSION_DOMAIN to .localhost in the session.php file under the config folder.

Body:
I have been trying to implement Laravel sanctum, but I am having this error "CSRF token mismatch" even though I followed everything that is said in the Laravel Sanctum documentation

cors.php config file

'paths' => [
    'api/*',
    'login',
    'logout',
    'sanctum/csrf-cookie'
],
'supports_credentials' => true,

kernal is added as per the documentation, so not wasting space by adding its code here

.env file

SESSION_DRIVER=cookie
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost

I am using Angular 9 as my frontend here

This is my interceptor

request = request.clone({
    withCredentials: true
})

This is how I send the request to Laravel

this.http.get<any>(url('sanctum/csrf-cookie')).subscribe(() => {
     this.http.post<any>(url('login'), { this.username, this.password })
         .subscribe(success => console.log(success), error => console.log(error))
})

Once the first route is hit I can confirm the creation of cookies, but the issue is with the second route ('/login')


问:
Partially exploding dataframe with nested lists items
I have a dataframe with the below format:

```<code>         A              B              C
0  [[1,2],[3,4]]  [[5,6],[7,8]]  [[9,10],[11,12]]
</code>```

for multiple rows.

The sub lists are always of length 2 and the length of A,B,C lists are always the same size.However the lengths of the latter vary and for example can be of size 2 or 6..etc for different rows.

What i would like to do is to explode rows like these into:

```<code>         A              B              C
0      [1,2]          [5,6]          [9,10]
0      [3,4]          [7,8]          [11,12]
</code>```

答:
Assuming you really have lists of lists, a simple explode on all columns should work:

```<code>df.explode(df.columns.to_list())
</code>```

output:

```<code>        A       B         C
0  [1, 2]  [5, 6]   [9, 10]
0  [3, 4]  [7, 8]  [11, 12]
</code>```

used input:

```<code>df = pd.DataFrame([[[[1,2],[3,4]], [[5,6],[7,8]], [[9,10],[11,12]]]],
                  columns=['A', 'B', 'C'])
</code>```

Body:
I have a dataframe with the below format:

         A              B              C
0  [[1,2],[3,4]]  [[5,6],[7,8]]  [[9,10],[11,12]]

for multiple rows.

The sub lists are always of length 2 and the length of A,B,C lists are always the same size.However the lengths of the latter vary and for example can be of size 2 or 6..etc for different rows.

What i would like to do is to explode rows like these into:

         A              B              C
0      [1,2]          [5,6]          [9,10]
0      [3,4]          [7,8]          [11,12]

Body:
Assuming you really have lists of lists, a simple explode on all columns should work:

df.explode(df.columns.to_list())

output:

        A       B         C
0  [1, 2]  [5, 6]   [9, 10]
0  [3, 4]  [7, 8]  [11, 12]

used input:

df = pd.DataFrame([[[[1,2],[3,4]], [[5,6],[7,8]], [[9,10],[11,12]]]],
                  columns=['A', 'B', 'C'])


问:
reload react component without reloading the page
Hi i have component and function "handleAvatarUpload". After onChange i want to reload only component not whole page. Now after change function reload whole page "only for tests". How can i reload only a component in the same place where now i put page reload?

```<code>
import { useUpdateSpecialistProfileMutation } from 'api-hooks/updateSpecialistProfile/updateSpecialistProfile.generated';
import { useS3DirectUpload } from 'hooks';
import { EditIcon } from 'icons';
import { FileTypeEnum } from 'interfaces';

import { AvatarEditIcon, ImageUpload } from './AvatarEdit.styled';

interface AvatarEditProps {
  onChange: (fileId: string) => void;
  userId?: string;
  avatarPictureFileId?: string;
  userName?: ReactNode;
  isDisabled?: boolean;
  fileId?: string;
}

const AvatarEdit = ({ onChange, userId, isDisabled }: AvatarEditProps) => {
  const { upload: uploadToS3 } = useS3DirectUpload();
  const [updateSpecialistProfile] = useUpdateSpecialistProfileMutation();

  const handleAvatarUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files === null) {
      return;
    }
    const file = event.target.files[0];
    try {
      const uploadResult = await uploadToS3(file, FileTypeEnum.AvatarImage);
      await updateSpecialistProfile({
        variables: { input: { avatarPictureFileId: uploadResult.fileId }, userId },
      });
      onChange(uploadResult.fileId);
      window.location.reload();
    } catch (error) {
      console.warn(error);
    }
  };

  return (
    <ImageUpload>
      <label htmlFor="file-input">
        <AvatarEditIcon isDisabled={isDisabled}>
          <EditIcon />
        </AvatarEditIcon>
      </label>
      {isDisabled ? null : (
        <input
          accept="image/jpeg, image/png"
          id="file-input"
          onChange={handleAvatarUpload}
          type="file"
        />
      )}
    </ImageUpload>
  );
};

export default AvatarEdit;
</code>```

i have component where image state was stored but when i edit image by component above nothing happens.

```<code>
import { useFileUrlLazyQuery } from 'api-hooks/fileUrl/fileUrl.generated';

interface ImageProps {
  alt: string;
  fileId?: string;
  fileUrl?: string;
  className?: string;
}

const Image: React.FC<ImageProps> = ({ alt, fileId, fileUrl, className }) => {
  const [resolvedFileUrl, setResolvedFileUrl] = useState<string | undefined>(fileUrl);
  const [executeFileUrlLazyQuery, { data, loading }] = useFileUrlLazyQuery();

  useEffect(() => {
    if (!loading && fileId) {
      executeFileUrlLazyQuery({
        variables: {
          fileId,
        },
      });
    }
  }, [fileId, loading, executeFileUrlLazyQuery]);

  useEffect(() => {
    if (data && data.fileUrl) {
      setResolvedFileUrl(data.fileUrl);
    }
  }, [data]);

  if (resolvedFileUrl) {
    return null;
  }

  return <img alt={alt} className={className} src={resolvedFileUrl} />;
};

export default Image;
</code>```

答:
Update the state using setState.
or
use React hooks like -

```<code>useEffect(()=> {
    fetchData();
}, [data]);
</code>```

this will reload whenever data is updated.

Body:
Hi i have component and function "handleAvatarUpload". After onChange i want to reload only component not whole page. Now after change function reload whole page "only for tests". How can i reload only a component in the same place where now i put page reload?

import { useUpdateSpecialistProfileMutation } from 'api-hooks/updateSpecialistProfile/updateSpecialistProfile.generated';
import { useS3DirectUpload } from 'hooks';
import { EditIcon } from 'icons';
import { FileTypeEnum } from 'interfaces';

import { AvatarEditIcon, ImageUpload } from './AvatarEdit.styled';

interface AvatarEditProps {
  onChange: (fileId: string) => void;
  userId?: string;
  avatarPictureFileId?: string;
  userName?: ReactNode;
  isDisabled?: boolean;
  fileId?: string;
}

const AvatarEdit = ({ onChange, userId, isDisabled }: AvatarEditProps) => {
  const { upload: uploadToS3 } = useS3DirectUpload();
  const [updateSpecialistProfile] = useUpdateSpecialistProfileMutation();

  const handleAvatarUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files === null) {
      return;
    }
    const file = event.target.files[0];
    try {
      const uploadResult = await uploadToS3(file, FileTypeEnum.AvatarImage);
      await updateSpecialistProfile({
        variables: { input: { avatarPictureFileId: uploadResult.fileId }, userId },
      });
      onChange(uploadResult.fileId);
      window.location.reload();
    } catch (error) {
      console.warn(error);
    }
  };

  return (
    <ImageUpload>

        <AvatarEditIcon isDisabled={isDisabled}>
          <EditIcon />
        </AvatarEditIcon>

      {isDisabled ? null : (
        <input
          accept="image/jpeg, image/png"
          id="file-input"
          onChange={handleAvatarUpload}
          type="file"
        />
      )}
    </ImageUpload>
  );
};

export default AvatarEdit;

i have component where image state was stored but when i edit image by component above nothing happens.

import { useFileUrlLazyQuery } from 'api-hooks/fileUrl/fileUrl.generated';

interface ImageProps {
  alt: string;
  fileId?: string;
  fileUrl?: string;
  className?: string;
}

const Image: React.FC<ImageProps> = ({ alt, fileId, fileUrl, className }) => {
  const [resolvedFileUrl, setResolvedFileUrl] = useState<string | undefined>(fileUrl);
  const [executeFileUrlLazyQuery, { data, loading }] = useFileUrlLazyQuery();

  useEffect(() => {
    if (!loading && fileId) {
      executeFileUrlLazyQuery({
        variables: {
          fileId,
        },
      });
    }
  }, [fileId, loading, executeFileUrlLazyQuery]);

  useEffect(() => {
    if (data && data.fileUrl) {
      setResolvedFileUrl(data.fileUrl);
    }
  }, [data]);

  if (resolvedFileUrl) {
    return null;
  }

  return ;
};

export default Image;

Body:
Update the state using setState.
or
use React hooks like -

useEffect(()=> {
    fetchData();
}, [data]);

this will reload whenever data is updated.


问:
how to goto a page by code?
I tried using window.location="#pageLogin".
It works in my desktop but appears a blank in my android device.

After doing some search,I uses $.mobile.changePage like this

```<code>var user;
$(document).ready(function(){
    user=GetCurrUser();
    if(user==null){
            $.mobile.changePage("#pageLogin", {
            transition: "pop",
            reverse: false,
            changeHash: false
        });
    }
});
</code>```

Still nothing appears,even on desktop (Chrome).

Is there any better way to do that?

UPDATE
The error message in firebug of $.mobile.changePage is
settings.pageContainer is undefined

答: The problem is at $(document).ready(function(){});.It seems that the jQuery mobile framework had not loaded at this stage.I have to use $("#pageMain").live("pagecreate", function() {}); instead.

Title: how to goto a page by code?

Body:
I tried using window.location="#pageLogin".
It works in my desktop but appears a blank in my android device.

After doing some search,I uses $.mobile.changePage like this

var user;
$(document).ready(function(){
    user=GetCurrUser();
    if(user==null){
            $.mobile.changePage("#pageLogin", {
            transition: "pop",
            reverse: false,
            changeHash: false
        });
    }
});

Still nothing appears,even on desktop (Chrome).

Is there any better way to do that?

UPDATE
The error message in firebug of $.mobile.changePage is
settings.pageContainer is undefined


问:
If I pull the data from BiqQuery, will Google charge me or not for sending the data to Data Studio?
If I pull the data from BiqQuery, will Google charge me or not for sending the data to Data Studio?</p>

答:
That depends.  BigQuery is a consumption based model, unless you purchased slots.  What that means is, any time you query you're utilizing resources and then getting charged at their defined rate, $5 per TB of data scanned.

There are a few caveats to that however one being that the first TB of data scanned per month is free, and not every query issued will scanned data as it may use cache.  If you are concerned about the associated cost one option would be to utilize the BigQuery sandbox.  It has limited functionality but will not charge you, however there are limitations.

https://cloud.google.com/bigquery/docs/quickstarts/quickstart-cloud-console


问:
Delete row from table using button - Bootstrap Table
I'm trying the row to be deleted when I click the delete icon in the table using bootstrap table.

My table:

```<code><table id="checkDataTable">
    <thead style="color: #31708f; background-color: #d9edf7 ">
        <tr>
            <th data-field="AssetReference">Referans</th>
            <th data-field="Customer">Müsteri</th>
            <th data-field="ReceiverCompanyName">Alici Firma</th>
            <th data-field="Tools" data-formatter="StatuFormatter">Islem</th>
        </tr>
    </thead>
</table>
</code>```

Javascript:

```<code>function StatuFormatter(value, row, index) {

    return "<a onclick='removeAssetEconomyCheckBillOfLadingRow()'><i class='fa fa-trash fa-2x' aria-hidden='true'></i></a>";
}

function removeAssetEconomyCheckBillOfLadingRow(id) {
    alert(id);
}
</code>```

It's fine until the removeAssetEconomyCheckBillOfLadingRow function.

How can I delete inside this function?

答:
First of all, you need to set id to  to identify the deleting row.

```<code><tr id="1"></tr>
</code>```

And get tr and remove

```<code>function removeAssetEconomyCheckBillOfLadingRow(id) {
    $('#checkDataTable').row($('#{{id}}'))).remove().draw();
}
</code>```

Body:
I'm trying the row to be deleted when I click the delete icon in the table using bootstrap table.

My table:

            Referans
            Müsteri
            Alici Firma
            Islem

Javascript:

function StatuFormatter(value, row, index) {

    return "";
}

function removeAssetEconomyCheckBillOfLadingRow(id) {
    alert(id);
}

It's fine until the removeAssetEconomyCheckBillOfLadingRow function.

How can I delete inside this function?

Body:
First of all, you need to set id to  to identify the deleting row.

<tr id="1"></tr>

And get tr and remove

function removeAssetEconomyCheckBillOfLadingRow(id) {
    $('#checkDataTable').row($('#{{id}}'))).remove().draw();
}


问:
Capture list of targets after cue
I am trying to create an expression that will retrieve a target or list of targets after a cue. I can currently get the first one, but I seem to be doing something wrong to get the repetitions. This is what I have so far:

```<code>import regex

text = "Some text cue: target, target, target and target. Other text."

expression = regex.compile(
fr"""
(?:cue)  # cue before targets. non capture (?:)
(?:.*?)  # text before the match. non capture (?:), as short as possible (?)
(target)
""",
re.VERBOSE,
)

matches = regex.findall(
    expression,
    text,
    overlapped=True,
)
</code>```

I have tried (target,\s)* but that is not working.

(Note that the real-use case will be more involved, where targets are actually a collection of strings, etc.)

The ideal output should be:

```<code>["target", "target", "target", "target"]
</code>```

答:
You can use

import regex

text = "Some text cue: target, target, target and target. Other text."

expression = regex.compile(fr"""
cue:  # cue before targets
(?:\s*(?:(?:,|\band\b)\s*)?(?P<targets>target))+
""",
regex.VERBOSE,
)

match = regex.search(expression, text)
if match:
    print( match.captures("targets") )

# => ['target', 'target', 'target', 'target']
```

See the Python demo.

The cue:(?:\s*(?:(?:,|\band\b)\s*)?(?P<targets>target))+ regex matches

cue: - a string

(?:\s*(?:(?:,|\band\b)\s*)?(?P<targets>target))+ - one or more sequences of

\s* - zero or more whitespaces

(?:(?:,|\band\b)\s*)? - an optional sequence of a comma or a whole word and followed with zero or more whitespaces

(?P<targets>target) - Group "targets" matching target

Title: Capture list of targets after cue

Body:
I am trying to create an expression that will retrieve a target or list of targets after a cue. I can currently get the first one, but I seem to be doing something wrong to get the repetitions. This is what I have so far:

import regex

text = "Some text cue: target, target, target and target. Other text."

expression = regex.compile(
fr"""
(?:cue)  # cue before targets. non capture (?:)
(?:.*?)  # text before the match. non capture (?:), as short as possible (?)
(target)
""",
re.VERBOSE,
)

matches = regex.findall(
    expression,
    text,
    overlapped=True,
)

I have tried (target,\s)* but that is not working.

(Note that the real-use case will be more involved, where targets are actually a collection of strings, etc.)

The ideal output should be:

["target", "target", "target", "target"]

Body:
You can use

import regex

text = "Some text cue: target, target, target and target. Other text."

expression = regex.compile(fr"""
cue:  # cue before targets
(?:\s*(?:(?:,|\band\b)\s*)?(?P<targets>target))+
""",
regex.VERBOSE,
)

match = regex.search(expression, text)
if match:
    print( match.captures("targets") )

# => ['target', 'target', 'target', 'target']

See the Python demo.

The cue:(?:\s*(?:(?:,|\band\b)\s*)?(?P<targets>target))+ regex matches

cue: - a string

(?:\s*(?:(?:,|\band\b)\s*)?(?P<targets>target))+ - one or more sequences of

\s* - zero or more whitespaces

(?:(?:,|\band\b)\s*)? - an optional sequence of a comma or a whole word and followed with zero or more whitespaces

(?P<targets>target) - Group "targets" matching target


问:
I need to install "docker pull bitnami/python:3.8.12-debian-10-r156" but I keep getting "permission denied"
the problem that pops

how can I install it? got to get this exact version...

答:
You can try to run docker command with sudo:

sudo docker pull bitnami/python:3.8.12-debian-10-r156

If you wanna make docker not requiring sudo, so you can run docker commands without sudo you have to run the following commands:

sudo usermod -aG docker $USER

newgrp docker