问:
Handle .net exceptions at application level
I was reading a couple of articles a while back which I think described a behaviour where you can, in a .net application (specifically VB.net), allow an exception to occur, and then handle it in some kind of application-level exception handler, as opposed to within a Try/Catch block.
My google-fu is weak at the moment, so I'm not having much luck guessing what this feature is called in order to find information about it.

If this rings a bell for any of you, can you point me in the right direction on what exactly the feature is called so that I can search for it?

Sample code is always welcome, of course, but this is mostly just a case of me forgetting the name of the feature and being unable to search for it.

答:
I believe you are looking for the AppDomain.UnhandledException event.  This will allow you to handle any exception that is unhandled in the AppDomain of your choice.  Most applications only have a single AppDomain so this code should do the trick

```<code>AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf MyHandler
</code>```

However, actually attempting to handle the event here is not the best idea.  This will fire for any exception thrown from any part of the code.  This could very easily be an exception that is fatal to some component you depend on and handling it could lead to further, worse errors down the road.

I usually use this event purely logging and error reporting scenarios.

Body:
I believe you are looking for the AppDomain.UnhandledException event.  This will allow you to handle any exception that is unhandled in the AppDomain of your choice.  Most applications only have a single AppDomain so this code should do the trick

AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf MyHandler

However, actually attempting to handle the event here is not the best idea.  This will fire for any exception thrown from any part of the code.  This could very easily be an exception that is fatal to some component you depend on and handling it could lead to further, worse errors down the road.

I usually use this event purely logging and error reporting scenarios.

OwnerDisplayName: JaredPar


来源: stackexchange

问:
RegEx Help, match long string, select substring
I want to match a url, but only want to select part of the url. Is that Possible?

IE: the url would look like this:

```<code>http://www.domain.com/link/88cbdgb7fwndkedl/
</code>```

My Regex looks like so:

```<code>@"http://www.domain.com/link/([a-zA-Z0-9]+)/"
</code>```

and I was hoping to only return the id, but instead its grabbing the whole url.

Any suggestions?

EDIT: using c# Regex.Matches()

答:
Match will be the entire url ( what is specified in the regex)

You need to extract the corresponding group.

Something like:

```<code>foreach(Match m in matches){
m.Groups[1];
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to match a url, but only want to select part of the url. Is that Possible?

IE: the url would look like this:

http://www.domain.com/link/88cbdgb7fwndkedl/

My Regex looks like so:

@"http://www.domain.com/link/([a-zA-Z0-9]+)/"

and I was hoping to only return the id, but instead its grabbing the whole url.

Any suggestions?

EDIT: using c# Regex.Matches()

Body:
Match will be the entire url ( what is specified in the regex)

You need to extract the corresponding group.

Something like:

foreach(Match m in matches){
m.Groups[1];
}


问:
How to fix 'Meta.fields' must not contain non-model field names: username for django graphene authentication endpoint
In my Django application I have created customer user model which uses email as username.

```<code>class UserManager(BaseUserManager):
    """Define a model manager for User model with no username field."""

    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        """Create and save a User with the given email and password."""
        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password=None, **extra_fields):
        """Create and save a regular User with the given email and password."""
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        """Create and save a SuperUser with the given email and password."""
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(email, password, **extra_fields)

class User(AbstractUser):
    username = None
    email = models.EmailField(_('email address'), unique=True,)

    user_id = models.UUIDField(
        default=uuid4,
        unique=True,
    )
</code>```

I am using graphene for APIs. For authentication endpoint I am following below steps,
https://django-graphql-auth.readthedocs.io/en/latest/quickstart/

I am keep getting below error,

```<code>sports_league-web-1  |   File "/usr/local/lib/python3.10/site-packages/django_filters/filterset.py", line 71, in __new__
sports_league-web-1  |     new_class.base_filters = new_class.get_filters()
sports_league-web-1  |   File "/usr/local/lib/python3.10/site-packages/django_filters/filterset.py", line 358, in get_filters
sports_league-web-1  |     raise TypeError(
sports_league-web-1  | TypeError: 'Meta.fields' must not contain non-model field names: username
</code>```

Kindly advise what I am doing wrong here. Let me know if any other details needed.

答:
This is how I solved this issue.

Modify the app settings file by adding below,

```<code>from graphql_auth.settings import DEFAULTS

DEFAULTS['LOGIN_ALLOWED_FIELDS'] = ['email']
DEFAULTS['REGISTER_MUTATION_FIELDS'] = ['email']
DEFAULTS['USER_NODE_FILTER_FIELDS'] = {
    'email': ['exact'],
    'is_active': ['exact'],
    'status__archived': ['exact'],
    'status__verified': ['exact'],
    'status__secondary_email': ['exact'],
}
GRAPHQL_AUTH = DEFAULTS
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In my Django application I have created customer user model which uses email as username.

class UserManager(BaseUserManager):
    """Define a model manager for User model with no username field."""

    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        """Create and save a User with the given email and password."""
        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password=None, **extra_fields):
        """Create and save a regular User with the given email and password."""
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        """Create and save a SuperUser with the given email and password."""
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(email, password, **extra_fields)

class User(AbstractUser):
    username = None
    email = models.EmailField(_('email address'), unique=True,)

    user_id = models.UUIDField(
        default=uuid4,
        unique=True,
    )

I am using graphene for APIs. For authentication endpoint I am following below steps,
https://django-graphql-auth.readthedocs.io/en/latest/quickstart/

I am keep getting below error,

sports_league-web-1  |   File "/usr/local/lib/python3.10/site-packages/django_filters/filterset.py", line 71, in __new__
sports_league-web-1  |     new_class.base_filters = new_class.get_filters()
sports_league-web-1  |   File "/usr/local/lib/python3.10/site-packages/django_filters/filterset.py", line 358, in get_filters
sports_league-web-1  |     raise TypeError(
sports_league-web-1  | TypeError: 'Meta.fields' must not contain non-model field names: username

Kindly advise what I am doing wrong here. Let me know if any other details needed.

Body:
This is how I solved this issue.

Modify the app settings file by adding below,

from graphql_auth.settings import DEFAULTS

DEFAULTS['LOGIN_ALLOWED_FIELDS'] = ['email']
DEFAULTS['REGISTER_MUTATION_FIELDS'] = ['email']
DEFAULTS['USER_NODE_FILTER_FIELDS'] = {
    'email': ['exact'],
    'is_active': ['exact'],
    'status__archived': ['exact'],
    'status__verified': ['exact'],
    'status__secondary_email': ['exact'],
}
GRAPHQL_AUTH = DEFAULTS


答:
Almost all regex solutions allow you to retrieve a group.  You'll find your parenthesized portion waiting for you in group 1.

If you are unable to bother with groups, then you can use positive look-behind:

```<code>(?<=http://www.domain.com/link/)[^/]+
</code>```

But honestly... try to use groups.  It's a nice feature.  :-)

In C#, it is:

```<code>Match match = Regex.Match(input, @"http://www.domain.com/link/([a-zA-Z0-9]+)/");

if (match.Success) {
   string key = match.Groups[1].Value;
}
</code>```

Title: RegEx Help, match long string, select substring

Body:
Almost all regex solutions allow you to retrieve a group.  You'll find your parenthesized portion waiting for you in group 1.

If you are unable to bother with groups, then you can use positive look-behind:

(?<=http://www.domain.com/link/)[^/]+

But honestly... try to use groups.  It's a nice feature.  :-)

In C#, it is:

Match match = Regex.Match(input, @"http://www.domain.com/link/([a-zA-Z0-9]+)/");

if (match.Success) {
   string key = match.Groups[1].Value;
}


问:
The useState is not being updated correctly in a loop
I am working on a certificate generator, where I have a list of name and i want to ithrate through those name and display them on a certificate, then download that certificate as a pdf. And then I move on to the next name and so on.

```<code>const _exportPdf = async () => {

    // if namelist is not uploaded
    if (nameList == null){
      console.log("Name List not uploaded");
      return;
    }

    // if name is uploaded
    Object.keys(nameList).forEach(async function(key){
      const name = nameList[key];
      // export the certificate as a pdf
      await html2canvas(document.querySelector("#capture")).then(canvas => {
        console.log("exporting "+name);
        setVisibleName(name);
        const imgData = canvas.toDataURL('image/png');
        const pdf = new jsPDF('l', 'pt', "a4");
        const imgProps= pdf.getImageProperties(imgData);
        var width = pdf.internal.pageSize.getWidth();
        var height = (imgProps.height * width) / imgProps.width;
        pdf.addImage(imgData, 'PNG', 0, 0,width, height);
        const filename = name + ".pdf";
        pdf.save(filename);
    })
   });

  }
</code>```

Currently I have 5 names in my sample nameList, when I use this function, I can see the name changeing on the certificate, but all the 5 downloaded certificates have "Sample Name" written on it (Sample Name is the default value of the visible name).

Need help.

答: First of all in forEach async-await doesn't work, as you would expect. So use for/ for of instead.

Body:
I am working on a certificate generator, where I have a list of name and i want to ithrate through those name and display them on a certificate, then download that certificate as a pdf. And then I move on to the next name and so on.

const _exportPdf = async () => {

    // if namelist is not uploaded
    if (nameList == null){
      console.log("Name List not uploaded");
      return;
    }

    // if name is uploaded
    Object.keys(nameList).forEach(async function(key){
      const name = nameList[key];
      // export the certificate as a pdf
      await html2canvas(document.querySelector("#capture")).then(canvas => {
        console.log("exporting "+name);
        setVisibleName(name);
        const imgData = canvas.toDataURL('image/png');
        const pdf = new jsPDF('l', 'pt', "a4");
        const imgProps= pdf.getImageProperties(imgData);
        var width = pdf.internal.pageSize.getWidth();
        var height = (imgProps.height * width) / imgProps.width;
        pdf.addImage(imgData, 'PNG', 0, 0,width, height);
        const filename = name + ".pdf";
        pdf.save(filename);
    })
   });

  }

Currently I have 5 names in my sample nameList, when I use this function, I can see the name changeing on the certificate, but all the 5 downloaded certificates have "Sample Name" written on it (Sample Name is the default value of the visible name).

Need help.


问:
Reading integers from binary file in Python
I'm trying to read a BMP file in Python. I know the first two bytes
indicate the BMP firm. The next 4 bytes are the file size. When I execute:

```<code>fin = open("hi.bmp", "rb")
firm = fin.read(2)
file_size = int(fin.read(4))
</code>```

I get:

ValueError: invalid literal for int() with base 10: 'F#\x13'

What I want to do is reading those four bytes as an integer, but it seems Python is reading them as characters and returning a string, which cannot be converted to an integer. How can I do this correctly?

答:
Here's a late solution but I though it might help.</p>
```<code>fin = open("hi.bmp", "rb")
firm = fin.read(2)
file_size = 0
for _ in range(4):
    (file_size << 8) += ord(fin.read(1))
</code>```

Body:
I'm trying to read a BMP file in Python. I know the first two bytes
indicate the BMP firm. The next 4 bytes are the file size. When I execute:

fin = open("hi.bmp", "rb")
firm = fin.read(2)
file_size = int(fin.read(4))

I get:

ValueError: invalid literal for int() with base 10: 'F#\x13'

What I want to do is reading those four bytes as an integer, but it seems Python is reading them as characters and returning a string, which cannot be converted to an integer. How can I do this correctly?

Body:
Here's a late solution but I though it might help.

fin = open("hi.bmp", "rb")
firm = fin.read(2)
file_size = 0
for _ in range(4):
    (file_size << 8) += ord(fin.read(1))


问:
how to provide a custom component with specific functions
I have a custom table with action buttons. I would like these buttons actions to trigger specific actions in the custom component.
Unfortunately I can't find any clean way to provide my custom table with functions, especially functions that use the attributes of my custom table. here is the table, the customized table.</p>

答:
I see you have an rolesListService injected to root, so I am going to use that to receive info what user has clicked on.

 <mat-menu #matMenu="matMenu">
      <button mat-menu-item (click)="onEditRow('rules')">
        rules
      </button>
      <button mat-menu-item (click)="onEditRow('configure')">
        configure
      </button>
      <button mat-menu-item (click)="onEditRow('notifications')">
        notifications
      </button>
    </mat-menu>
```
<pre class="lang-js prettyprint-override"><code>@Component({
  selector: 'app-roles-list',
  templateUrl: './roles-list.component.html',
  styleUrls: ['./roles-list.component.css'],
})
export class RolesListComponent implements OnInit {

  onEditRow(action: string) {
    this.roleListService.onClickAction.next(action)
  }

}
</code>```

Service will hold the latest action and emit this to all subscribers.

@Injectable({
  providedIn: 'root',
})
export class RolesListService {

  onClickAction = new ReplaySubject<string>(1);
  constructor() {}

}
```
<p>RolesPaneComponent will subscribe to it and use it.</p>
<pre class="lang-js prettyprint-override"><code>@Component({
  selector: 'app-roles-pane',
  templateUrl: './roles-pane.component.html',
  styleUrls: ['./roles-pane.component.css']
})
export class RolesPaneComponent implements OnInit {

  userClickedAction$: Observable<any> | undefined;

  constructor(private roleListService: RolesListService) { }

  ngOnInit() {
    this.userClickedAction$ = this.roleListService.onClickAction.pipe(data => {return data;})
  }

}
</code>```

I am roles panel, I have recieved info that user clicked: {{userClickedAction$ | async}}
```

Here is a working example: https://stackblitz.com/edit/angular-ivy-etcip4?file=src%2Fapp%2Froles-pane%2Froles-pane.component.html

Body:
I see you have an rolesListService injected to root, so I am going to use that to receive info what user has clicked on.

 <mat-menu #matMenu="matMenu">
      <button mat-menu-item (click)="onEditRow('rules')">
        <span>rules</span>
      </button>
      <button mat-menu-item (click)="onEditRow('configure')">
        <span>configure</span>
      </button>
      <button mat-menu-item (click)="onEditRow('notifications')">
        <span>notifications</span>
      </button>
    </mat-menu>

@Component({
  selector: 'app-roles-list',
  templateUrl: './roles-list.component.html',
  styleUrls: ['./roles-list.component.css'],
})
export class RolesListComponent implements OnInit {

  onEditRow(action: string) {
    this.roleListService.onClickAction.next(action)
  }

}

Service will hold the latest action and emit this to all subscribers.

@Injectable({
  providedIn: 'root',
})
export class RolesListService {

  onClickAction = new ReplaySubject<string>(1);
  constructor() {}

}

RolesPaneComponent will subscribe to it and use it.

@Component({
  selector: 'app-roles-pane',
  templateUrl: './roles-pane.component.html',
  styleUrls: ['./roles-pane.component.css']
})
export class RolesPaneComponent implements OnInit {

  userClickedAction$: Observable<any> | undefined;

  constructor(private roleListService: RolesListService) { }

  ngOnInit() {
    this.userClickedAction$ = this.roleListService.onClickAction.pipe(data => {return data;})
  }

}

I am roles panel, I have recieved info that user clicked: {{userClickedAction$ | async}}

Here is a working example: https://stackblitz.com/edit/angular-ivy-etcip4?file=src%2Fapp%2Froles-pane%2Froles-pane.component.html


答:
```<code>Match match = Regex.Match(input, @"http://www.domain.com/link/([a-zA-Z0-9]+)/")
string key = match.Groups[1].Value;
</code>```


问:
Prompting for user input (like Perl's $inp=<>) in Raku
How do we do Perl's  '

$inp=<>;

to prompt user a single line, in Raku ?

As lines(); keep on prompting a user input so not work identically

Please help clarify

答:
See get, which is an alias for lines(1), or something pretty close to that.

It initially surprised me how hard it is to discover in Raku resources -- doc, design doc, chat logs, etc. But I guess <> and line are so overloaded that it's not that odd after all.

I've added a comment about get's (lack of) discoverability in the doc issues queue. It would be helpful to those working on the doc if you added another comment in the same issue saying where you'd looked to get (!) an answer to your Q.


问:
How to optimize nonlinear funtion with some constraint in c++
I want to find a variable in C++ that allows a given nonlinear formula to have a maximum value in a constraint.

It is to calculate the maximum value of the formula below in the given constraint in C++.
You can also use the library.(e.g. Nlopt)

formula : ln(1+ax+by+c*z)

a, b, c are numbers input by the user

x, y, z are variables to be derived

variable constraint is that x, y, z are positive and x+y+z<=1

答:
This can actually be transformed into a linear optimization problem.

max ln(1+ax+by+cz) <--> max (ax+by+cz) s.t. ax+by+cz > -1

This means that it is a linear optimization problem (with one more constraint) that you can easily handle with whatever C++ methods together with your Convex Optimization knowledge.

Reminders to write a good code:

Check the validity of input value.

Since the input value can be negative, you need to consider this circumstance which can yield different results.

P.S.

This problem seems to be Off Topic on SO.

If it is your homework, it is for your own good to write the code yourself. Besides, we do not have enough time to write that for you.

This should have been a comment if I had more reputation.


问:
How to center scrollable content with header?
I'm trying to center some content. The content is larger than the parent and therefore requires scrolling. There is also a header at top. For some reason, the scroll height clips the scrollable content. Thoughts on how I should fix the issue?

Here's the fiddle: https://jsfiddle.net/xgsqyu45/

.app {
  height: 400px;
}

.header {
  width: 100%;
  height: 44px;
  background-color: grey;
  border: 2px solid;
}

.container {
  border: 1px solid red;
  height: 100%;
}

.scroll {
  overflow: scroll;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.content {
  height: 600px;
  width: 300px;
  margin: 12px;
  border: 2px solid blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="app">
  <div class="header">
  </div>
  <div class="container">
    <div class="scroll">
      <div class="content">
      </div>
    </div>
  </div>
</div></code>```

答:
The documentation says:

center

The flex items' margin boxes are centered within the line on the cross-axis. If the cross-size of an item is larger than the flex container, it will overflow equally in both directions.

The flex center is calculated using height 400px. So align-items: center is making the content overflow by 100px from top.

```<code> 100 = (600 - 400) / 2

here,
600 = content height
400 = .scroll and container height
</code>```

Notice how the .scroll gets 500px scrollHeight and not 600px. It's 100px less.

Solution:

We can transform the content if it is taller than the container using CSS calc() function. Assuming you want to keep shorter content at center we can use below solution. View it in 'full page' mode.

:root {
  --app-height: 400px;
  --content-margin-top: 12px;
}

* {
  box-sizing: border-box;
}

.app {
  height: var(--app-height);
}

.header {
  width: 100%;
  height: 44px;
  background-color: grey;
  border: 2px solid;
}

.container {
  border: 1px solid red;
  height: 100%;
  position: relative;
}

.scroll {
  overflow-y: scroll;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.content {
  height: 600px;
  width: 300px;
  margin: 12px;
  border: 2px solid blue;
  position: relative;

  transform: translateY(calc((max(100% + var(--content-margin-top), var(--app-height)) - var(--app-height)) / 2));
}

/* center lines for debugging */
.content::after {
  content: "-";
  color: blue;
  position: absolute;
  top: 50%;
  left: 0%;
  transform: translateY(-50%);
  width: 100%;
  border-bottom: 1px dashed rgba(0, 0, 255);
  line-height: 3px;
}

.container::after {
  content: "-";
  color: red;
  position: absolute;
  top: 50%;
  left: 0%;
  transform: translateY(-50%);
  width: 100%;
  border-bottom: 1px dashed rgba(255, 0, 0);
  line-height: 3px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="app">
  <div class=header></div>
  <div class="container">
    <div class="scroll">
      <div class="content">content1</div>
      <div class="content" style="height: 200px;">content2</div>
    </div>
  </div>
</div></code>```

Dashed lines mark the center for contents and container.

Update 10th Feb 2022 : Simple solution to cover the new requirements mentioned in comments.

 I think we are over complicating things. We just need margin:auto and flex-shrink:0 to address all the issues:

* {
  box-sizing: border-box;
}

.app {
  height: 400px;
  width: 80%;
  margin-bottom: 5rem;
}

.header {
  width: 100%;
  height: 44px;
  background-color: grey;
  border: 2px solid;
}

.container {
  border: 1px solid red;
  height: 100%;
  position: relative;
}

.scroll {
  overflow: auto;
  height: 100%;
  padding: 12px;
  display: flex;
}

.content {
  position: relative;
  border: 2px solid blue;

   margin: auto;
   flex-shrink: 0;
}

/* center lines for debugging */
.content::after {
  content: "-";
  color: blue;
  position: absolute;
  top: 50%;
  left: 0%;
  transform: translateY(-50%);
  width: 100%;
  border-bottom: 1px dashed rgba(0, 0, 255);
  line-height: 3px;
}

.container::after {
  content: "-";
  color: red;
  position: absolute;
  top: 50%;
  left: 0%;
  transform: translateY(-50%);
  width: 100%;
  border-bottom: 1px dashed rgba(255, 0, 0);
  line-height: 3px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>1. Small content</div>
<div class="app">
  <div class=header></div>
  <div class="container">
    <div class="scroll">
      <div class="content" style="height: 100px; width:100px;">content1</div>
    </div>
  </div>
</div>
<hr>
<div>2. Taller content</div>
<div class="app">
  <div class=header></div>
  <div class="container">
    <div class="scroll">
      <div class="content" style="height: 600px; width:100px;">content1</div>
    </div>
  </div>
</div>
<hr>
<div>3. Wider content</div>
<div class="app">
  <div class=header></div>
  <div class="container">
    <div class="scroll">
      <div class="content" style="height: 100px; width:120vw;">content1</div>
    </div>
  </div>
</div>

<hr>
<div>4. Taller and wider content</div>
<div class="app">
  <div class=header></div>
  <div class="container">
    <div class="scroll">
      <div class="content" style="height: 600px; width:120vw;">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Rem ad perspiciatis earum atque dolorum laborum corrupti animi? Dolor, laudantium! Non cupiditate in eligendi modi temporibus at maiores iste tempora accusantium dolorem quibusdam magnam
        totam, rem voluptatum distinctio sapiente debitis praesentium unde esse corporis perferendis id amet autem. Reprehenderit, non molestias?
      </div>
    </div>
  </div>
</div></code>```

In case 3, note scrollbars shifts content a little bit due to this issue. User agents handle scrollbar widths differently.

Body:
The documentation says:

center

The flex items' margin boxes are centered within the line on the cross-axis. If the cross-size of an item is larger than the flex container, it will overflow equally in both directions.

The flex center is calculated using height 400px. So align-items: center is making the content overflow by 100px from top.

 100 = (600 - 400) / 2

here,
600 = content height
400 = .scroll and container height

Notice how the .scroll gets 500px scrollHeight and not 600px. It's 100px less.

Solution:

We can transform the content if it is taller than the container using CSS calc() function. Assuming you want to keep shorter content at center we can use below solution. View it in 'full page' mode.

:root {
  --app-height: 400px;
  --content-margin-top: 12px;
}

* {
  box-sizing: border-box;
}

.app {
  height: var(--app-height);
}

.header {
  width: 100%;
  height: 44px;
  background-color: grey;
  border: 2px solid;
}

.container {
  border: 1px solid red;
  height: 100%;
  position: relative;
}

.scroll {
  overflow-y: scroll;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.content {
  height: 600px;
  width: 300px;
  margin: 12px;
  border: 2px solid blue;
  position: relative;

  transform: translateY(calc((max(100% + var(--content-margin-top), var(--app-height)) - var(--app-height)) / 2));
}

/* center lines for debugging */
.content::after {
  content: "-";
  color: blue;
  position: absolute;
  top: 50%;
  left: 0%;
  transform: translateY(-50%);
  width: 100%;
  border-bottom: 1px dashed rgba(0, 0, 255);
  line-height: 3px;
}

.container::after {
  content: "-";
  color: red;
  position: absolute;
  top: 50%;
  left: 0%;
  transform: translateY(-50%);
  width: 100%;
  border-bottom: 1px dashed rgba(255, 0, 0);
  line-height: 3px;
}

<div class="app">
  <div class=header></div>
  <div class="container">
    <div class="scroll">
      <div class="content">content1</div>
      <div class="content" style="height: 200px;">content2</div>
    </div>
  </div>
</div>

Dashed lines mark the center for contents and container.

Update 10th Feb 2022 : Simple solution to cover the new requirements mentioned in comments.

 I think we are over complicating things. We just need margin:auto and flex-shrink:0 to address all the issues:

* {
  box-sizing: border-box;
}

.app {
  height: 400px;
  width: 80%;
  margin-bottom: 5rem;
}

.header {
  width: 100%;
  height: 44px;
  background-color: grey;
  border: 2px solid;
}

.container {
  border: 1px solid red;
  height: 100%;
  position: relative;
}

.scroll {
  overflow: auto;
  height: 100%;
  padding: 12px;
  display: flex;
}

.content {
  position: relative;
  border: 2px solid blue;

   margin: auto;
   flex-shrink: 0;
}

/* center lines for debugging */
.content::after {
  content: "-";
  color: blue;
  position: absolute;
  top: 50%;
  left: 0%;
  transform: translateY(-50%);
  width: 100%;
  border-bottom: 1px dashed rgba(0, 0, 255);
  line-height: 3px;
}

.container::after {
  content: "-";
  color: red;
  position: absolute;
  top: 50%;
  left: 0%;
  transform: translateY(-50%);
  width: 100%;
  border-bottom: 1px dashed rgba(255, 0, 0);
  line-height: 3px;
}

<div>1. Small content</div>
<div class="app">
  <div class=header></div>
  <div class="container">
    <div class="scroll">
      <div class="content" style="height: 100px; width:100px;">content1</div>
    </div>
  </div>
</div>
<hr>
<div>2. Taller content</div>
<div class="app">
  <div class=header></div>
  <div class="container">
    <div class="scroll">
      <div class="content" style="height: 600px; width:100px;">content1</div>
    </div>
  </div>
</div>
<hr>
<div>3. Wider content</div>
<div class="app">
  <div class=header></div>
  <div class="container">
    <div class="scroll">
      <div class="content" style="height: 100px; width:120vw;">content1</div>
    </div>
  </div>
</div>

<hr>
<div>4. Taller and wider content</div>
<div class="app">
  <div class=header></div>
  <div class="container">
    <div class="scroll">
      <div class="content" style="height: 600px; width:120vw;">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Rem ad perspiciatis earum atque dolorum laborum corrupti animi? Dolor, laudantium! Non cupiditate in eligendi modi temporibus at maiores iste tempora accusantium dolorem quibusdam magnam
        totam, rem voluptatum distinctio sapiente debitis praesentium unde esse corporis perferendis id amet autem. Reprehenderit, non molestias?
      </div>
    </div>
  </div>
</div>

In case 3, note scrollbars shifts content a little bit due to this issue. User agents handle scrollbar widths differently.


问:
Creating an Image from a DIV
I've scoured Google and Stackoverflow and can't seem to come up with a definitive answer.

I'm wanting to create an image from a particular bit of content. So I've got a div which I've added images, text, background colours etc. to and I'm wanting to save out that DIV as an Image. I've read on GD and how to create each individual bit, like creating the canvas first, filling it with a colour, rendering the fonts etc...
What I'm wondering, is there not an easier way? It seems like a straight forward task but I appreciate it's not. Are there any libraries that you could recommend that will aid this? Rather than having to go through rendering each image, each bit of text and each colour on the canvas..

Thanks

答:
If you're looking for an online image editor to lay up ads, svg-edit may suit your requirements. This should get you most the way there.

There's a few services around too that do the job and you may even be able to leverage as a 3rd-party tool. I'm sure you can also appreciate their complexity.

Aviary

Sketchpad

Pixastic

Title: Creating an Image from a DIV


问:
Export multiple snowflake query result into separate CSV files
I have stored multiple snowflake queries in an excel file and i'm trying to write a python program to execute those queries and export the result set into different CSV files in my local path.
When I execute the program, it reads all the queries but exports only one query result into a CSV file.

```<code>from EXCEL_CONNECTION import * ---python program for snowflake connection
from SNOWFLAKE_CONNECTION import *--- python program for excel connection
import pandas

  cur = ctx.cursor()
  try:

     for row in ws.iter_rows(min_row=2, min_col=2):
        for cell in row:
          cur.execute(cell.value)
          #one_row = cur.fetchall()
          df = cur.fetch_pandas_all()
         df.to_csv(r"excel_output_path\table.csv")
 finally:
     cur.close()
  cur.close()
</code>```

I couldn't figure out the mistake I'm doing and would really need some help here to make this work

答:
you are writing all results to the same files, so they are overwriting each other</p>
```<code>df.to_csv(r"excel_output_path\table.csv")
</code>```
```<code>     count = 0
     for row in ws.iter_rows(min_row=2, min_col=2):
        for cell in row:
          cur.execute(cell.value)
          #one_row = cur.fetchall()
          df = cur.fetch_pandas_all()
         df.to_csv(r"excel_output_path\table" + str(count) + r".csv")
         count += 1
</code>```

Body:
I have stored multiple snowflake queries in an excel file and i'm trying to write a python program to execute those queries and export the result set into different CSV files in my local path.
When I execute the program, it reads all the queries but exports only one query result into a CSV file.

from EXCEL_CONNECTION import * ---python program for snowflake connection
from SNOWFLAKE_CONNECTION import *--- python program for excel connection
import pandas

  cur = ctx.cursor()
  try:

     for row in ws.iter_rows(min_row=2, min_col=2):
        for cell in row:
          cur.execute(cell.value)
          #one_row = cur.fetchall()
          df = cur.fetch_pandas_all()
         df.to_csv(r"excel_output_path\table.csv")
 finally:
     cur.close()
  cur.close()

I couldn't figure out the mistake I'm doing and would really need some help here to make this work

Body:
you are writing all results to the same files, so they are overwriting each other

df.to_csv(r"excel_output_path\table.csv")

     count = 0
     for row in ws.iter_rows(min_row=2, min_col=2):
        for cell in row:
          cur.execute(cell.value)
          #one_row = cur.fetchall()
          df = cur.fetch_pandas_all()
         df.to_csv(r"excel_output_path\table" + str(count) + r".csv")
         count += 1


问:
How to selectively show portions of an iframe website using HTML
How to selectively show portions of an iframe website using HTML? The current website shows the entire iframe website and needs scrolling when I choose the options on the table as shown.

But I want to show a particular portion of an iframe website without showing the other articles in the iframe website when I press on the option on the main website as shown below.

How do we pull this off? Thanks!

The code I used for the iframe website is:

```<code>
<!DOCTYPE html>
<html>
<style>
    body {
  background-image: url('20211121_175201.jpg');
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: cover;
}

p,h1 {color:white;}
</style>
<head>
<title>Wacky Ideas List of Ideas</title>
</head>
<body>

<table style="float: right;margin-right: 160px;display: none">
    <tr>
        <th>Wacky Ideas</th>
    </tr>
    <tr>
        <td><a href="#A1">Model Cardboard Jet Engine</a></td>
    </tr>
    <tr>
        <td><a href="#A2">Toy Electric Fan</a></td>
    </tr>
    <tr>
        <td><a href="#A3">Toy Model Car</a></td>
    </tr>
</table>

<h1 id="A1">Model Cardboard Jet Engine</h1>

<p style = "width: 100%;text-align: left">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc sit amet quam non erat luctus vehicula a id augue.....</p>
</p>

<hr>

<h1 id="A2">Toy Electric Fan</h1>

<p style = "width: 100%;text-align: left">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc sit amet quam non erat luctus vehicula a id augue....</p>

<hr>

<h1 id="A3">Toy Model Car</h1>

<p style = "width: 100%;text-align: left">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc sit amet quam non erat luctus vehicula a id augue.... </p>

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

The code I used for the main website is:

```<code><!DOCTYPE html>
<html>
<style>

    table,th,td{border: 1px solid white;color: white;height: 50px;font-size: 20px}
    body {
  background-image: url('20211121_175201.jpg');
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: cover;
}

p,h1 {color:white;}
</style>
<head>
<title>Wacky Ideas</title>
</head>
<body>

<h1 style="color: white;height: 50px">Wacky Ideas</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>

<table style="float: right;margin-right: 160px">
    <tr>
        <th>Wacky Ideas</th>
    </tr>
    <tr>
        <td><a href="file:///C:/Users/pc/Desktop/experimental%20website/wacky%20ideas%20list%20of%20ideas.html#A1" target="iframe_a">Model Cardboard Jet Engine</td>
    </tr>
    <tr>
        <td><a href="file:///C:/Users/pc/Desktop/experimental%20website/wacky%20ideas%20list%20of%20ideas.html#A2" target="iframe_a">Toy Electric Fan</td>
    </tr>
    <tr>
        <td><a href="file:///C:/Users/pc/Desktop/experimental%20website/wacky%20ideas%20list%20of%20ideas.html#A3" target="iframe_a">Toy Model Car</td>
    </tr>

</table>

<iframe src="file:///C:/Users/pc/Desktop/experimental%20website/wacky%20ideas%20list%20of%20ideas.html" name="iframe_a" height="1000px" width="1100px"></iframe>

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

Thank you all!

答:
It seems it's impossible to do it. An alternative is to making individual articles on individual webpages and just make it appear on the main website via iframe. It gets the job done.

Thank you!

Body:
How to selectively show portions of an iframe website using HTML? The current website shows the entire iframe website and needs scrolling when I choose the options on the table as shown.

But I want to show a particular portion of an iframe website without showing the other articles in the iframe website when I press on the option on the main website as shown below.

How do we pull this off? Thanks!

The code I used for the iframe website is:

<!DOCTYPE html>

<title>Wacky Ideas List of Ideas</title>

        Wacky Ideas

        Model Cardboard Jet Engine

        Toy Electric Fan

        Toy Model Car

Model Cardboard Jet Engine

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc sit amet quam non erat luctus vehicula a id augue.....

Toy Electric Fan

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc sit amet quam non erat luctus vehicula a id augue....

Toy Model Car

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc sit amet quam non erat luctus vehicula a id augue....

The code I used for the main website is:

<!DOCTYPE html>

<title>Wacky Ideas</title>

Wacky Ideas

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

        Wacky Ideas

        Model Cardboard Jet Engine

        Toy Electric Fan

        Toy Model Car

Thank you all!


问:
How to prevent WebView2(Edge based) to open a new window
Inside Webview2 when I open a new tab, a new window outside WindowsForms is open. I want to prevent this window to Open, how can I do that?</p>

答:
Just be careful about where you register the WebView.CoreWebView2.NewWindowRequested event..

I tried to use Browser.Initialized event in which handler I would register this event handler but that event is never raised.

I had to use Browser.CoreWebView2InitializationCompleted and now everything works just fine..


问:
How do you remove the last value in an array if it doesn't match the first value in the next array?
I might not be asking the right question here.

I'm retrieving bookings that have the first night and last night date and I'm trying to display on a calendar which dates are not available.

The date comes in as: firstNight: "2022-02-05" and currently, it needs to go out as Sat Feb 05 2022

In order to get a list of booked dates, I am doing the following:

```<code>const bookedDates = bedsData?.map(({ firstNight, lastNight }) => {
    const newArrivalDate = new Date(firstNight + "T00:00")
    const newDepartureDate = new Date(lastNight + "T24:00")

    var getDaysArray = function (start, end) {
      for (
        var arr = [], dt = new Date(start);
        dt <= end;
        dt.setDate(dt.getDate() + 1)
      ) {
        arr.push(new Date(dt).toDateString())
      }
      return arr
    }
    var daylist = getDaysArray(newArrivalDate, newDepartureDate)

    daylist?.map((v) => v)

    return daylist.join(", ")
  })
</code>```

This returns

```<code>0: undefined
1: "Sat Feb 05 2022, Sun Feb 06 2022, Mon Feb 07 2022, Tue Feb 08 2022, Wed Feb 09 2022, Thu Feb 10 2022, Fri Feb 11 2022, Sat Feb 12 2022"
2: undefined
3: "Sat Feb 12 2022, Sun Feb 13 2022, Mon Feb 14 2022, Tue Feb 15 2022, Wed Feb 16 2022, Thu Feb 17 2022, Fri Feb 18 2022, Sat Feb 19 2022"
4: "Sat Feb 19 2022, Sun Feb 20 2022, Mon Feb 21 2022, Tue Feb 22 2022, Wed Feb 23 2022, Thu Feb 24 2022, Fri Feb 25 2022, Sat Feb 26 2022"
5: undefined
6: undefined
7: "Sat Feb 26 2022, Sun Feb 27 2022, Mon Feb 28 2022, Tue Mar 01 2022, Wed Mar 02 2022, Thu Mar 03 2022, Fri Mar 04 2022, Sat Mar 05 2022"
8: "Sat Mar 05 2022, Sun Mar 06 2022, Mon Mar 07 2022, Tue Mar 08 2022, Wed Mar 09 2022, Thu Mar 10 2022, Fri Mar 11 2022, Sat Mar 12 2022"
9: undefined
10: undefined
11: "Fri Mar 25 2022, Sat Mar 26 2022, Sun Mar 27 2022, Mon Mar 28 2022, Tue Mar 29 2022"
</code>```

To show which dates are booked I'm am using

```<code>if (bookedDates.join().includes(calDates)) {
    style.textDecoration = "line-through"
    style.color = "rgba(0, 0, 0, 0.25)"
}
</code>```

The issue I'm facing is with dates that don't have a check out and check in on the same day. The "last day" and the "first day" of the next booking are still being included in the list of "bookedDates". However, they need to be "available" to check out or check in still.

I hope that makes sense... pretty lost with this one!

Thanks

答:
I presume that in new Date(lastNight + "T24:00") that lastNight is in the format YYYY-MM-DD. Because there is no offset, the string will be parsed as local and the date will be set to 00:00 on the following day, i.e. 2022-02-06T24:00 will create a date with an identical time value to 2022-02-07T00:00.

It seems your souce data is booked nights, which you want to do use to disable dates that can't be selected as checkout days. So wherever there is an un–booked night, the following day can be selected as a checkout day even if it's booked.

So when making the array of dates to disable, check for gaps and remove the first booked date. You'll have to deal with this in the UI to indicate that the date can't be booked for checkin.

Another method would be to create the booked nights array, then wherever there's a gap delete the following night as gaps must always be two dates. The first is available for check in only, the last for checkout only.

E.g.

// Parse YYYY-MM-DD as local, not UTC
function parseLocal(s) {
  let [y,m,d] = s.split(/\D/);
  return new Date(y, m-1, d);
}
// Format as YYYY-MM-DD
function format(date = new Date()) {
  return date.toLocaleDateString('en-CA'); // YYYY-MM-DD
}
// Add day to date (modifies date)
function addDay(date = new Date()) {
  date.setDate(date.getDate() + 1);
  return date;
}

let bookings = [
 {id: 0,
  firstNight: '2022-02-05',
  lastNight: '2022-02-09'
 },
 {id: 1,
  firstNight: '2022-02-10', // Contiguous booking, no gap
  lastNight: '2022-02-15'
 },
  {id: 2,
  firstNight: '2022-02-17', // Gap, 17th available for check out
  lastNight: '2022-02-20'
 },
  {id: 3,
  firstNight: '2022-02-21', // No gap, not avilable for checkout
  lastNight: '2022-02-21'
 },
  {id: 4,
  firstNight: '2022-02-22', // No gap, not avilable for checkout
  lastNight: '2022-02-22'
 },
  {id: 4,
  firstNight: '2022-02-24', // Gap, avilable for checkout
  lastNight: '2022-02-24'
 },
  {id: 4,
  firstNight: '2022-02-25', // No gap, not avilable for checkout
  lastNight: '2022-02-25'
 }
]

let bookedDates = bookings.map(
  ({firstNight, lastNight}) => [parseLocal(firstNight), parseLocal(lastNight)]
  ).reduce((dates, [firstNight, lastNight], i, mapDates) => {
    // If lastNight of previous booking is not prevNight,
    // don't add firstNight to array
    let prevBookedNight = i? mapDates[i-1][1] : null;
    if (i && format(addDay(prevBookedNight)) != format(firstNight)) {
      addDay(firstNight);
    }

  while (firstNight <= lastNight) {
    dates.push(format(firstNight));
    firstNight.setDate(firstNight.getDate() + 1);
  }
  return dates;
},[]);

console.log('Not available for check in or out:\n' + bookedDates.join('\n'));```

Body:
I might not be asking the right question here.

I'm retrieving bookings that have the first night and last night date and I'm trying to display on a calendar which dates are not available.

The date comes in as: firstNight: "2022-02-05" and currently, it needs to go out as Sat Feb 05 2022

In order to get a list of booked dates, I am doing the following:

const bookedDates = bedsData?.map(({ firstNight, lastNight }) => {
    const newArrivalDate = new Date(firstNight + "T00:00")
    const newDepartureDate = new Date(lastNight + "T24:00")

    var getDaysArray = function (start, end) {
      for (
        var arr = [], dt = new Date(start);
        dt <= end;
        dt.setDate(dt.getDate() + 1)
      ) {
        arr.push(new Date(dt).toDateString())
      }
      return arr
    }
    var daylist = getDaysArray(newArrivalDate, newDepartureDate)

    daylist?.map((v) => v)

    return daylist.join(", ")
  })

This returns

0: undefined
1: "Sat Feb 05 2022, Sun Feb 06 2022, Mon Feb 07 2022, Tue Feb 08 2022, Wed Feb 09 2022, Thu Feb 10 2022, Fri Feb 11 2022, Sat Feb 12 2022"
2: undefined
3: "Sat Feb 12 2022, Sun Feb 13 2022, Mon Feb 14 2022, Tue Feb 15 2022, Wed Feb 16 2022, Thu Feb 17 2022, Fri Feb 18 2022, Sat Feb 19 2022"
4: "Sat Feb 19 2022, Sun Feb 20 2022, Mon Feb 21 2022, Tue Feb 22 2022, Wed Feb 23 2022, Thu Feb 24 2022, Fri Feb 25 2022, Sat Feb 26 2022"
5: undefined
6: undefined
7: "Sat Feb 26 2022, Sun Feb 27 2022, Mon Feb 28 2022, Tue Mar 01 2022, Wed Mar 02 2022, Thu Mar 03 2022, Fri Mar 04 2022, Sat Mar 05 2022"
8: "Sat Mar 05 2022, Sun Mar 06 2022, Mon Mar 07 2022, Tue Mar 08 2022, Wed Mar 09 2022, Thu Mar 10 2022, Fri Mar 11 2022, Sat Mar 12 2022"
9: undefined
10: undefined
11: "Fri Mar 25 2022, Sat Mar 26 2022, Sun Mar 27 2022, Mon Mar 28 2022, Tue Mar 29 2022"

To show which dates are booked I'm am using

if (bookedDates.join().includes(calDates)) {
    style.textDecoration = "line-through"
    style.color = "rgba(0, 0, 0, 0.25)"
}

The issue I'm facing is with dates that don't have a check out and check in on the same day. The "last day" and the "first day" of the next booking are still being included in the list of "bookedDates". However, they need to be "available" to check out or check in still.

I hope that makes sense... pretty lost with this one!

Thanks


问:
How do I convert a .tlb file to headers and implementation files?
I'm trying to convert mscorlib.tlb.
It normally used in C++ like this:

```<code>#import "mscorlib.tlb" raw_interfaces_only              \
     high_property_prefixes("_get","_put","_putref")        \
     rename("ReportEvent", "InteropServices_ReportEvent")
</code>```

How can I convert it to headers and implementation files?

I was able to use Visual Studio to compile a dummy cpp file that contained the lines above, and it produced a .tlh file.  Shouldn't there also be implementation files?

答:
You can split implementation and declaration by using the "no_implementation" and "implementation_only" parameters to #import. These generate .tlh (type library header) and .tli (type library implementation) files.

I typically put the following into a header file (like stdafx.h):

```<code>#import "C:\Windows\Microsoft.NET\Framework64\v2.0.50727\mscorlib.tlb" no_implementation
</code>```

And the following into a .cpp file (like stdafx.cpp):

```<code>#import "C:\Windows\Microsoft.NET\Framework64\v2.0.50727\mscorlib.tlb" implementation_only
</code>```

Body:
I'm trying to convert mscorlib.tlb.
It normally used in C++ like this:

#import "mscorlib.tlb" raw_interfaces_only              \
     high_property_prefixes("_get","_put","_putref")        \
     rename("ReportEvent", "InteropServices_ReportEvent")

How can I convert it to headers and implementation files?

I was able to use Visual Studio to compile a dummy cpp file that contained the lines above, and it produced a .tlh file.  Shouldn't there also be implementation files?

Body:
You can split implementation and declaration by using the "no_implementation" and "implementation_only" parameters to #import. These generate .tlh (type library header) and .tli (type library implementation) files.

I typically put the following into a header file (like stdafx.h):

#import "C:\Windows\Microsoft.NET\Framework64\v2.0.50727\mscorlib.tlb" no_implementation

And the following into a .cpp file (like stdafx.cpp):

#import "C:\Windows\Microsoft.NET\Framework64\v2.0.50727\mscorlib.tlb" implementation_only


问:
starting my second data project and already ran into something I can't figure out
So I have a table with a column for active covid cases and another one for the city the cases are reported in. Now, I need to somehow sum all the cases for a given state on each day for each state. For example, I have 2 years of daily active covid cases from 100 cities. I would like to put them into "state buckets" for my analysis. Is there a way to do this in R? Appreciate the help!</p>

答:
With tidyverse you can group by the date and state, then use summarize and get the sum for each day.

```<code>library(tidyverse)

df %>%
  group_by(date, state) %>%
  summarize(sum = sum(active_cases))
</code>```

Output

```<code>  date       state        sum
  <date>     <chr>      <int>
1 2022-01-31 Alabama     6240
2 2022-01-31 New York   10004
3 2022-01-31 Washington  3384
4 2022-02-01 Alabama     6240
5 2022-02-01 New York   10004
6 2022-02-01 Washington  3384
</code>```

Data Table

```<code>dt <- df

setDT(dt)[, sum(active_cases), by = c("date", "state")]

         date      state    V1
1: 2022-01-31    Alabama  6240
2: 2022-02-01    Alabama  6240
3: 2022-01-31   New York 10004
4: 2022-02-01   New York 10004
5: 2022-01-31 Washington  3384
6: 2022-02-01 Washington  3384
</code>```

Data

```<code>df <- structure(list(date = structure(c(19023, 19023, 19023, 19023,
                                        19024, 19024, 19024, 19024, 19023, 19023, 19023, 19023, 19024,
                                        19024, 19024, 19024, 19023, 19023, 19023, 19023, 19024, 19024,
                                        19024, 19024), class = "Date"),
                     city = c("Birmingham", "Huntsville", "Mobile", "Montgomery", "Birmingham", "Huntsville", "Mobile",
                                                                                "Montgomery", "New York", "Buffalo", "Ithaca", "Long Island",
                                                                                "New York", "Buffalo", "Ithaca", "Long Island", "Seattle", "Olympia",
                                                                                "Ellensburg", "Spokane", "Seattle", "Olympia", "Ellensburg",
                                                                                "Spokane"),
                     state = c("Alabama", "Alabama", "Alabama", "Alabama", "Alabama", "Alabama", "Alabama", "Alabama", "New York", "New York",
                                                                                "New York", "New York", "New York", "New York", "New York", "New York",
                                                                                "Washington", "Washington", "Washington", "Washington", "Washington",
                                                                                "Washington", "Washington", "Washington"),
                     active_cases = c(1567L, 2340L, 1039L, 1294L, 1567L, 2340L, 1039L, 1294L, 3980L, 2390L, 2133L, 1501L, 3980L, 2390L, 2133L, 1501L, 567L, 1340L, 384L,
                                      1093L, 567L, 1340L, 384L, 1093L)), row.names = c(NA, -24L), class = "data.frame")

         date        city      state active_cases
1  2022-01-31  Birmingham    Alabama         1567
2  2022-01-31  Huntsville    Alabama         2340
3  2022-01-31      Mobile    Alabama         1039
4  2022-01-31  Montgomery    Alabama         1294
5  2022-02-01  Birmingham    Alabama         1567
6  2022-02-01  Huntsville    Alabama         2340
7  2022-02-01      Mobile    Alabama         1039
8  2022-02-01  Montgomery    Alabama         1294
9  2022-01-31    New York   New York         3980
10 2022-01-31     Buffalo   New York         2390
11 2022-01-31      Ithaca   New York         2133
12 2022-01-31 Long Island   New York         1501
13 2022-02-01    New York   New York         3980
14 2022-02-01     Buffalo   New York         2390
15 2022-02-01      Ithaca   New York         2133
16 2022-02-01 Long Island   New York         1501
17 2022-01-31     Seattle Washington          567
18 2022-01-31     Olympia Washington         1340
19 2022-01-31  Ellensburg Washington          384
20 2022-01-31     Spokane Washington         1093
21 2022-02-01     Seattle Washington          567
22 2022-02-01     Olympia Washington         1340
23 2022-02-01  Ellensburg Washington          384
24 2022-02-01     Spokane Washington         1093
</code>```

Body:
With tidyverse you can group by the date and state, then use summarize and get the sum for each day.

library(tidyverse)

df %>%
  group_by(date, state) %>%
  summarize(sum = sum(active_cases))

Output

  date       state        sum
  <date>     <chr>      <int>
1 2022-01-31 Alabama     6240
2 2022-01-31 New York   10004
3 2022-01-31 Washington  3384
4 2022-02-01 Alabama     6240
5 2022-02-01 New York   10004
6 2022-02-01 Washington  3384

Data Table

dt <- df

setDT(dt)[, sum(active_cases), by = c("date", "state")]

         date      state    V1
1: 2022-01-31    Alabama  6240
2: 2022-02-01    Alabama  6240
3: 2022-01-31   New York 10004
4: 2022-02-01   New York 10004
5: 2022-01-31 Washington  3384
6: 2022-02-01 Washington  3384

Data

df <- structure(list(date = structure(c(19023, 19023, 19023, 19023,
                                        19024, 19024, 19024, 19024, 19023, 19023, 19023, 19023, 19024,
                                        19024, 19024, 19024, 19023, 19023, 19023, 19023, 19024, 19024,
                                        19024, 19024), class = "Date"),
                     city = c("Birmingham", "Huntsville", "Mobile", "Montgomery", "Birmingham", "Huntsville", "Mobile",
                                                                                "Montgomery", "New York", "Buffalo", "Ithaca", "Long Island",
                                                                                "New York", "Buffalo", "Ithaca", "Long Island", "Seattle", "Olympia",
                                                                                "Ellensburg", "Spokane", "Seattle", "Olympia", "Ellensburg",
                                                                                "Spokane"),
                     state = c("Alabama", "Alabama", "Alabama", "Alabama", "Alabama", "Alabama", "Alabama", "Alabama", "New York", "New York",
                                                                                "New York", "New York", "New York", "New York", "New York", "New York",
                                                                                "Washington", "Washington", "Washington", "Washington", "Washington",
                                                                                "Washington", "Washington", "Washington"),
                     active_cases = c(1567L, 2340L, 1039L, 1294L, 1567L, 2340L, 1039L, 1294L, 3980L, 2390L, 2133L, 1501L, 3980L, 2390L, 2133L, 1501L, 567L, 1340L, 384L,
                                      1093L, 567L, 1340L, 384L, 1093L)), row.names = c(NA, -24L), class = "data.frame")

         date        city      state active_cases
1  2022-01-31  Birmingham    Alabama         1567
2  2022-01-31  Huntsville    Alabama         2340
3  2022-01-31      Mobile    Alabama         1039
4  2022-01-31  Montgomery    Alabama         1294
5  2022-02-01  Birmingham    Alabama         1567
6  2022-02-01  Huntsville    Alabama         2340
7  2022-02-01      Mobile    Alabama         1039
8  2022-02-01  Montgomery    Alabama         1294
9  2022-01-31    New York   New York         3980
10 2022-01-31     Buffalo   New York         2390
11 2022-01-31      Ithaca   New York         2133
12 2022-01-31 Long Island   New York         1501
13 2022-02-01    New York   New York         3980
14 2022-02-01     Buffalo   New York         2390
15 2022-02-01      Ithaca   New York         2133
16 2022-02-01 Long Island   New York         1501
17 2022-01-31     Seattle Washington          567
18 2022-01-31     Olympia Washington         1340
19 2022-01-31  Ellensburg Washington          384
20 2022-01-31     Spokane Washington         1093
21 2022-02-01     Seattle Washington          567
22 2022-02-01     Olympia Washington         1340
23 2022-02-01  Ellensburg Washington          384
24 2022-02-01     Spokane Washington         1093


问:
How to hide button when another button is clicked in React?
I have 2 buttons displayed on the page Display and Hide. When the Hide button is clicked I want to hide the Display button.

I am using useState. To some extent, I am able to hide Display more text present on the button, but not the whole button

Initial state- https://ibb.co/jMdH3tq

When the Hide button is clicked, Display text disappear but the button stays- https://ibb.co/Jm5FPNy

```<code>const [show, setShow] = useState(false);

const hideButton = () => {
  setShow(true);
};
</code>```

Hide button code:

```<code><div>
  <button
    style={{ marginLeft: '190px' }}
    className="button button1"
    onClick={() => {
      clearBooks();
      hideButton();
    }}
  >
    Hide
  </button>
</div>;
</code>```

Show button code:

```<code><button
  className="button button1"
  style={{ marginLeft: '190px', width: '124px', height: '50px' }}
  onClick={fetchBooks}
>
  {!show && 'Display more'}
</button>;
</code>```

答:
If you don't want to re-render, you can achieve this by using classes as follows:

screen.js

```<code>import "./styles.css"

export default function MyScreen() {
  const onButtonPressed = (target) => {
    document.querySelector('button.hide').classList.remove('hide')
    target.classList.add('hide')
  }
  return (
    <div>
      <button
        style={{ marginLeft: 190 }}
        className="button button1 hide"
        onClick={(element) => {
          onButtonPressed(element.target)
          clearBooks()
        }}
      >
        {"Hide"}
      </button>
    </div>
    <div>
      <button
        className="button button1"
        style={{ marginLeft: 190, width: 124, height: 50 }}
        onClick={(element) => {
          onButtonPressed(element.target)
          fetchBooks()
        }}
      >
        {"Display more"}
      </button>
    </div>
  )
}
</code>```

styles.css

```<code>button.hide {
  display: none;
}
</code>```

This is an example testing the JS functionality:

button.hide {
    display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
    <button
        class="button button1 hide"
        style="margin-left:190px;width:124px;height:50px"
        onClick="onButtonPressed(this)"
    >
        Hide
    </button>
</div>
<div>
    <button
        class="button button1"
        style="margin-left:190px;width:124px;height:50px"
        onClick="onButtonPressed(this)"
    >
        Display more
    </button>
</div>

<script>
    function onButtonPressed(element) {
        document.querySelector('button.hide').classList.remove('hide')
        element.classList.add('hide')
    }
</script></code>```

Body:
I have 2 buttons displayed on the page Display and Hide. When the Hide button is clicked I want to hide the Display button.

I am using useState. To some extent, I am able to hide Display more text present on the button, but not the whole button

Initial state- https://ibb.co/jMdH3tq

When the Hide button is clicked, Display text disappear but the button stays- https://ibb.co/Jm5FPNy

const [show, setShow] = useState(false);

const hideButton = () => {
  setShow(true);
};

Hide button code:

  <button
    style={{ marginLeft: '190px' }}
    className="button button1"
    onClick={() => {
      clearBooks();
      hideButton();
    }}
  >
    Hide
  </button>

;

Show button code:

<button
  className="button button1"
  style={{ marginLeft: '190px', width: '124px', height: '50px' }}
  onClick={fetchBooks}
>
  {!show && 'Display more'}
</button>;

Body:
If you don't want to re-render, you can achieve this by using classes as follows:

screen.js

import "./styles.css"

export default function MyScreen() {
  const onButtonPressed = (target) => {
    document.querySelector('button.hide').classList.remove('hide')
    target.classList.add('hide')
  }
  return (
    <div>
      <button
        style={{ marginLeft: 190 }}
        className="button button1 hide"
        onClick={(element) => {
          onButtonPressed(element.target)
          clearBooks()
        }}
      >
        {"Hide"}
      </button>
    </div>
    <div>
      <button
        className="button button1"
        style={{ marginLeft: 190, width: 124, height: 50 }}
        onClick={(element) => {
          onButtonPressed(element.target)
          fetchBooks()
        }}
      >
        {"Display more"}
      </button>
    </div>
  )
}

styles.css

button.hide {
  display: none;
}

This is an example testing the JS functionality:

button.hide {
    display: none;
}

<div>
    <button
        class="button button1 hide"
        style="margin-left:190px;width:124px;height:50px"
        onClick="onButtonPressed(this)"
    >
        Hide
    </button>
</div>
<div>
    <button
        class="button button1"
        style="margin-left:190px;width:124px;height:50px"
        onClick="onButtonPressed(this)"
    >
        Display more
    </button>
</div>

<script>
    function onButtonPressed(element) {
        document.querySelector('button.hide').classList.remove('hide')
        element.classList.add('hide')
    }
</script>


问:
How to pass argument to $store.getters with onclick event?
How to pass argument to $store.getters with onclick event? I can see the default value but not the new value. This is my code

```<code>const store = new Vuex.Store({
  state: {
    notes: [
      { id: 1, text: 'Hello World 1, Vuex!', deleted: false},
      { id: 2, text: 'Hello World 2, Vuex!', deleted: true},
      { id: 3, text: 'Hello World 3, Vuex!', deleted: false}
    ]
  },
  getters: {
    getNoteById: (state) => (id) => {
      return state.notes.find(note => note.id === id);
    }
  }
});

new Vue({
  el: "#app",
  data() {
    return {
      result: ''
    }
  },
  store,
  computed: {
    note() {
      return this.$store.getters.getNoteById(3);
    }
  },
  methods: {
    showText(id) {
      this.result = this.$store.getters.getNoteById(id);
    }
  }
});
</code>```

and html

```<code><div id='app'>
  <p>Default value: {{ note.text }}</p>
    <button @click="showText('1')">1</button>
    <button @click="showText('2')">2</button>
    <button @click="showText('3')">3</button>
  <p>New value: {{ result.text }}</p>
</div>
</code>```

答:
Your getter is working perfectly. And it correctly returns undefined when searching for any item with an id of '1', '2' or '3'.

Because the store doesn't contain any such item.

All your store items have number ids, none of them has a string id. See it working (I changed the template to send numbers):

Vue.config.productionTip = false;
Vue.config.devtools = false;
const store = new Vuex.Store({
  state: {
    notes: [
      { id: 1, text: 'Hello World 1, Vuex!', deleted: false},
      { id: 2, text: 'Hello World 2, Vuex!', deleted: true},
      { id: 3, text: 'Hello World 3, Vuex!', deleted: false}
    ]
  },
  getters: {
    getNoteById: (state) => (id) => {
      return state.notes.find(note => note.id === id);
    }
  }
});

new Vue({
  el: "#app",
  data() {
    return {
      result: ''
    }
  },
  store,
  computed: {
    note() {
      return this.$store.getters.getNoteById(3);
    }
  },
  methods: {
    showText(id) {
      this.result = this.$store.getters.getNoteById(id);
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.14/vue.js"></script>
<script src="https://unpkg.com/vuex"></script>

<div id='app'>
  <p>Default value: {{ note.text }}</p>
    <button @click="showText(1)">1</button>
    <button @click="showText(2)">2</button>
    <button @click="showText(3)">3</button>
  <p>New value: {{ result.text }}</p>
</div></code>```

If, for any reason, you don't have control over the incoming type (you might have this problem when reading the value of an <input>, which is always a string, even when the type of the input is "number"), you might want to cast the value as number: +'5' => 5.

So, as an alternative to fixing the template, as above, you could do this in the method:

```<code> showText(id) {
   this.result = this.$store.getters.getNoteById(+id);
 }
</code>```

Body:
How to pass argument to $store.getters with onclick event? I can see the default value but not the new value. This is my code

const store = new Vuex.Store({
  state: {
    notes: [
      { id: 1, text: 'Hello World 1, Vuex!', deleted: false},
      { id: 2, text: 'Hello World 2, Vuex!', deleted: true},
      { id: 3, text: 'Hello World 3, Vuex!', deleted: false}
    ]
  },
  getters: {
    getNoteById: (state) => (id) => {
      return state.notes.find(note => note.id === id);
    }
  }
});

new Vue({
  el: "#app",
  data() {
    return {
      result: ''
    }
  },
  store,
  computed: {
    note() {
      return this.$store.getters.getNoteById(3);
    }
  },
  methods: {
    showText(id) {
      this.result = this.$store.getters.getNoteById(id);
    }
  }
});

and html

Default value: {{ note.text }}

    <button @click="showText('1')">1</button>
    <button @click="showText('2')">2</button>
    <button @click="showText('3')">3</button>

New value: {{ result.text }}

Body:
Your getter is working perfectly. And it correctly returns undefined when searching for any item with an id of '1', '2' or '3'.

Because the store doesn't contain any such item.

All your store items have number ids, none of them has a string id. See it working (I changed the template to send numbers):

Vue.config.productionTip = false;
Vue.config.devtools = false;
const store = new Vuex.Store({
  state: {
    notes: [
      { id: 1, text: 'Hello World 1, Vuex!', deleted: false},
      { id: 2, text: 'Hello World 2, Vuex!', deleted: true},
      { id: 3, text: 'Hello World 3, Vuex!', deleted: false}
    ]
  },
  getters: {
    getNoteById: (state) => (id) => {
      return state.notes.find(note => note.id === id);
    }
  }
});

new Vue({
  el: "#app",
  data() {
    return {
      result: ''
    }
  },
  store,
  computed: {
    note() {
      return this.$store.getters.getNoteById(3);
    }
  },
  methods: {
    showText(id) {
      this.result = this.$store.getters.getNoteById(id);
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.14/vue.js"></script>
<script src="https://unpkg.com/vuex"></script>

<div id='app'>
  <p>Default value: {{ note.text }}</p>
    <button @click="showText(1)">1</button>
    <button @click="showText(2)">2</button>
    <button @click="showText(3)">3</button>
  <p>New value: {{ result.text }}</p>
</div>

If, for any reason, you don't have control over the incoming type (you might have this problem when reading the value of an <input>, which is always a string, even when the type of the input is "number"), you might want to cast the value as number: +'5' => 5.

So, as an alternative to fixing the template, as above, you could do this in the method:

 showText(id) {
   this.result = this.$store.getters.getNoteById(+id);
 }


问:
Using nodejs passport for multiple OAuth2.0 methods to login to the same account
Im trying to use passport to use OAuth2 to login but I'm not fully understanding the documentation.

My end goal is to have the front page of my website to have multiple login options via twitch/google/facebook that all lead you to the same account if you email happens to match. (example service that does this: streamlabs login) I want to do this without using a username and password so each of my DB docs only have a unique ID to identify each account and subsequent objects keys as twitch/google/facebook containing API tokens and emails.

The part I dont understand is how to tell passport to identify the same DB doc when the user is logged in, from what I think it could be is the callback for the passport strategy registration where you use done(null, profile) to tell passport they have been successfully authed.

Would I have to change  profile to the unique DB doc ID to make it universal accross all auth methods?

答: Turns out I was right, was hoping for an answer earlier before I had to change a bunch of my code</p>


问:
StreamBuilder The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type
```<code>                StreamBuilder<QuerySnapshot>(
                stream: _fire.collection('messages').snapshots(),
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    final messages = snapshot.data!.docs;
                    List<Text> messageWidgets = [];
                    for (var message in messages) {
                      final messageText = message.get('text');
                      final messageSender = message.get('sender');

                      final messageWidget =
                          Text('$messageText from $messageSender');
                      messageWidgets.add(messageWidget);
                    }
                    return Column(
                      children: messageWidgets,
                    );
                  }
                },
              ),
</code>```

builder:(context, snapshot){ starting bracket show this error:
The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type
Try adding either a return or a throw statement at the end.

答:
The idea is to make sure the body of your StreamBuilder returns a Widget that is non-nullable, and because your return statement is nested within your if statement makes it conditional so assuming the if statement returns false or the data you are requesting isn't available the body of your StreamBuilder would return null and that's why you have the above error.

Here is a piece of you could try:

```<code>class Sample extends StatelessWidget {
  const Sample({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: _fire.collection('messages').snapshots(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          final messages = snapshot.data!.docs;
          List<Text> messageWidgets = [];
          for (var message in messages) {
            final messageText = message.get('text');
            final messageSender = message.get('sender');

            final messageWidget =
            Text('$messageText from $messageSender');
            messageWidgets.add(messageWidget);
          }
        }
        return Column(
          children: messageWidgets,
        );
      },
    );
  }
}
</code>```

additionally you want to check the ConnectionState of the resulting snapshot to help create a meaningful flow so you can have to Loading Indicator of your choice show up while your data is being loaded and neatly show the requested data when it becomes available

Body:
                StreamBuilder<QuerySnapshot>(
                stream: _fire.collection('messages').snapshots(),
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    final messages = snapshot.data!.docs;
                    List<Text> messageWidgets = [];
                    for (var message in messages) {
                      final messageText = message.get('text');
                      final messageSender = message.get('sender');

                      final messageWidget =
                          Text('$messageText from $messageSender');
                      messageWidgets.add(messageWidget);
                    }
                    return Column(
                      children: messageWidgets,
                    );
                  }
                },
              ),

builder:(context, snapshot){ starting bracket show this error:
The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type
Try adding either a return or a throw statement at the end.

Body:
The idea is to make sure the body of your StreamBuilder returns a Widget that is non-nullable, and because your return statement is nested within your if statement makes it conditional so assuming the if statement returns false or the data you are requesting isn't available the body of your StreamBuilder would return null and that's why you have the above error.

Here is a piece of you could try:

class Sample extends StatelessWidget {
  const Sample({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: _fire.collection('messages').snapshots(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          final messages = snapshot.data!.docs;
          List<Text> messageWidgets = [];
          for (var message in messages) {
            final messageText = message.get('text');
            final messageSender = message.get('sender');

            final messageWidget =
            Text('$messageText from $messageSender');
            messageWidgets.add(messageWidget);
          }
        }
        return Column(
          children: messageWidgets,
        );
      },
    );
  }
}

additionally you want to check the ConnectionState of the resulting snapshot to help create a meaningful flow so you can have to Loading Indicator of your choice show up while your data is being loaded and neatly show the requested data when it becomes available


问:
WebView: Maintain Background Image Aspect
I have a WebView app that is used to load a remote web page. I have set a background image to be displayed before the web page is fully loaded.

activity_main.xml:

```<code>...
<WebView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/clientWebView"
    android:background="@drawable/splash"
...
</code>```

MyClient.java:

```<code>...
WebView clientView = (WebView) mainActivity.findViewById(R.id.clientWebView);
clientView.setBackgroundColor(android.graphics.Color.TRANSPARENT);
WebSettings viewSettings = clientView.getSettings();
viewSettings.setJavaScriptEnabled(true);
viewSettings.setLoadWithOverviewMode(true);
viewSettings.setUseWideViewPort(true);
...
</code>```

The issue is that the background image is stretched/squished, especially in portrait mode. I have been looking for an answer on StackOverflow & Google but have not come across anything that works.

答:
Yes, background of any view will always fit to the screen dimensions.

Which will cause the image to stretch out.

Best thing is you need to add an ImageView behind the WebView and set image as its src

Then,

Add the following line to your ImageView

```<code>android:scaleType="centerCrop"
</code>```

This ensures that your Image does not stretch out

Body:
I have a WebView app that is used to load a remote web page. I have set a background image to be displayed before the web page is fully loaded.

activity_main.xml:

...
<WebView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/clientWebView"
    android:background="@drawable/splash"
...

MyClient.java:

...
WebView clientView = (WebView) mainActivity.findViewById(R.id.clientWebView);
clientView.setBackgroundColor(android.graphics.Color.TRANSPARENT);
WebSettings viewSettings = clientView.getSettings();
viewSettings.setJavaScriptEnabled(true);
viewSettings.setLoadWithOverviewMode(true);
viewSettings.setUseWideViewPort(true);
...

The issue is that the background image is stretched/squished, especially in portrait mode. I have been looking for an answer on StackOverflow & Google but have not come across anything that works.

Body:
Yes, background of any view will always fit to the screen dimensions.

Which will cause the image to stretch out.

Best thing is you need to add an ImageView behind the WebView and set image as its src

Then,

Add the following line to your ImageView

android:scaleType="centerCrop"

This ensures that your Image does not stretch out


问:
Try Catch outside of: await Task.Run(()
Does try catch outside of: await Task.Run(() => make sense or just use them only inside of await?

```<code>private async void Test()
{
     try
     {
         await Task.Run(() =>
         {
             try
             {
                  DoingSomething();
             }
             catch (Exception ex)
             {
                  log.Error(ex.Message);
             }
         });
      }
      catch (Exception ex)
      {
          log.Error(ex.Message);
      }
}
</code>```

答:
This is the behavior in .Net 6:

```<code>try{
 await Task.Run(()=>   & call whatever method    );
}
catch { handle the exception }          <-- the catch will never get hit. An unhandled exception in the Task.Run line will happen
</code>```

However, this will work:

```<code>try{
await Task.Run(async ()=> & call some method );
}
catch(Exception ex){
   handle the exception
}
</code>```

The async before the ()=> has to be there for .Net 6

I've just confirmed this.

Title: Try Catch outside of: await Task.Run(()

Body:
Does try catch outside of: await Task.Run(() => make sense or just use them only inside of await?

private async void Test()
{
     try
     {
         await Task.Run(() =>
         {
             try
             {
                  DoingSomething();
             }
             catch (Exception ex)
             {
                  log.Error(ex.Message);
             }
         });
      }
      catch (Exception ex)
      {
          log.Error(ex.Message);
      }
}

Body:
This is the behavior in .Net 6:

try{
 await Task.Run(()=>   & call whatever method    );
}
catch { handle the exception }          <-- the catch will never get hit. An unhandled exception in the Task.Run line will happen

However, this will work:

try{
await Task.Run(async ()=> & call some method );
}
catch(Exception ex){
   handle the exception
}

The async before the ()=> has to be there for .Net 6

I've just confirmed this.


问:
How should the lodash flow function be typed in typescript?
lodash.flow combines two or more functions.

lodash.flow(double, addTwo) would return a function the would double and add two. How should this function be typed in typescript (the current definition just returns Function)?

declare function flow<In, Intermediate, Out>(f1: (a1: In) => Intermediate, f2: (a1: Intermediate) => Out): (a1: In)=> Out works for two functions with the first having one input argument. I'm not sure how to extend the definition to work in all cases.

My attempt can support mulitple functions if called like this:

lodash.flow(f1, lodash.flow(f2, f3))

but am looking for

lodash.flow(f1, f2, f3)

答:
here's a way to kind of do it using conditional types:

const compose =
  <T1, T2>(f1: (p: T1) => T2) =>
  <T3>(f2: (p: T2) => T3) =>
  (p: T1) =>
    f2(f1(p));

const flow = <T1, T2, T3 = "♘", T4 = "♘">(
  f0: (p: T1) => T2,
  ...f: [] | [(p: T2) => T3] | [(p: T2) => T3, (p: T3) => T4]
): ((p: T1) => T3 extends "♘" ? T2 : T4 extends "♘" ? T3 : T4) => {
  if (f[1]) {
    return compose(compose(f0)(f[0]!))(f[1]) as any;
  }

  if (f[0]) {
    return compose(f0)(f[0]) as any;
  }

  return f0 as any;
};
```

in this example, flow supports up to 3 args, but it can be extended to as many as you like.

Body:
here's a way to kind of do it using conditional types:

const compose =
  <T1, T2>(f1: (p: T1) => T2) =>
  <T3>(f2: (p: T2) => T3) =>
  (p: T1) =>
    f2(f1(p));

const flow = <T1, T2, T3 = "♘", T4 = "♘">(
  f0: (p: T1) => T2,
  ...f: [] | [(p: T2) => T3] | [(p: T2) => T3, (p: T3) => T4]
): ((p: T1) => T3 extends "♘" ? T2 : T4 extends "♘" ? T3 : T4) => {
  if (f[1]) {
    return compose(compose(f0)(f[0]!))(f[1]) as any;
  }

  if (f[0]) {
    return compose(f0)(f[0]) as any;
  }

  return f0 as any;
};

in this example, flow supports up to 3 args, but it can be extended to as many as you like.


问:
Laravel observer not attaching on pivot table
I have a Category Model which has a parent relation to itself:

```<code>public function parent()
{
    return $this->belongsTo('App\Models\Category', 'parent_id', 'id');
}
</code>```

and a ManyToMany relation to FieldCategory

```<code>public function fieldcategories()
{
    return $this->belongsToMany('App\Models\FieldCategory');
}
</code>```

And I have a CategoryObserver to observe if there are any changes of parent (ex. if a category was moved to subcategory) if threre was a change I want to attach parent FielCategory entries to subcategory

```<code>public function updated(Category $category)
{
    if($category->parent_id != null) {
        $this->updateFieldCategories($category);
    }
}
public function updateFieldCategories(Category $category)
{

    $category->fieldcategories()->detach();

    $parent = \App\Models\Category::find($category->parent->id);

    $parentFieldCategoriesArray = [];
    foreach ($parent->fieldcategories as $parentCat)
    {
        $parentFieldCategoriesArray[] = $parentCat->id;
    }
    $category->fieldcategories()->attach($parentFieldCategoriesArray);
}
</code>```

And it works fine on updated! But when I try to do exact thing on created (when it has parent selected) it fails, and I have no idea why?
I've try to debug this function and $parentFieldCategoriesArray is filled with necessary ID's. It looks like the $category->fieldcategories()->attach() method is not firing and I don't know why.
There are no records in the pivot table on created and on updated it works fine.
I'm using Laravel 5.6

Any help please?

UPDATE:
As requested this is my created function

```<code>public function created(Category $category)
{
    \Log::debug('PARENT: '.$category->parent_id);
    if($category->parent_id != null) {
        $this->updateFieldCategories($category);
    }
}
</code>```

答:
Just add:

```<code>public $afterCommit = true;
</code>```

at the beginning of the observer class.. It will wait until the transactions are done, then save your attaching or detaching..

Please check Laravel's documentation for that.

Body:
I have a Category Model which has a parent relation to itself:

public function parent()
{
    return $this->belongsTo('App\Models\Category', 'parent_id', 'id');
}

and a ManyToMany relation to FieldCategory

public function fieldcategories()
{
    return $this->belongsToMany('App\Models\FieldCategory');
}

And I have a CategoryObserver to observe if there are any changes of parent (ex. if a category was moved to subcategory) if threre was a change I want to attach parent FielCategory entries to subcategory

public function updated(Category $category)
{
    if($category->parent_id != null) {
        $this->updateFieldCategories($category);
    }
}
public function updateFieldCategories(Category $category)
{

    $category->fieldcategories()->detach();

    $parent = \App\Models\Category::find($category->parent->id);

    $parentFieldCategoriesArray = [];
    foreach ($parent->fieldcategories as $parentCat)
    {
        $parentFieldCategoriesArray[] = $parentCat->id;
    }
    $category->fieldcategories()->attach($parentFieldCategoriesArray);
}

And it works fine on updated! But when I try to do exact thing on created (when it has parent selected) it fails, and I have no idea why?
I've try to debug this function and $parentFieldCategoriesArray is filled with necessary ID's. It looks like the $category->fieldcategories()->attach() method is not firing and I don't know why.
There are no records in the pivot table on created and on updated it works fine.
I'm using Laravel 5.6

Any help please?

UPDATE:
As requested this is my created function

public function created(Category $category)
{
    \Log::debug('PARENT: '.$category->parent_id);
    if($category->parent_id != null) {
        $this->updateFieldCategories($category);
    }
}

Body:
Just add:

public $afterCommit = true;

at the beginning of the observer class.. It will wait until the transactions are done, then save your attaching or detaching..

Please check Laravel's documentation for that.


问:
read_csv differences between different Jupyter Notebooks
I have the following code which works fine in Google Colab, but throws an error when run in QuantConnect's Jupyter Notebook on their site.  Any idea why this could be and how to make it work within the QuantConnect notebook?

```<code>import pandas as pd
url = 'https://raw.githubusercontent.com/QuantConnect/Lean/master/Data/symbol-properties/symbol-properties-database.csv'
df = pd.read_csv(url)
df.head()
</code>```

The error it is giving below. Seems like maybe something with the encoding is the issue, but I've tried setting various encodings into the read_csv function with nothing working.

```<code>---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
/opt/miniconda3/lib/python3.6/urllib/request.py in do_open(self, http_class, req, **http_conn_args)
   1317                 h.request(req.get_method(), req.selector, req.data, headers,
-> 1318                           encode_chunked=req.has_header('Transfer-encoding'))
   1319             except OSError as err: # timeout error
</code>```

答:
Do you have the same error with the following code?

import io
import pandas as pd
import requests

res = requests.get(r'https://raw.githubusercontent.com/QuantConnect/Lean/master/Data/symbol-properties/symbol-properties-database.csv')
text_csv = res.text
df = pd.read_csv(io.StringIO(text_csv))
```

Body:
I have the following code which works fine in Google Colab, but throws an error when run in QuantConnect's Jupyter Notebook on their site.  Any idea why this could be and how to make it work within the QuantConnect notebook?

import pandas as pd
url = 'https://raw.githubusercontent.com/QuantConnect/Lean/master/Data/symbol-properties/symbol-properties-database.csv'
df = pd.read_csv(url)
df.head()

The error it is giving below. Seems like maybe something with the encoding is the issue, but I've tried setting various encodings into the read_csv function with nothing working.

---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
/opt/miniconda3/lib/python3.6/urllib/request.py in do_open(self, http_class, req, **http_conn_args)
   1317                 h.request(req.get_method(), req.selector, req.data, headers,
-> 1318                           encode_chunked=req.has_header('Transfer-encoding'))
   1319             except OSError as err: # timeout error


问:
xvfb-run unreliable when multiple instances invoked in parallel
Can you help me, why I get sometimes (50:50):

```<code>webkit_server.NoX11Error: Cannot connect to X. You can try running with xvfb-run.
</code>```

When I start the script in parallel as:

```<code>xvfb-run -a python script.py
</code>```

You can reproduce this yourself like so:

```<code>for ((i=0; i<10; i++)); do
  xvfb-run -a xterm &
done
</code>```

Of the 10 instances of xterm this starts, 9 of them will typically fail, exiting with the message Xvfb failed to start.

答:
This questions was asked in 2015.

In my version of xvfb (2:1.20.13-1ubuntu1~20.04.2), this problem has been fixed.

It looks at /tmp/.X*-lock to find an available port, and then runs Xvfb. If Xvfb fails to start, it finds a new port and retries, up to 10 times.

Body:
Can you help me, why I get sometimes (50:50):

webkit_server.NoX11Error: Cannot connect to X. You can try running with xvfb-run.

When I start the script in parallel as:

xvfb-run -a python script.py

You can reproduce this yourself like so:

for ((i=0; i<10; i++)); do
  xvfb-run -a xterm &
done

Of the 10 instances of xterm this starts, 9 of them will typically fail, exiting with the message Xvfb failed to start.


问:
Copy select items from one folder to a new folder
I am getting all wav files in the past 24 hours from one folder and putting them in another folder. I swear this worked for me a bit ago and wanted to add in some more conditional statements but now it is working. It is not creating a new folder for 'NewSounds' it is just creating a blank document named that, and I am stumped. Also any tips on best place to put a pipeline for only selecting the -Top 10 results once filtered down from the .wav files recently added??</p>
```<code>$scriptPath = "/Users/robertunderwood/Splice/sounds/"
$Destination = "/Users/robertunderwood/NewSounds"
$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.wav

    foreach($file in $fileNames){
        if ($file.LastWriteTime -ge (Get-Date).AddDays(-1)){
            Write-Host $file.Name
            Copy-Item $file -Destination $Destination
    }
 }
</code>```

答:
Continuing from my comment...

You can always just create the folder and copy to it:

```<code>$scriptPath = "/Users/robertunderwood/Splice/sounds/"
$Destination = "/Users/robertunderwood/NewSounds"
Get-ChildItem -Path $scriptPath -Filter "*.wav" -Recurse |
    Where-Object -FilterScript { $_.LastWriteTime -ge (Get-Date).AddDays(-1).Date } |
    Select-Object -First 10 | ForEach-Object -Begin {
        if (-not(Test-Path -Path $Destination -PathType Container)) {
            New-Item -Path $Destination -ItemType Container | Out-Null
        }
    } -Process {
        Copy-Item -Path $_.FullName -Destination $Destination
    }
</code>```

Swapped your if statement to Where-Object to streamline the process. Also selected the top (first) 10 files found to copy.

You're expecting Copy-Item to create the folder and copy the files for you and that's where your issue occurs. Copy-Item can in fact create the folder first, then recursively copy to it when providing the -Recurse switch but, not when it's piped to it (... | Copy-Item); this includes even providing the -Force switch. So the alternative is to use the Foreach-Object cmdlet to create the folder first (in your Begin block), then copy to it. You can honestly create it whenever, wherever, using other methods, as long as it's not before the actual copying.

Body:
I am getting all wav files in the past 24 hours from one folder and putting them in another folder. I swear this worked for me a bit ago and wanted to add in some more conditional statements but now it is working. It is not creating a new folder for 'NewSounds' it is just creating a blank document named that, and I am stumped. Also any tips on best place to put a pipeline for only selecting the -Top 10 results once filtered down from the .wav files recently added??

$scriptPath = "/Users/robertunderwood/Splice/sounds/"
$Destination = "/Users/robertunderwood/NewSounds"
$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.wav

    foreach($file in $fileNames){
        if ($file.LastWriteTime -ge (Get-Date).AddDays(-1)){
            Write-Host $file.Name
            Copy-Item $file -Destination $Destination
    }
 }

Body:
Continuing from my comment...

You can always just create the folder and copy to it:

$scriptPath = "/Users/robertunderwood/Splice/sounds/"
$Destination = "/Users/robertunderwood/NewSounds"
Get-ChildItem -Path $scriptPath -Filter "*.wav" -Recurse |
    Where-Object -FilterScript { $_.LastWriteTime -ge (Get-Date).AddDays(-1).Date } |
    Select-Object -First 10 | ForEach-Object -Begin {
        if (-not(Test-Path -Path $Destination -PathType Container)) {
            New-Item -Path $Destination -ItemType Container | Out-Null
        }
    } -Process {
        Copy-Item -Path $_.FullName -Destination $Destination
    }

Swapped your if statement to Where-Object to streamline the process. Also selected the top (first) 10 files found to copy.

You're expecting Copy-Item to create the folder and copy the files for you and that's where your issue occurs. Copy-Item can in fact create the folder first, then recursively copy to it when providing the -Recurse switch but, not when it's piped to it (... | Copy-Item); this includes even providing the -Force switch. So the alternative is to use the Foreach-Object cmdlet to create the folder first (in your Begin block), then copy to it. You can honestly create it whenever, wherever, using other methods, as long as it's not before the actual copying.


问:
Addition on HashSet of KeyValuePair
I have a list of entries. Each entry contains a string and a numerical value. The same string  can appear one or more times in a list and it can have a different numerical value. be I am looking for an elegant way to process the list. The end result should be a list of unique pairs of string and (sum of values for the string). Each unique string should be associated with the sum of all numerical values for the string. I consider creating a HashSet<KeyValuePair<string, double>> and to add each string to the HashSet. But I am not sure how to add all values together in a single loop. The code below works, but it is inefficient.</p>
```<code>        SortedSet<string> symbols = new SortedSet<string>();
        HashSet<KeyValuePair<string, double>> results = new HashSet<KeyValuePair<string, double>>();
        string file = openFileDialog1.FileName;
        string[] lines = File.ReadAllLines(file);

        foreach(string line in lines) {
            string[] values = line.Split('\t');
            string symbol = values[0].Trim();
            symbols.Add(symbol);
        }

        foreach(string uniqueSymbol in symbols) {
            double value = 0;
            foreach(string line in lines) {
                string[] values = line.Split('\t');
                string symbol = values[0].Trim();
                string sProfit = values[7].Trim();
                double fProfit = Convert.ToDouble(sProfit);

                if(symbol == uniqueSymbol) {
                    value += fProfit;
                }
            }

            results.Add(new KeyValuePair<string, double>(uniqueSymbol, value));
        }
</code>```

答:
If I understand that you want to get the sum of the duplicate row values, this might be helpful.</p>
```<code>Dictionary<string, double> results = new Dictionary<string, double>();
foreach(string line in lines) {
            string[] values = line.Split('\t');
            string symbol = values[0].Trim();
            double profit = Convert.ToDouble(values[7].Trim());
            results.Add(symbol, profit);
}

List<KeyValuePair<string, double>> grouped = (from kvp in results
                                             group kvp by kvp.Key
                                             into g
                                             select
                                             new KeyValuePair<string, double>
                                             (g.Key,g.Sum(e => e.Value)))
.ToList();
</code>```

Title: Addition on HashSet of KeyValuePair

Body:
I have a list of entries. Each entry contains a string and a numerical value. The same string  can appear one or more times in a list and it can have a different numerical value. be I am looking for an elegant way to process the list. The end result should be a list of unique pairs of string and (sum of values for the string). Each unique string should be associated with the sum of all numerical values for the string. I consider creating a HashSet<KeyValuePair<string, double>> and to add each string to the HashSet. But I am not sure how to add all values together in a single loop. The code below works, but it is inefficient.

        SortedSet<string> symbols = new SortedSet<string>();
        HashSet<KeyValuePair<string, double>> results = new HashSet<KeyValuePair<string, double>>();
        string file = openFileDialog1.FileName;
        string[] lines = File.ReadAllLines(file);

        foreach(string line in lines) {
            string[] values = line.Split('\t');
            string symbol = values[0].Trim();
            symbols.Add(symbol);
        }

        foreach(string uniqueSymbol in symbols) {
            double value = 0;
            foreach(string line in lines) {
                string[] values = line.Split('\t');
                string symbol = values[0].Trim();
                string sProfit = values[7].Trim();
                double fProfit = Convert.ToDouble(sProfit);

                if(symbol == uniqueSymbol) {
                    value += fProfit;
                }
            }

            results.Add(new KeyValuePair<string, double>(uniqueSymbol, value));
        }

Body:
If I understand that you want to get the sum of the duplicate row values, this might be helpful.

Dictionary<string, double> results = new Dictionary<string, double>();
foreach(string line in lines) {
            string[] values = line.Split('\t');
            string symbol = values[0].Trim();
            double profit = Convert.ToDouble(values[7].Trim());
            results.Add(symbol, profit);
}

List<KeyValuePair<string, double>> grouped = (from kvp in results
                                             group kvp by kvp.Key
                                             into g
                                             select
                                             new KeyValuePair<string, double>
                                             (g.Key,g.Sum(e => e.Value)))
.ToList();