问:
How to put comma separated array of json into span tags coming from ngFor in angular 8
I have simple array of object.I am using those into loop ngFor. I can able to render. But the problem is json contains Treatment":"OPD,MEDICINES". So I need to iterate those comma separated value into span and put border.Here is the code below

home.component.html

```<code><div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="mb-3 text-right">
<input [(ngModel)]="searchText" autocomplete="off" class="col-md-3 searchinput" type="text" placeholder="Search.."/>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<table class="table table-bordered expensetable">
    <thead>
      <tr>
        <th>Date</th>
        <th>Treatment</th>
        <th>Expenses</th>
      </tr>
    </thead>
    <tbody>
    <ng-container *ngIf="( getListData | filter:searchText) as result">
      <tr *ngFor="let item of result">
        <td>{{item.Date}}</td>
        <td>{{item.Treatment}}</td>
        <td>{{item.Expenses}}</td>
      </tr>
     <tr *ngIf="result.length === 0">
        <td colspan="3" class="text-center">No Data Found</td>
      </tr>
      </ng-container>
    </tbody>
  </table>
  </div>
  </div>
</div>
</code>```

home.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { CommonserviceService } from './../utilities/services/commonservice.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  getListData: any;
  constructor(private commonserviceService: CommonserviceService) { }

  ngOnInit() {
      this.getHeroes();
  }
getHeroes(){
   this.commonserviceService.getData().subscribe(getListData =>{
          this.getListData = getListData;
          console.log(this.getListData);
      },
      (error) => {
      alert('No data');
      }
  );
}
}
</code>```

commonservice.service.ts

```<code>import { Injectable } from '@angular/core';
import {Http,Headers} from '@angular/http';
import 'rxjs/add/operator/map';

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

  constructor(private http:Http) { }

  getData(){
      let url = "http://dummy.restapiexample.com/api/v1/employees";
      return this.http.get(url)
     .map(
     (res) =>{
    let resData = /*res;*/ [{"Date":"8/02/2020","Expenses":750,"Treatment":"OPD,MEDICINES"},{"Date":"15/02/2020","Expenses":2565,"Treatment":"OPD,MEDICINES,ULTRASOUND SCAN"}]
    console.log(resData);
    return  resData;

     }
     );
  }
}
</code>```

答:
Try this.

1) Create a function in ts file. This function will split your treatment string by comma. Use javascript native function split for this. This will return you an array. Loop through this array and create desired html.

2) Use [innerHtml] to assign value in td of table

.ts file

```<code>getTreatment(data) {
    let str = ''
    let arr = data.split(',');
    if (arr.length > 0) {
      for (let i = 0; i < arr.length; i++) {
        str += '<p>' + arr[i] + '</p>'
      }
    }
    return str
  }
</code>```

.html

```<code><table class="table" border="1px">
    <thead>
      <tr>
        <th>Date</th>
        <th>Treatment</th>
        <th>Expenses</th>
      </tr>
    </thead>
    <tbody>
    <ng-container>
      <tr *ngFor="let item of resData">
        <td>{{item.Date}}</td>
        <td [innerHtml]="getTreatment(item.Treatment)"></td>
        <td>{{item.Expenses}}</td>
      </tr>

      </ng-container>
    </tbody>
  </table>
</code>```

Working link

https://stackblitz.com/edit/angular-mwd3us

Note : : It may also done using pipe as well. You can try it using pipe

Body:
I have simple array of object.I am using those into loop ngFor. I can able to render. But the problem is json contains Treatment":"OPD,MEDICINES". So I need to iterate those comma separated value into span and put border.Here is the code below

home.component.html

<input [(ngModel)]="searchText" autocomplete="off" class="col-md-3 searchinput" type="text" placeholder="Search.."/>

        Date
        Treatment
        Expenses

    <ng-container *ngIf="( getListData | filter:searchText) as result">

        {{item.Date}}
        {{item.Treatment}}
        {{item.Expenses}}

        No Data Found

      </ng-container>

home.component.ts

import { Component, OnInit } from '@angular/core';
import { CommonserviceService } from './../utilities/services/commonservice.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  getListData: any;
  constructor(private commonserviceService: CommonserviceService) { }

  ngOnInit() {
      this.getHeroes();
  }
getHeroes(){
   this.commonserviceService.getData().subscribe(getListData =>{
          this.getListData = getListData;
          console.log(this.getListData);
      },
      (error) => {
      alert('No data');
      }
  );
}
}

commonservice.service.ts

import { Injectable } from '@angular/core';
import {Http,Headers} from '@angular/http';
import 'rxjs/add/operator/map';

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

  constructor(private http:Http) { }

  getData(){
      let url = "http://dummy.restapiexample.com/api/v1/employees";
      return this.http.get(url)
     .map(
     (res) =>{
    let resData = /*res;*/ [{"Date":"8/02/2020","Expenses":750,"Treatment":"OPD,MEDICINES"},{"Date":"15/02/2020","Expenses":2565,"Treatment":"OPD,MEDICINES,ULTRASOUND SCAN"}]
    console.log(resData);
    return  resData;

     }
     );
  }
}

Body:
Try this.

1) Create a function in ts file. This function will split your treatment string by comma. Use javascript native function split for this. This will return you an array. Loop through this array and create desired html.

2) Use [innerHtml] to assign value in td of table

.ts file

getTreatment(data) {
    let str = ''
    let arr = data.split(',');
    if (arr.length > 0) {
      for (let i = 0; i < arr.length; i++) {
        str += '<p>' + arr[i] + '</p>'
      }
    }
    return str
  }

.html

<table class="table" border="1px">
    <thead>
      <tr>
        <th>Date</th>
        <th>Treatment</th>
        <th>Expenses</th>
      </tr>
    </thead>
    <tbody>
    <ng-container>
      <tr *ngFor="let item of resData">
        <td>{{item.Date}}</td>
        <td [innerHtml]="getTreatment(item.Treatment)"></td>
        <td>{{item.Expenses}}</td>
      </tr>

      </ng-container>
    </tbody>
  </table>

Working link

https://stackblitz.com/edit/angular-mwd3us

Note : : It may also done using pipe as well. You can try it using pipe


来源: stackexchange

问:
Best way to find lowest number in a list of objects using math.min?
Heres my code, which works but i feel like there is a more simple way doing this. The bold part is where i want to change.</p>

```<code>interface properties {
    age: number;
    salary: number;
    name: string;
}
let minSalary: any;
let maxSalary: any;

let list: properties[] = [
    {name: "P", age: 12, salary: 100},
    {name: "S", age: 80, salary: 12000},
    {name: "Q", age: 25, salary: 80000},
    {name: "W", age: 55, salary: 45000},
    {name: "E", age: 32, salary: 25000},
    {name: "V", age: 5, salary: 0}
];

**minSalary =  Math.min.apply(Math, list.map( salaries => {
    return salaries.salary;** // This is the code i want to make easier
}
));

console.log(minSalary);
</code>```

答:
You can use reduce

minSalary = list.reduce((least, x) => Math.min(least, x.salary), Infinity)
```

ContentLicense: CC BY-SA 4.0

Body:
Heres my code, which works but i feel like there is a more simple way doing this. The bold part is where i want to change.

interface properties {
    age: number;
    salary: number;
    name: string;
}
let minSalary: any;
let maxSalary: any;

let list: properties[] = [
    {name: "P", age: 12, salary: 100},
    {name: "S", age: 80, salary: 12000},
    {name: "Q", age: 25, salary: 80000},
    {name: "W", age: 55, salary: 45000},
    {name: "E", age: 32, salary: 25000},
    {name: "V", age: 5, salary: 0}
];

**minSalary =  Math.min.apply(Math, list.map( salaries => {
    return salaries.salary;** // This is the code i want to make easier
}
));

console.log(minSalary);


问:
Alternative to Single-spa
We have huge enterprise application written in angularjs.

Now we have to migrate to angular, so we have ruled out an option of hybrid approach angular suggests using "ngUpgrade".

So now we are creating a new application in angular, which means we have 2 applications "angularjs(old)" and angular(new).

So to switch between these two applications can be done without refresh using angular-spa.

I was trying to find if there is another framework, where navigating between two apps happens without refreshing(without refreshing entire page by navigating to new html).

答:
I've recently tried the micro-frontend architecture described here:
https://www.martinfowler.com/articles/micro-frontends.html

Each app on different code repository, runtime build and quite easy to implement. Take a look :)

Title: Alternative to Single-spa


问:
Is there a way to take screen shots of desktop that not current active one using mss?
I'm trying to record screen when playing a website by using mss and opencv, but I don't want the program to use the current screen. I want to put them to play on a second desktop, like Desktop 2 in the following picture
macos have 4 desktop setup

so I can work in the desktop 1 without any interruption.

答:
Currently, MSS does not support capturing inactive workspaces.

This Ask Ubuntu answer indicates (referencing a post on an "archived" (i.e. apparently deleted) forum) that this is not normally possible in the X Window System.1 The answer discusses using Xvfb as a workaround, but this does not appear to be useful for screen-capture software, as it is essentially a way to run the application on a virtual display, which can then be captured normally.

If taking a screenshot of an inactive space is possible on macOS (which I consider unlikely for the same reasons as on X), you would likely need to use non-API functions from CoreGraphics (as there was no public API for spaces as of 2016). This GitHub repository documents those functions, though the repository was last updated in 2016, so it may not be as helpful as you would like.

Another option, which may be the least OS-dependent, is to run a headless virtual machine and take screenshots of that. How well this works will depend on the virtual machine manager and the virtual machine itself, as well as how you are taking the screenshots.

1 Basically because the inactive desktops are not rendered.

For anyone who sees this question while looking for a way to take screenshots of other monitors, look at the edit history of this answer.


问:
Leave out quotes when copying from cell
Problem:

When copying a cell from Excel outside of the program, double-quotes are added automatically.

Details:

I'm using Excel 2007 on a Windows 7 machine. If I have a cell with the following formula:

```<code>="1"&CHAR(9)&"SOME NOTES FOR LINE 1."&CHAR(9)&"2"&CHAR(9)&"SOME NOTES FOR LINE 2."
</code>```

The output in the cell (formatted as number) looks like this in Excel:

```<code>1SOME NOTES FOR LINE 1.2SOME NOTES FOR LINE 2.
</code>```

Well and good. But, if I copy the cell into another program, such as notepad, I get annoying double-quotes at the beginning and end. Notice the tabs created by "CHAR(9)" are kept, which is good.

```<code>"1  SOME NOTES FOR LINE 1.  2     SOME NOTES FOR LINE 2."
</code>```

How can I keep these double-quotes from showing up, when I copy to another program? In other words, can I keep these from being automatically added when the cell is copied to clipboard?

答:
Note:The cause of the quotes is that when data moves from excel to clipboard it is fully complying with CSV standards which include quoting values that include tabs, new lines etc (and double-quote characters are replaced with two double-quote characters )

So another approach, especially as in OP's case when tabs/new lines are due to the formula, is to use alternate characters for tabs and hard returns. I use ascii Unit Separator =char(31) for tabs and ascii Record Separator =char(30) for new lines.

Then pasting into text editor will not involve the extra CSV rules and you can do a quick search and replace to convert them back again.

If the tabs/new lines are embedded in the data, you can do a search and replace in excel to convert them.

Whether using formula or changing the data, the key to choosing delimiters is never use characters that can be in the actual data. This is why I recommend the low level ascii characters.

ContentLicense: CC BY-SA 3.0

Title: Leave out quotes when copying from cell

Body:
Problem:

When copying a cell from Excel outside of the program, double-quotes are added automatically.

Details:

I'm using Excel 2007 on a Windows 7 machine. If I have a cell with the following formula:

="1"&CHAR(9)&"SOME NOTES FOR LINE 1."&CHAR(9)&"2"&CHAR(9)&"SOME NOTES FOR LINE 2."

The output in the cell (formatted as number) looks like this in Excel:

1SOME NOTES FOR LINE 1.2SOME NOTES FOR LINE 2.

Well and good. But, if I copy the cell into another program, such as notepad, I get annoying double-quotes at the beginning and end. Notice the tabs created by "CHAR(9)" are kept, which is good.

"1  SOME NOTES FOR LINE 1.  2     SOME NOTES FOR LINE 2."

How can I keep these double-quotes from showing up, when I copy to another program? In other words, can I keep these from being automatically added when the cell is copied to clipboard?


问:
Calculate the standard deviation in R for a specific group of the dependent variable
I am trying to calculate the standard deviation from certain variables for different groups. In my dataset I have a 2 explanatory variables with a 0 or 1 outcome (CH and CH2). I would like to know the difference in the standard deviation of these two groups.

so far I am working with the following command. sample being the dataset and COM being one of the explanatory variables.

```<code>sd(sample$COM, na.rm=TRUE)
</code>```

Is it possible to specify it for CH = 1?
And additionally for CH = 1 or CH2=1?

Thank you in advance and kind regards.

答:
An easy way is using the tidyverse package. </p>

<p>using the mtcars dataset as an example: </p>

```<code>library(tidyverse)

mtcars %>% group_by(am) %>%
  summarise(SD_disp = sd(disp),
            SD_hp = sd(hp))
</code>```

Body:
I am trying to calculate the standard deviation from certain variables for different groups. In my dataset I have a 2 explanatory variables with a 0 or 1 outcome (CH and CH2). I would like to know the difference in the standard deviation of these two groups.

so far I am working with the following command. sample being the dataset and COM being one of the explanatory variables.

sd(sample$COM, na.rm=TRUE)

Is it possible to specify it for CH = 1?
And additionally for CH = 1 or CH2=1?

Thank you in advance and kind regards.

Body:
An easy way is using the tidyverse package.

using the mtcars dataset as an example:

library(tidyverse)

mtcars %>% group_by(am) %>%
  summarise(SD_disp = sd(disp),
            SD_hp = sd(hp))


问:
How does Windows/Linux x64 determine the last time a memory page was accessed?
When virtual memory systems decide to evict a memory page out to disk, it's sometimes mentioned that the last time of access of that memory page is used to help decide which page is evicted.  But what mechanism is used to track the last time of access of a memory page?

I believe the TLB only stores information on its current set of pages not all of them.  Or is it simply that anything not present in the TLB is game for eviction under that criteria?

答:
The page frame reclaiming algorithm(PFRA) in Linux kernel is acutally quite complex and it uses several heuristics to decide which page to evict. The actual decision is based on many factors, but following two stand out.

1. The Least Recently Used (LRU) Lists

Linux divides memory into different memory zones, each zone has a zone descriptor and this descriptor along with other things stores references to two very important lists namely active and inactive.

The active list includes the pages that have been accessed recently, while the inactive list includes the pages that have not been accessed for some time. Different page frames move from one list to another and out of lists depending on the access patterns.

2. Page descriptor flags

following two flags in the page descriptor allows kernel to identify if a given page is included in one of the above lists.

PG_lru - The page is in the active or inactive page list

PG_active -The page is in the active page list

Understanding the Linux Kernel states the following when it describes how PFRA actually uses above information.

The main idea behind the LRU algorithm is to associate a counter
storing the age of the page with each page in RAM—that is, the
interval of time elapsed since the last access to the page. This
counter allows the PFRA to reclaim only the oldest page of any
process. Some computer platforms provide sophisticated support for LRU
algorithms;† unfortunately, 80 × 86 processors do not offer such a
hardware feature, thus the Linux kernel cannot rely on a page counter
that keeps track of the age of every page. To cope with this
restriction, Linux takes advantage of the Accessed bit included in
each Page Table entry, which is automatically set by the hardware when
the page is accessed; moreover, the age of a page is represented by
the position of the page descriptor in one of two different “The Least
Recently Used (LRU) Lists”.


问:
Is there a way to do this in a simple query?
I have a BIG (23 millions rows) table CONTRATOS which has these columns:

```<code>SELECT
    CONTRATO,
    CODIGO_ORIGEN,
    ORIGEN
FROM CONTRATOS;
</code>```

There are multiple rows with the same value for the column CODIGO_ORIGEN:

```<code>CODIGO_ORIGEN     CONTRATO       ORIGEN
-------------    ----------     --------
     1               345          CONT
     1               363          BKP
     1               645          BKP
     1               365          CONT
</code>```

I need to get only one CONTRATO per CODIGO_ORIGEN but always prioritizing the 'CONT' value. So in this sample it would be the CONTRATO with value 365

I was trying to to something like this:

```<code>SELECT
   CODIGO_ORIGEN,
   CASE
    WHEN ORIGEN = 'CONT' THEN
        FIRST_VALUE (CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY CONTRATO DESC)
    WHEN ORIGEN = 'BKP' THEN
        FIRST_VALUE (CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY CAMPO1 DESC, CAMPO2 DESC, CONTRATO DESC)
   END AS CONTRATO
FROM CONTRATOS;
</code>```

In case ORIGEN is 'CONTR' i should sort by the highest CONTRATO and get the CONTRATO column.
In case ORIGEN is 'BKP' i should sort by different columns and get the CONTRATO column.

Finally, i should be able to have one unique row with CODIGO_ORIGEN -> CONTRATO (1:1).

Is there a simple way to do this (1 query)?

Thanks in advance!

答:
You can use ROW_NUMBER in order to rank your rows per codigo_origen. Here is one way to write its ORDER BY clause. There are others, too.

```<code>select *
from
(
  select
     c.*,
     row_number() over (
       partition by codigo_origen
       order by
         case when origen 'BKP' then campo1 end desc,
         case when origen 'BKP' then campo2 end desc,
         origen desc
     ) as rn
  from contratos c
) ranked
where rn = 1
order by codigo_origen;
</code>```

Body:
I have a BIG (23 millions rows) table CONTRATOS which has these columns:

SELECT
    CONTRATO,
    CODIGO_ORIGEN,
    ORIGEN
FROM CONTRATOS;

There are multiple rows with the same value for the column CODIGO_ORIGEN:

CODIGO_ORIGEN     CONTRATO       ORIGEN
-------------    ----------     --------
     1               345          CONT
     1               363          BKP
     1               645          BKP
     1               365          CONT

I need to get only one CONTRATO per CODIGO_ORIGEN but always prioritizing the 'CONT' value. So in this sample it would be the CONTRATO with value 365

I was trying to to something like this:

SELECT
   CODIGO_ORIGEN,
   CASE
    WHEN ORIGEN = 'CONT' THEN
        FIRST_VALUE (CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY CONTRATO DESC)
    WHEN ORIGEN = 'BKP' THEN
        FIRST_VALUE (CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY CAMPO1 DESC, CAMPO2 DESC, CONTRATO DESC)
   END AS CONTRATO
FROM CONTRATOS;

In case ORIGEN is 'CONTR' i should sort by the highest CONTRATO and get the CONTRATO column.
In case ORIGEN is 'BKP' i should sort by different columns and get the CONTRATO column.

Finally, i should be able to have one unique row with CODIGO_ORIGEN -> CONTRATO (1:1).

Is there a simple way to do this (1 query)?

Thanks in advance!

Body:
You can use ROW_NUMBER in order to rank your rows per codigo_origen. Here is one way to write its ORDER BY clause. There are others, too.

select *
from
(
  select
     c.*,
     row_number() over (
       partition by codigo_origen
       order by
         case when origen 'BKP' then campo1 end desc,
         case when origen 'BKP' then campo2 end desc,
         origen desc
     ) as rn
  from contratos c
) ranked
where rn = 1
order by codigo_origen;


问:
Use mutate in purrr workflow
I got the following datasets:

```<code>dflist <- list(mtcars, mtcars)

dflist[[1]] %>%
  mutate(cyl2 = cyl * 2)
</code>```

This works!

```<code>dflist %>%
  map(.x, ~.x$cyl2 = .x$cyl * 2)

Error: unexpected '=' in:
"dflist %>%
  map(.x, ~x$cyl2 ="
</code>```

This results in an error. I tried other options, but the function does not except the = sign. What is wrong there?

答:
We can use transform without anonymous function call in base R

```<code>lapply(dflist, transform, cyl2 = cyl *2)
</code>```

Title: Use mutate in purrr workflow

Body:
I got the following datasets:

dflist <- list(mtcars, mtcars)

dflist[[1]] %>%
  mutate(cyl2 = cyl * 2)

This works!

dflist %>%
  map(.x, ~.x$cyl2 = .x$cyl * 2)

Error: unexpected '=' in:
"dflist %>%
  map(.x, ~x$cyl2 ="

This results in an error. I tried other options, but the function does not except the = sign. What is wrong there?

Body:
We can use transform without anonymous function call in base R

lapply(dflist, transform, cyl2 = cyl *2)


问:
Connecting Vertica as Django backend
I want to connect Vertica as the database backend for my Django application. Officially no support is provided by Django to it. I googled this problem and found this:
https://github.com/rutube/django_vertica_backend

The code which is written in this git hub returning following error:

```<code>Traceback (most recent call last):
File "/usr/lib/python3.6/site-packages/django/db/utils.py", line 110, in load_backend
    return import_module('%s.base' % backend_name)
  File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/rksharma/ccChatBot/django_vertica_backend/vertica/base.py", line 8, in <module>
    from django.db.backends.creation import BaseDatabaseCreation
ModuleNotFoundError: No module named 'django.db.backends.creation'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/usr/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute
    django.setup()
  File "/usr/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/usr/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate
    app_config.import_models()
  File "/usr/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/usr/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "/usr/lib/python3.6/site-

    packages/django/contrib/auth/base_user.py", line 47, in <module>
        class AbstractBaseUser(models.Model):
      File "/usr/lib/python3.6/site-packages/django/db/models/base.py", line 114, in __new__
        new_class.add_to_class('_meta', Options(meta, app_label))
      File "/usr/lib/python3.6/site-packages/django/db/models/base.py", line 315, in add_to_class
        value.contribute_to_class(cls, name)
      File "/usr/lib/python3.6/site-packages/django/db/models/options.py", line 205, in contribute_to_class
        self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
      File "/usr/lib/python3.6/site-packages/django/db/__init__.py", line 33, in __getattr__
        return getattr(connections[DEFAULT_DB_ALIAS], item)
      File "/usr/lib/python3.6/site-packages/django/db/utils.py", line 202, in __getitem__
        backend = load_backend(db['ENGINE'])
      File "/usr/lib/python3.6/site-packages/django/db/utils.py", line 125, in load_backend
        ) from e_user
    django.core.exceptions.ImproperlyConfigured: 'vertica' isn't an available database backend.
    Try using 'django.db.backends.XXX', where XXX is one of:
        'mysql', 'oracle', 'postgresql', 'sqlite3'
</code>```

答: This is not possible as of now. We can create some custom functionality to do so.</p>

Title: Connecting Vertica as Django backend

Body:
I want to connect Vertica as the database backend for my Django application. Officially no support is provided by Django to it. I googled this problem and found this:
https://github.com/rutube/django_vertica_backend

The code which is written in this git hub returning following error:

Traceback (most recent call last):
File "/usr/lib/python3.6/site-packages/django/db/utils.py", line 110, in load_backend
    return import_module('%s.base' % backend_name)
  File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/rksharma/ccChatBot/django_vertica_backend/vertica/base.py", line 8, in <module>
    from django.db.backends.creation import BaseDatabaseCreation
ModuleNotFoundError: No module named 'django.db.backends.creation'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/usr/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute
    django.setup()
  File "/usr/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/usr/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate
    app_config.import_models()
  File "/usr/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/usr/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "/usr/lib/python3.6/site-

    packages/django/contrib/auth/base_user.py", line 47, in <module>
        class AbstractBaseUser(models.Model):
      File "/usr/lib/python3.6/site-packages/django/db/models/base.py", line 114, in __new__
        new_class.add_to_class('_meta', Options(meta, app_label))
      File "/usr/lib/python3.6/site-packages/django/db/models/base.py", line 315, in add_to_class
        value.contribute_to_class(cls, name)
      File "/usr/lib/python3.6/site-packages/django/db/models/options.py", line 205, in contribute_to_class
        self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
      File "/usr/lib/python3.6/site-packages/django/db/__init__.py", line 33, in __getattr__
        return getattr(connections[DEFAULT_DB_ALIAS], item)
      File "/usr/lib/python3.6/site-packages/django/db/utils.py", line 202, in __getitem__
        backend = load_backend(db['ENGINE'])
      File "/usr/lib/python3.6/site-packages/django/db/utils.py", line 125, in load_backend
        ) from e_user
    django.core.exceptions.ImproperlyConfigured: 'vertica' isn't an available database backend.
    Try using 'django.db.backends.XXX', where XXX is one of:
        'mysql', 'oracle', 'postgresql', 'sqlite3'


问:
Angular / SpringBoot how to send an image file as Request Body?
all the tutorials that i have seen tend to treat an image as a stand alone model and send it using a FormData , what i want is to include the image file as a property of an object Called Course, </p>

<p>what is the process to do so , and in what way should i receive my image in the back-end if it was a property of a model </p>

答:
You can use it by using an @Multipart annotation and getting the image as MultiPartBody.part. You can check in the below link for more detailed explanation.
How to Upload Image file in Retrofit 2</p>

Body:
all the tutorials that i have seen tend to treat an image as a stand alone model and send it using a FormData , what i want is to include the image file as a property of an object Called Course,

what is the process to do so , and in what way should i receive my image in the back-end if it was a property of a model


问:
Runtime error in sorting a singly linked list
I have written a linked list(which is aimed for the data type int) implementation.
Seems to be working fine except when I try to sort the list in such a way that all the odd
elements should come after all the even elements with the original order of the even and odd numbers preserved.

Upon debugging in MS Visual Studio, I found out that in the oddevenSort() function, the for loop seems to be going on infinitely...as if somehow the tail->next was not being updated to nullptr.
I can't seem to grasp where the error lies in my logic.

```<code>#include<iostream>

template<class T>
class SLL_Node
{
public:
    T info;
    SLL_Node* next;
    SLL_Node();
    SLL_Node(T el, SLL_Node<T>* n = nullptr);

};

template<class T>
class SLL
{
private:
    SLL_Node<T>* head, * tail;
    size_t size;
public:
    SLL();
    ~SLL();
    bool isEmpty() const;
    size_t get_size() const;
    void add_to_head(T el);
    void add_to_tail(T el);
    void delete_at(size_t); //delete at a certain index. Index starting from 1. Throws an error //message if index out of bounds or list empty.

    void display()const; //the logic is for mostly primitive data types and not user defined data //types (including classes)
    void oddevenSort();
};

template<class T>
bool SLL<T>::isEmpty() const
{
    if (tail == nullptr)
        return true;
    else
        return false;
}

template<class T>
SLL_Node<T>::SLL_Node() : next{ nullptr }
{}

template<class T>
SLL_Node<T>::SLL_Node(T el, SLL_Node<T>* n) : info{ el }, next{ n }
{}

template<class T>
SLL<T>::SLL()
{
    size = 0;
    head = tail = nullptr;
}

template<class T>
void SLL<T>::add_to_tail(T el)
{
    ++size;
    if (!isEmpty())
    {
        tail->next = new SLL_Node<T>(el);
        tail = tail->next;
    }
    else
        head = tail = new SLL_Node<T>(el);
}

template<class T>
void SLL<T>::add_to_head(T el)
{
    head = new SLL_Node<T>(el, head);
    if (tail == nullptr) //if empty
    {
        tail = head;
    }
    ++size;
}

template<class T>
void SLL<T>::display()const
{
    std::cout << '\n';
    for (SLL_Node<T>* tmp{ head }; tmp != nullptr; tmp = tmp->next)
    {
        std::cout << tmp->info << "->";
    }
    std::cout << "NULL\n";
}

template<class T>
void SLL<T>::delete_at(size_t index)
{

    if (index >= 1 && index <= size) //bound checking
    {
        if (!isEmpty()) //we dont need is empty since size takes care of that but still adding it for clarity
        {

            if (head == tail && index == 1) //if list only has one node and we delete head node
            {
                delete head;
                head = tail = nullptr;
            }

            //otherwise if list more than one node

            else if (index == 1) //if deleting head node
            {
                SLL_Node<T>* tmp{ head };
                head = head->next;
                delete tmp;
                tmp = nullptr;
            }

            else //deleting other nodes
            {
                SLL_Node<T>* tmp{ head->next }, * pred{ head };
                for (size_t i{ 2 }; i < index; ++i)
                {
                    tmp = tmp->next;
                    pred = pred->next;
                }
                pred->next = tmp->next;
                if (tmp == tail)
                {
                    tail = pred;
                }
                delete tmp;
                tmp = nullptr;
            }

        }
    }

    else
    {
        std::cout<<"\nError! Either the list is empty or the index entered is out of bounds!\n";
    }
}

template<class T>
void SLL<T>::oddevenSort()
{
    SLL_Node<T>* t=head;
    size_t count{1};
    for (; t != nullptr; t = t->next)
    {
        if (((t->info) % 2) != 0)
        {
        add_to_tail(t->info);
        delete_at(count);

        }
        ++count;
    }
}
</code>```

main:

```<code>int main()
{
    SLL<int> a;
    a.add_to_head(1);
    a.add_to_head(2);
    a.add_to_tail(3);
    a.add_to_tail(4);
    a.add_to_head(6);
    a.add_to_tail(7);
    a.add_to_head(5);
    a.display();
    //a.oddevenSort();
    a.display();
    return 0;
}

</code>```

答:
Consider an example input for oddevenSort a(1)->b(2) ->c(3)->null

on 1st iteration t is pointing to a(1) new node is created with
data 1 which is appended at the end of list like
b(2)->c(3)->d(1)->null.

On 2nd iteration t will point to node b(2) and no changes done
on list.

On 3rd iteration t will point to node c(3) new node is created
with data 3 which is appended at the end of list like
b(2)->d(1)->e(3)->null.

on 4th iteration t will point to d(1) which creates new node at the end of list. Iteration goes on and on recursively without breaking the loop.

Every time you need not to delete and create the new node. You can segregate even and odd nodes and make final list.

Here is the updated snippet

```<code>template<class T>
void SLL<T>::oddevenSort()
{
    SLL_Node <T>tempOddHeader;
    SLL_Node <T> *tempOddPtr = &tempOddHeader;
    SLL_Node <T> tempEvenHeader;
    SLL_Node <T> *tempEvenPtr = &tempEvenHeader;

    SLL_Node<T>* t = head;
    tempOddHeader.next = nullptr;
    tempEvenHeader.next = nullptr;

    while(t)
    {
        if (((t->info) % 2) != 0) {
            //append to the odd list
            tempOddPtr->next = t;
            tempOddPtr = tempOddPtr->next;
            t = t->next;
            tempOddPtr->next = nullptr;
        }
        else {
            //append to the even list
            tempEvenPtr->next = t;
            tempEvenPtr = tempEvenPtr->next;
            t = t->next;
            tempEvenPtr->next = nullptr;
        }
    }

    tempEvenPtr->next = tempOddHeader.next;
    head = tempEvenHeader.next;
    tail = tempOddPtr;
}
</code>```

Body:
I have written a linked list(which is aimed for the data type int) implementation.
Seems to be working fine except when I try to sort the list in such a way that all the odd
elements should come after all the even elements with the original order of the even and odd numbers preserved.

Upon debugging in MS Visual Studio, I found out that in the oddevenSort() function, the for loop seems to be going on infinitely...as if somehow the tail->next was not being updated to nullptr.
I can't seem to grasp where the error lies in my logic.

#include<iostream>

template<class T>
class SLL_Node
{
public:
    T info;
    SLL_Node* next;
    SLL_Node();
    SLL_Node(T el, SLL_Node<T>* n = nullptr);

};

template<class T>
class SLL
{
private:
    SLL_Node<T>* head, * tail;
    size_t size;
public:
    SLL();
    ~SLL();
    bool isEmpty() const;
    size_t get_size() const;
    void add_to_head(T el);
    void add_to_tail(T el);
    void delete_at(size_t); //delete at a certain index. Index starting from 1. Throws an error //message if index out of bounds or list empty.

    void display()const; //the logic is for mostly primitive data types and not user defined data //types (including classes)
    void oddevenSort();
};

template<class T>
bool SLL<T>::isEmpty() const
{
    if (tail == nullptr)
        return true;
    else
        return false;
}

template<class T>
SLL_Node<T>::SLL_Node() : next{ nullptr }
{}

template<class T>
SLL_Node<T>::SLL_Node(T el, SLL_Node<T>* n) : info{ el }, next{ n }
{}

template<class T>
SLL<T>::SLL()
{
    size = 0;
    head = tail = nullptr;
}

template<class T>
void SLL<T>::add_to_tail(T el)
{
    ++size;
    if (!isEmpty())
    {
        tail->next = new SLL_Node<T>(el);
        tail = tail->next;
    }
    else
        head = tail = new SLL_Node<T>(el);
}

template<class T>
void SLL<T>::add_to_head(T el)
{
    head = new SLL_Node<T>(el, head);
    if (tail == nullptr) //if empty
    {
        tail = head;
    }
    ++size;
}

template<class T>
void SLL<T>::display()const
{
    std::cout << '\n';
    for (SLL_Node<T>* tmp{ head }; tmp != nullptr; tmp = tmp->next)
    {
        std::cout << tmp->info << "->";
    }
    std::cout << "NULL\n";
}

template<class T>
void SLL<T>::delete_at(size_t index)
{

    if (index >= 1 && index <= size) //bound checking
    {
        if (!isEmpty()) //we dont need is empty since size takes care of that but still adding it for clarity
        {

            if (head == tail && index == 1) //if list only has one node and we delete head node
            {
                delete head;
                head = tail = nullptr;
            }

            //otherwise if list more than one node

            else if (index == 1) //if deleting head node
            {
                SLL_Node<T>* tmp{ head };
                head = head->next;
                delete tmp;
                tmp = nullptr;
            }

            else //deleting other nodes
            {
                SLL_Node<T>* tmp{ head->next }, * pred{ head };
                for (size_t i{ 2 }; i < index; ++i)
                {
                    tmp = tmp->next;
                    pred = pred->next;
                }
                pred->next = tmp->next;
                if (tmp == tail)
                {
                    tail = pred;
                }
                delete tmp;
                tmp = nullptr;
            }

        }
    }

    else
    {
        std::cout<<"\nError! Either the list is empty or the index entered is out of bounds!\n";
    }
}

template<class T>
void SLL<T>::oddevenSort()
{
    SLL_Node<T>* t=head;
    size_t count{1};
    for (; t != nullptr; t = t->next)
    {
        if (((t->info) % 2) != 0)
        {
        add_to_tail(t->info);
        delete_at(count);

        }
        ++count;
    }
}

main:

int main()
{
    SLL<int> a;
    a.add_to_head(1);
    a.add_to_head(2);
    a.add_to_tail(3);
    a.add_to_tail(4);
    a.add_to_head(6);
    a.add_to_tail(7);
    a.add_to_head(5);
    a.display();
    //a.oddevenSort();
    a.display();
    return 0;
}

Body:
Consider an example input for oddevenSort a(1)->b(2) ->c(3)->null

on 1st iteration t is pointing to a(1) new node is created with
data 1 which is appended at the end of list like
b(2)->c(3)->d(1)->null.

On 2nd iteration t will point to node b(2) and no changes done
on list.

On 3rd iteration t will point to node c(3) new node is created
with data 3 which is appended at the end of list like
b(2)->d(1)->e(3)->null.

on 4th iteration t will point to d(1) which creates new node at the end of list. Iteration goes on and on recursively without breaking the loop.

Every time you need not to delete and create the new node. You can segregate even and odd nodes and make final list.

Here is the updated snippet

template<class T>
void SLL<T>::oddevenSort()
{
    SLL_Node <T>tempOddHeader;
    SLL_Node <T> *tempOddPtr = &tempOddHeader;
    SLL_Node <T> tempEvenHeader;
    SLL_Node <T> *tempEvenPtr = &tempEvenHeader;

    SLL_Node<T>* t = head;
    tempOddHeader.next = nullptr;
    tempEvenHeader.next = nullptr;

    while(t)
    {
        if (((t->info) % 2) != 0) {
            //append to the odd list
            tempOddPtr->next = t;
            tempOddPtr = tempOddPtr->next;
            t = t->next;
            tempOddPtr->next = nullptr;
        }
        else {
            //append to the even list
            tempEvenPtr->next = t;
            tempEvenPtr = tempEvenPtr->next;
            t = t->next;
            tempEvenPtr->next = nullptr;
        }
    }

    tempEvenPtr->next = tempOddHeader.next;
    head = tempEvenHeader.next;
    tail = tempOddPtr;
}


问:
Extract some data from string php
Quick question to easily cut a string. I know the substr but I can not use it in my case.

I have for example this thong: "1 rue Maryse Bastie 69500 BRON"
I'd like to say "Get all the end before the numbers" in this case "BRON" and get the numbers. I want the city and the postalcode in difference variable.

The API I'm using returns the complete address but I'd like to cut out to save the city and postal code in a different table.

I think this subject can help me : Extracting a zip code from an address string but not to get the city.

For exemple, if i have 1 rue Maryse Bastie 69500 BRON
I want $city = "BRON" and $pc = "69500"

If i have 13 rue Hohwald 67000 Strasbourg
I want $city = "Strasbourg" and $pc = "67000"

Thanks

答:
I give you a workaround, it should totally works, but maybe you will have to improve it :

```<code>$test = '1 rue Maryse Bastie 69500 BRON';
\preg_match('/\b\d{4,5}.+$/i', $test, $out);
$output = \explode(' ', \trim($out[0]), 2);
var_dump($output);
/*
array(2) {
  [0]=>
  string(5) "69500"
  [1]=>
  string(4) "BRON"
}
*/
</code>```

In the code above we have used regex to find this way :

find digits (many characters --> 4 or 5 five for french zipcode)

find all characters next the zipcode until the end

Next we remove spaces at start and end, then we split into an array.

Title: Extract some data from string php

Body:
I give you a workaround, it should totally works, but maybe you will have to improve it :

$test = '1 rue Maryse Bastie 69500 BRON';
\preg_match('/\b\d{4,5}.+$/i', $test, $out);
$output = \explode(' ', \trim($out[0]), 2);
var_dump($output);
/*
array(2) {
  [0]=>
  string(5) "69500"
  [1]=>
  string(4) "BRON"
}
*/

In the code above we have used regex to find this way :

find digits (many characters --> 4 or 5 five for french zipcode)

find all characters next the zipcode until the end

Next we remove spaces at start and end, then we split into an array.


问:
How to elegantly check if a number is within a range?
How can I do this elegantly with C#?

For example, a number can be between 1 and 100.

I know a simple if (x >= 1 && x <= 100) would suffice; but with a lot of syntax sugar and new features constantly added to C#/.Net this question is about more idiomatic (one can all it elegance) ways to write that.

Performance is not a concern, but please add performance note to solutions that are not O(1) as people may copy-paste the suggestions.

答:
Regarding elegance, the closest thing to the mathematical notation (a <= x <= b) slightly improves readability:

```<code>public static bool IsBetween(this int value, int min, int max)
{
    return min <= value && value <= max;
}
</code>```

For further illustration:

```<code>public static bool IsOutside(this int value, int min, int max)
{
    return value < min || max < value;
}
</code>```

Body:
Regarding elegance, the closest thing to the mathematical notation (a <= x <= b) slightly improves readability:

public static bool IsBetween(this int value, int min, int max)
{
    return min <= value && value <= max;
}

For further illustration:

public static bool IsOutside(this int value, int min, int max)
{
    return value < min || max < value;
}


问:
Lambda fails with "Cannot find module..."
I'm packing my lambdas with Webpack. And I'm deploying them with CDK.

However, when testing them through ApiGateway, I get this:

Lambda execution failed with status 200 due to customer function
  error: Error: Cannot find module 'apollo-server-lambda'.

Here's my Webpack config:

```<code>{
  mode: 'production',
  entry: {
    graphql: './src/lambdas/graphql.ts',
    cognito: './src/lambdas/cognito.ts',
    'smoke-detector': './src/lambdas/smoke-detector.ts',
  },
  output: {
    libraryTarget: 'commonjs',
    path: path.resolve(__dirname, "dist"),
    filename: '[name]/[name].js'
  },
  target: 'node',
  externals: [nodeExternals()],
  resolve: {
    extensions: ['.ts', '.js']
  },
  module: {
    rules: [
      loader({
        test: /\.ts$/,
        use: {
          loader: 'ts-loader',
          options: {
            getCustomTransformers: () => ({
              before: [graphqlTag.getTransformer()]
            })
          }
        }
      }),
      loader({
        test: /\.graphqls$/,
        use: {
          loader: 'graphql-tag/loader',
        }
      })
    ]
  },
  plugins: [
  ]
}
</code>```

Executing the output file like node graphql.js doesn't fail.
What am I doing wrong?

答:
Removing

```<code>externals: [nodeExternals()]
</code>```

fixed the problem.

It caused dependencies to be excluded from the bundle.

Body:
I'm packing my lambdas with Webpack. And I'm deploying them with CDK.

However, when testing them through ApiGateway, I get this:

Lambda execution failed with status 200 due to customer function
  error: Error: Cannot find module 'apollo-server-lambda'.

Here's my Webpack config:

{
  mode: 'production',
  entry: {
    graphql: './src/lambdas/graphql.ts',
    cognito: './src/lambdas/cognito.ts',
    'smoke-detector': './src/lambdas/smoke-detector.ts',
  },
  output: {
    libraryTarget: 'commonjs',
    path: path.resolve(__dirname, "dist"),
    filename: '[name]/[name].js'
  },
  target: 'node',
  externals: [nodeExternals()],
  resolve: {
    extensions: ['.ts', '.js']
  },
  module: {
    rules: [
      loader({
        test: /\.ts$/,
        use: {
          loader: 'ts-loader',
          options: {
            getCustomTransformers: () => ({
              before: [graphqlTag.getTransformer()]
            })
          }
        }
      }),
      loader({
        test: /\.graphqls$/,
        use: {
          loader: 'graphql-tag/loader',
        }
      })
    ]
  },
  plugins: [
  ]
}

Executing the output file like node graphql.js doesn't fail.
What am I doing wrong?

Body:
Removing

externals: [nodeExternals()]

fixed the problem.

It caused dependencies to be excluded from the bundle.


问:
Compare two list with same length and remove by specific value
I have two lists with the same length, both have 9 items

```<code>listA = ["spain","italy","germany","brazil","france","argentina","peru","bolivia","giappone"]
listB = [0,0,1,1,1,0,1,1,0]
</code>```

I'd like to get listA without value '1' from listB:

```<code>listA = ["spain", "italy","argentina","giappone"]
</code>```

Thanks.

答:
Just use zip :)

```<code>listA = ["spain", "italy", "germany", "brazil", "france", "argentina", "peru", "bolivia", "giappone"]
listB = [0, 0, 1, 1, 1, 0, 1, 1, 0]

getCountries = [i for (i,j) in zip(listA, listB) if j==0]
'''
  i being all the countries and j being the value 0 or 1
  in this case gets all the countries only for j == 0 or you could do j != 1
'''
print(getCountries)
</code>```

Output:

```<code>['spain', 'italy', 'argentina', 'giappone']
</code>```

Body:
I have two lists with the same length, both have 9 items

listA = ["spain","italy","germany","brazil","france","argentina","peru","bolivia","giappone"]
listB = [0,0,1,1,1,0,1,1,0]

I'd like to get listA without value '1' from listB:

listA = ["spain", "italy","argentina","giappone"]

Thanks.

Body:
Just use zip :)

listA = ["spain", "italy", "germany", "brazil", "france", "argentina", "peru", "bolivia", "giappone"]
listB = [0, 0, 1, 1, 1, 0, 1, 1, 0]

getCountries = [i for (i,j) in zip(listA, listB) if j==0]
'''
  i being all the countries and j being the value 0 or 1
  in this case gets all the countries only for j == 0 or you could do j != 1
'''
print(getCountries)

Output:

['spain', 'italy', 'argentina', 'giappone']


问:
Correct way to reference images in Firestore document
In my application, my user documents have an avatar image associated with them which is kept in cloud storage. Currently I have a field in the user object that references the download URL of its image. Just wondering if this is the correct/best way to do it.</p>

答:
There isn't really a best way to materialize the link between an avatar image that you store in Cloud Storage and a specific user of your Firebase project.

You can very well do the way you do (having a "field in the user object that references the download URL").

Another approach would be to store the avatar images in a public "folder" under your default bucket using the user UID to name the avatar image (see at the bottom the note on "folders").

Then you you can use a link with the following structure to directly download the image (or include it in a img src HTML tag)

```<code>https://firebasestorage.googleapis.com/v0/b/<yourprojectname>.appspot.com/o/users%2F38r174prM9aTx4JAdcm50r3V0Hq2.png?alt=media
</code>```

where users is the name of the "folder" dedicated to public avatar images

and 38r174prM9aTx4JAdcm50r3V0Hq2.png is the image file name for a specific user (i.e. user UId + png extension).

Note that the / is encoded as %2F (standard URL encoding).

You would then set your Cloud Storage security rules like the following:

```<code>service firebase.storage {
 match /b/{bucket}/o {

    match /privateFiles {   //All other files that are not under users
     match /{allprivateFiles=**} {
       allow read: if false;
       allow write: .....
     }
   }

   match /users/{userId} {   //Public "folder"
     allow read;
   }
 }
}
</code>```

Note: Actually Google Cloud Storage does not have true "folders", but by using a "/" delimiter character in the file path it will behave similarly to folders. In particular the Firebase console will display the files organised in folders.

Body:
There isn't really a best way to materialize the link between an avatar image that you store in Cloud Storage and a specific user of your Firebase project.

You can very well do the way you do (having a "field in the user object that references the download URL").

Another approach would be to store the avatar images in a public "folder" under your default bucket using the user UID to name the avatar image (see at the bottom the note on "folders").

Then you you can use a link with the following structure to directly download the image (or include it in a img src HTML tag)

https://firebasestorage.googleapis.com/v0/b/<yourprojectname>.appspot.com/o/users%2F38r174prM9aTx4JAdcm50r3V0Hq2.png?alt=media

where users is the name of the "folder" dedicated to public avatar images

and 38r174prM9aTx4JAdcm50r3V0Hq2.png is the image file name for a specific user (i.e. user UId + png extension).

Note that the / is encoded as %2F (standard URL encoding).

You would then set your Cloud Storage security rules like the following:

service firebase.storage {
 match /b/{bucket}/o {

    match /privateFiles {   //All other files that are not under users
     match /{allprivateFiles=**} {
       allow read: if false;
       allow write: .....
     }
   }

   match /users/{userId} {   //Public "folder"
     allow read;
   }
 }
}

Note: Actually Google Cloud Storage does not have true "folders", but by using a "/" delimiter character in the file path it will behave similarly to folders. In particular the Firebase console will display the files organised in folders.


问:
Call script from Server side in asp.net mvc core 3.0
I'm trying to open bootstrap modal from server side in asp.net mvc core 3.0 but unable open getting error

```<code>ViewBag.RegisterStartupScript(this, this.GetType(), "$('#modalRegisterForm').modal('show')", true);
</code>```

答:
I solved this by creating a variable in my PageModel:

```<code>public string errMsg { get; private set; }
</code>```

And then using this variable in the cshtml page in a script section:

```<code><script>
  if ('' !== '@Model.errMsg') {
    window.alert('@Model.errMsg');
  }
</script>
</code>```

So, by assigning a value to my errMsg variable in the code-behind I can control the rendering of scripts client side based on what's going on server side. I think you can get what you want with the modal using this approach?

Body:
I'm trying to open bootstrap modal from server side in asp.net mvc core 3.0 but unable open getting error

ViewBag.RegisterStartupScript(this, this.GetType(), "$('#modalRegisterForm').modal('show')", true);

Body:
I solved this by creating a variable in my PageModel:

public string errMsg { get; private set; }

And then using this variable in the cshtml page in a script section:

<script>
  if ('' !== '@Model.errMsg') {
    window.alert('@Model.errMsg');
  }
</script>

So, by assigning a value to my errMsg variable in the code-behind I can control the rendering of scripts client side based on what's going on server side. I think you can get what you want with the modal using this approach?


问:
Jackson databind enum case insensitive
How can I deserialize  JSON string that contains enum values that are case insensitive? (using Jackson Databind)

The JSON string:

```<code>[{"url": "foo", "type": "json"}]
</code>```

and my Java POJO:

```<code>public static class Endpoint {

    public enum DataType {
        JSON, HTML
    }

    public String url;
    public DataType type;

    public Endpoint() {

    }

}
</code>```

in this case,deserializing the JSON with "type":"json" would fail where as "type":"JSON" would work.
But I want "json" to work as well for naming convention reasons.

Serializing the POJO also results in upper case "type":"JSON"

I thought of using @JsonCreator and @JsonGetter:

```<code>    @JsonCreator
    private Endpoint(@JsonProperty("name") String url, @JsonProperty("type") String type) {
        this.url = url;
        this.type = DataType.valueOf(type.toUpperCase());
    }

    //....
    @JsonGetter
    private String getType() {
        return type.name().toLowerCase();
    }
</code>```

And it worked. But I was wondering whether there's a better solutuon because this looks like a hack to me.

I can also write a custom deserializer but I got many different POJOs that use enums and it would be hard to maintain.

Can anyone suggest a better way to serialize and deserialize enums with proper naming convention?

I don't want my enums in java to be lowercase!

Here is some test code that I used:

```<code>    String data = "[{\"url\":\"foo\", \"type\":\"json\"}]";
    Endpoint[] arr = new ObjectMapper().readValue(data, Endpoint[].class);
        System.out.println("POJO[]->" + Arrays.toString(arr));
        System.out.println("JSON ->" + new ObjectMapper().writeValueAsString(arr));
</code>```

答:
With apologies to @Konstantin Zyubin, his answer was close to what I needed - but I didn't understand it, so here's how I think it should go:

If you want to deserialize one enum type as case insensitive - i.e. you don't want to, or can't, modify the behavior of the entire application, you can create a custom deserializer just for one type - by sub-classing StdConverter and force Jackson to use it only on the relevant fields using the JsonDeserialize annotation.

Example:

```<code>public class ColorHolder {

  public enum Color {
    RED, GREEN, BLUE
  }

  public static final class ColorParser extends StdConverter<String, Color> {
    @Override
    public Color convert(String value) {
      return Arrays.stream(Color.values())
        .filter(e -> e.getName().equalsIgnoreCase(value.trim()))
        .findFirst()
        .orElseThrow(() -> new IllegalArgumentException("Invalid value '" + value + "'"));
    }
  }

  @JsonDeserialize(converter = ColorParser.class)
  Color color;
}
</code>```

Title: Jackson databind enum case insensitive

Body:
How can I deserialize  JSON string that contains enum values that are case insensitive? (using Jackson Databind)

The JSON string:

[{"url": "foo", "type": "json"}]

and my Java POJO:

public static class Endpoint {

    public enum DataType {
        JSON, HTML
    }

    public String url;
    public DataType type;

    public Endpoint() {

    }

}

in this case,deserializing the JSON with "type":"json" would fail where as "type":"JSON" would work.
But I want "json" to work as well for naming convention reasons.

Serializing the POJO also results in upper case "type":"JSON"

I thought of using @JsonCreator and @JsonGetter:

    @JsonCreator
    private Endpoint(@JsonProperty("name") String url, @JsonProperty("type") String type) {
        this.url = url;
        this.type = DataType.valueOf(type.toUpperCase());
    }

    //....
    @JsonGetter
    private String getType() {
        return type.name().toLowerCase();
    }

And it worked. But I was wondering whether there's a better solutuon because this looks like a hack to me.

I can also write a custom deserializer but I got many different POJOs that use enums and it would be hard to maintain.

Can anyone suggest a better way to serialize and deserialize enums with proper naming convention?

I don't want my enums in java to be lowercase!

Here is some test code that I used:

    String data = "[{\"url\":\"foo\", \"type\":\"json\"}]";
    Endpoint[] arr = new ObjectMapper().readValue(data, Endpoint[].class);
        System.out.println("POJO[]->" + Arrays.toString(arr));
        System.out.println("JSON ->" + new ObjectMapper().writeValueAsString(arr));

Body:
With apologies to @Konstantin Zyubin, his answer was close to what I needed - but I didn't understand it, so here's how I think it should go:

If you want to deserialize one enum type as case insensitive - i.e. you don't want to, or can't, modify the behavior of the entire application, you can create a custom deserializer just for one type - by sub-classing StdConverter and force Jackson to use it only on the relevant fields using the JsonDeserialize annotation.

Example:

public class ColorHolder {

  public enum Color {
    RED, GREEN, BLUE
  }

  public static final class ColorParser extends StdConverter<String, Color> {
    @Override
    public Color convert(String value) {
      return Arrays.stream(Color.values())
        .filter(e -> e.getName().equalsIgnoreCase(value.trim()))
        .findFirst()
        .orElseThrow(() -> new IllegalArgumentException("Invalid value '" + value + "'"));
    }
  }

  @JsonDeserialize(converter = ColorParser.class)
  Color color;
}


问:
Converting old AS2 script to AS3
I have just got my self into coding however I'm still learning and after searching everywhere last week I have given up.

I have a an old AS2 sript that I have compiled from various sources and created a count up clock for a friend website. Now the issue I have is that we all know flash will not be supported for much longer and is currently being phased out. Since this is the case can someone please convert the following code to AS3 or perhaps into JavaScript.

I have tried looking at countdown timers in AS3 but for the life of me I can't figure this out.

I hope someone can help of point me in the right direction.

Thank you for your help in advance.

```<code>// set date variables
var year = 1961;
var month = 3; // (number -1 as zero indexed array)
var day = 28;
var hour = 16; // (24 hour)
var minute = 40;
var second = 0;
start = new Date(year, month, day, hour, minute, second);

function calcAge() {
var now = new Date();
var o = new Object();

o.calendar_years = now.getYear()-start.getYear();
o.calendar_months = now.getMonth()-start.getMonth();
o.calendar_days = now.getDate()-start.getDate();
o.calendar_hours = now.getHours()-start.getHours();
o.calendar_minutes = now.getMinutes()-start.getMinutes();
o.calendar_second = now.getSeconds()-start.getSeconds();

if (o.calendar_second<0) {
    o.calendar_second += 60;
    o.calendar_second--;
}
if (o.calendar_minutes<0) {
    o.calendar_minutes += 60;
    o.calendar_hours--;
}
if (o.calendar_hours<0) {
    o.calendar_hours += 24;
    o.calendar_days--;
}
if (o.calendar_days<0) {
    // Days need to be taken from first day of the month
    var nextmonth = new Date(now.getYear(), now.getMonth(), 32);
    o.calendar_days += 32-nextmonth.getDate();
    o.calendar_months--;
}
if (o.calendar_months<0) {
    o.calendar_months += 12;
    o.calendar_years--;
}
return o;
}

function getAge(){
age = calcAge();
years_txt.text = age.calendar_years;
months_txt.text = age.calendar_months;
day_txt.text = age.calendar_days;
hour_txt.text = age.calendar_hours;
mins_txt.text = age.calendar_minutes;
sec_txt.text = age.calendar_second;
}

var intervalID = setInterval( getAge, 1000 );
</code>```

答:
Your code is already pretty close to javascript, as AS2/AS3 are ECMA Script based, and thus pretty transferable.

The major issue, is that you are updating multiple text objects that don't exist.

I changed your code so it assigns the text to the innerHTML of a div with the id = "ageOutDiv".

I also changed the name of the function getAge to outputAge, because you aren't returning / "getting" a value.

// set date variables
var year = 1961;
var month = 3; // (number -1 as zero indexed array)
var day = 28;
var hour = 16; // (24 hour)
var minute = 40;
var second = 0;

var ageOutDiv = document.getElementById('ageOutDiv');

start = new Date(year, month, day, hour, minute, second);

function calcAge() {
  var now = new Date();
  var o = new Object();

  o.calendar_years = now.getYear()-start.getYear();
  o.calendar_months = now.getMonth()-start.getMonth();
  o.calendar_days = now.getDate()-start.getDate();
  o.calendar_hours = now.getHours()-start.getHours();
  o.calendar_minutes = now.getMinutes()-start.getMinutes();
  o.calendar_second = now.getSeconds()-start.getSeconds();

  if (o.calendar_second<0) {
      o.calendar_second += 60;
      o.calendar_second--;
  }
  if (o.calendar_minutes<0) {
      o.calendar_minutes += 60;
      o.calendar_hours--;
  }
  if (o.calendar_hours<0) {
      o.calendar_hours += 24;
      o.calendar_days--;
  }
  if (o.calendar_days<0) {
      // Days need to be taken from first day of the month
      var nextmonth = new Date(now.getYear(), now.getMonth(), 32);
      o.calendar_days += 32-nextmonth.getDate();
      o.calendar_months--;
  }
  if (o.calendar_months<0) {
      o.calendar_months += 12;
      o.calendar_years--;
  }
  return o;
}

function outputAge(){
  age = calcAge();
  var str = "";
  str+="Year: "+age.calendar_years+"
";
  str+="Month: "+age.calendar_months+"
";
  str+="Days: "+age.calendar_days+"
";
  str+="Hours:"+ age.calendar_hours+"
";
  str+="Minutes:"+age.calendar_minutes+"
";
  str+="Seconds:"+age.calendar_second;
  ageOutDiv.innerHTML=str;
}

var intervalID = setInterval(outputAge,1000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="ageOutDiv"></div></code>```

Title: Converting old AS2 script to AS3

Body:
I have just got my self into coding however I'm still learning and after searching everywhere last week I have given up.

I have a an old AS2 sript that I have compiled from various sources and created a count up clock for a friend website. Now the issue I have is that we all know flash will not be supported for much longer and is currently being phased out. Since this is the case can someone please convert the following code to AS3 or perhaps into JavaScript.

I have tried looking at countdown timers in AS3 but for the life of me I can't figure this out.

I hope someone can help of point me in the right direction.

Thank you for your help in advance.

// set date variables
var year = 1961;
var month = 3; // (number -1 as zero indexed array)
var day = 28;
var hour = 16; // (24 hour)
var minute = 40;
var second = 0;
start = new Date(year, month, day, hour, minute, second);

function calcAge() {
var now = new Date();
var o = new Object();

o.calendar_years = now.getYear()-start.getYear();
o.calendar_months = now.getMonth()-start.getMonth();
o.calendar_days = now.getDate()-start.getDate();
o.calendar_hours = now.getHours()-start.getHours();
o.calendar_minutes = now.getMinutes()-start.getMinutes();
o.calendar_second = now.getSeconds()-start.getSeconds();

if (o.calendar_second<0) {
    o.calendar_second += 60;
    o.calendar_second--;
}
if (o.calendar_minutes<0) {
    o.calendar_minutes += 60;
    o.calendar_hours--;
}
if (o.calendar_hours<0) {
    o.calendar_hours += 24;
    o.calendar_days--;
}
if (o.calendar_days<0) {
    // Days need to be taken from first day of the month
    var nextmonth = new Date(now.getYear(), now.getMonth(), 32);
    o.calendar_days += 32-nextmonth.getDate();
    o.calendar_months--;
}
if (o.calendar_months<0) {
    o.calendar_months += 12;
    o.calendar_years--;
}
return o;
}

function getAge(){
age = calcAge();
years_txt.text = age.calendar_years;
months_txt.text = age.calendar_months;
day_txt.text = age.calendar_days;
hour_txt.text = age.calendar_hours;
mins_txt.text = age.calendar_minutes;
sec_txt.text = age.calendar_second;
}

var intervalID = setInterval( getAge, 1000 );

Body:
Your code is already pretty close to javascript, as AS2/AS3 are ECMA Script based, and thus pretty transferable.

The major issue, is that you are updating multiple text objects that don't exist.

I changed your code so it assigns the text to the innerHTML of a div with the id = "ageOutDiv".

I also changed the name of the function getAge to outputAge, because you aren't returning / "getting" a value.

// set date variables
var year = 1961;
var month = 3; // (number -1 as zero indexed array)
var day = 28;
var hour = 16; // (24 hour)
var minute = 40;
var second = 0;

var ageOutDiv = document.getElementById('ageOutDiv');

start = new Date(year, month, day, hour, minute, second);

function calcAge() {
  var now = new Date();
  var o = new Object();

  o.calendar_years = now.getYear()-start.getYear();
  o.calendar_months = now.getMonth()-start.getMonth();
  o.calendar_days = now.getDate()-start.getDate();
  o.calendar_hours = now.getHours()-start.getHours();
  o.calendar_minutes = now.getMinutes()-start.getMinutes();
  o.calendar_second = now.getSeconds()-start.getSeconds();

  if (o.calendar_second<0) {
      o.calendar_second += 60;
      o.calendar_second--;
  }
  if (o.calendar_minutes<0) {
      o.calendar_minutes += 60;
      o.calendar_hours--;
  }
  if (o.calendar_hours<0) {
      o.calendar_hours += 24;
      o.calendar_days--;
  }
  if (o.calendar_days<0) {
      // Days need to be taken from first day of the month
      var nextmonth = new Date(now.getYear(), now.getMonth(), 32);
      o.calendar_days += 32-nextmonth.getDate();
      o.calendar_months--;
  }
  if (o.calendar_months<0) {
      o.calendar_months += 12;
      o.calendar_years--;
  }
  return o;
}

function outputAge(){
  age = calcAge();
  var str = "";
  str+="Year: "+age.calendar_years+"<br>";
  str+="Month: "+age.calendar_months+"<br>";
  str+="Days: "+age.calendar_days+"<br>";
  str+="Hours:"+ age.calendar_hours+"<br>";
  str+="Minutes:"+age.calendar_minutes+"<br>";
  str+="Seconds:"+age.calendar_second;
  ageOutDiv.innerHTML=str;
}

var intervalID = setInterval(outputAge,1000);

<div id="ageOutDiv"></div>


问:
Sending an int from Java to C using sockets
I was just wondering how to send an int from a Java application to a C application using sockets. I have got different C programs communicating with each other and have got the Java application retrieving data from the C application, but I can't work out sending.

The C application is acting as database, the Java application then sends a user id (a 4 digit number) to the C application, if it exists it returns that record's details.

In Java I have tried using a printWriter and DataOutputStream to send the data, printWriter produces weird symbols and DataOutputStream produces "prof_agent.so".

Any help would be appreciated as I don't have a good grasp of sockets at the moment.

答:
It's a bit too late but let this answer be here. Using UDP sockets:

Java code:

```<code>public void runJavaSocket() {
            System.out.println("Java Sockets Program has started."); int i=0;
    try {
            DatagramSocket socket = new DatagramSocket();
            System.out.println("Sending the udp socket...");
            // Send the Message "HI"
            socket.send(toDatagram("HI",InetAddress.getByName("127.0.0.1"),3800));
            while (true)
            {
              System.out.println("Sending hi " + i);
              Thread.currentThread();
              Thread.sleep(1000);
              socket.send(toDatagram("HI " +             String.valueOf(i),InetAddress.getByName("127.0.0.1"),3800));
                    i++;
            }
        }
    catch (Exception e)
    {
         e.printStackTrace();
    }
}

public DatagramPacket toDatagram(
          String s, InetAddress destIA, int destPort) {
    // Deprecated in Java 1.1, but it works:
    byte[] buf = new byte[s.length() + 1];
    s.getBytes(0, s.length(), buf, 0);
    // The correct Java 1.1 approach, but it's
    // Broken (it truncates the String):
    // byte[] buf = s.getBytes();
    return new DatagramPacket(buf, buf.length,
    destIA, destPort);
    }
</code>```

C# code:

```<code>        string returnData;
        byte[] receiveBytes;
        //ConsoleKeyInfo cki = new ConsoleKeyInfo();

        using (UdpClient udpClient = new UdpClient(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3800)))
        {
            IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3800);
            while (true)
            {
                receiveBytes = udpClient.Receive(ref remoteIpEndPoint);
                returnData = Encoding.ASCII.GetString(receiveBytes);
                Console.WriteLine(returnData);
            }
        }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
It's a bit too late but let this answer be here. Using UDP sockets:

Java code:

public void runJavaSocket() {
            System.out.println("Java Sockets Program has started."); int i=0;
    try {
            DatagramSocket socket = new DatagramSocket();
            System.out.println("Sending the udp socket...");
            // Send the Message "HI"
            socket.send(toDatagram("HI",InetAddress.getByName("127.0.0.1"),3800));
            while (true)
            {
              System.out.println("Sending hi " + i);
              Thread.currentThread();
              Thread.sleep(1000);
              socket.send(toDatagram("HI " +             String.valueOf(i),InetAddress.getByName("127.0.0.1"),3800));
                    i++;
            }
        }
    catch (Exception e)
    {
         e.printStackTrace();
    }
}

public DatagramPacket toDatagram(
          String s, InetAddress destIA, int destPort) {
    // Deprecated in Java 1.1, but it works:
    byte[] buf = new byte[s.length() + 1];
    s.getBytes(0, s.length(), buf, 0);
    // The correct Java 1.1 approach, but it's
    // Broken (it truncates the String):
    // byte[] buf = s.getBytes();
    return new DatagramPacket(buf, buf.length,
    destIA, destPort);
    }

C# code:

        string returnData;
        byte[] receiveBytes;
        //ConsoleKeyInfo cki = new ConsoleKeyInfo();

        using (UdpClient udpClient = new UdpClient(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3800)))
        {
            IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3800);
            while (true)
            {
                receiveBytes = udpClient.Receive(ref remoteIpEndPoint);
                returnData = Encoding.ASCII.GetString(receiveBytes);
                Console.WriteLine(returnData);
            }
        }


问:
Aws lambda vs aws batch
I am currently working on a project where I need to merge two significantly large csv files into one(both are a few hundred MBs). I am fairly new to aws. I am aware of memory allocation and execution time limitations of lambda. Other than that are there any advantages of using batch jobs over lambda for this project? Is there any other aws component which more suitable for this task? Either lambda or batch job will be triggered inside a step function using a sns notification.</p>

答: Try using a Python function in Lambda that writes to S3 with boto3.</p>

Title: Aws lambda vs aws batch


问:
How to extract particular values from a factor store as column value in dataframe
I have a data frame with the following columns :

```<code>df <- A B C
    heart_rate  ['53.0', '1']   94
    heart_rate  ['54.0', '2']   1
    heart_rate  ['54.0', '1']   9
    heart_rate  ['55.0', '0']   1
    heart_rate  ['55.0', '1']   7
</code>```

How to read the df1 which just stores one value for cases where we have y= 1 for B[x,y].Which means :

Output desired dataframe df1

```<code>  df1

    A B C
    heart_rate  53.0    94
    heart_rate  54.0    9
    heart_rate  55.0    7

    structure(list(source = structure(c(1L, 1L, 1L), .Label = "heart_rate", class = "factor"),
        values = structure(3:1, .Label = c("['171.0', '1']", "['172.0', '1']",
        "['173.0', '0']"), class = "factor"), timediff = c(6L, 7L,
        10L)), class = "data.frame", row.names = c(NA, -3L))
</code>```

答:
We can do this with parse_number after filtering

```<code>library(dplyr)
library(stringr)
df %>%
    filter(str_detect(B, "1\\]")) %>%
    mutate(B = readr::parse_number(as.character(B)))
#           A  B  C
#1 heart_rate 53 94
#2 heart_rate 54  9
#3 heart_rate 55  7
</code>```

Or another option is base R

```<code>transform(subset(cbind(df, read.csv(text = gsub("[][ ]", "",
      df$B), header = FALSE)), V2 == 1), B = V1)[names(df)]
#           A  B  C
#1 heart_rate 53 94
#3 heart_rate 54  9
#5 heart_rate 55  7
</code>```

data

```<code>df <- structure(list(A = structure(c(1L, 1L, 1L, 1L, 1L),
.Label = "heart_rate", class = "factor"),
B = structure(c(1L, 3L, 2L, 4L, 5L), .Label = c("[53.0, 1]",
"[54.0, 1]", "[54.0, 2]", "[55.0, 0]", "[55.0, 1]"), class = "factor"),
C = c(94L, 1L, 9L, 1L, 7L)), class = "data.frame", row.names = c(NA, -5L))
</code>```

Body:
I have a data frame with the following columns :

df <- A B C
    heart_rate  ['53.0', '1']   94
    heart_rate  ['54.0', '2']   1
    heart_rate  ['54.0', '1']   9
    heart_rate  ['55.0', '0']   1
    heart_rate  ['55.0', '1']   7

How to read the df1 which just stores one value for cases where we have y= 1 for B[x,y].Which means :

Output desired dataframe df1

  df1

    A B C
    heart_rate  53.0    94
    heart_rate  54.0    9
    heart_rate  55.0    7

    structure(list(source = structure(c(1L, 1L, 1L), .Label = "heart_rate", class = "factor"),
        values = structure(3:1, .Label = c("['171.0', '1']", "['172.0', '1']",
        "['173.0', '0']"), class = "factor"), timediff = c(6L, 7L,
        10L)), class = "data.frame", row.names = c(NA, -3L))

Body:
We can do this with parse_number after filtering

library(dplyr)
library(stringr)
df %>%
    filter(str_detect(B, "1\\]")) %>%
    mutate(B = readr::parse_number(as.character(B)))
#           A  B  C
#1 heart_rate 53 94
#2 heart_rate 54  9
#3 heart_rate 55  7

Or another option is base R

transform(subset(cbind(df, read.csv(text = gsub("[][ ]", "",
      df$B), header = FALSE)), V2 == 1), B = V1)[names(df)]
#           A  B  C
#1 heart_rate 53 94
#3 heart_rate 54  9
#5 heart_rate 55  7

data

df <- structure(list(A = structure(c(1L, 1L, 1L, 1L, 1L),
.Label = "heart_rate", class = "factor"),
B = structure(c(1L, 3L, 2L, 4L, 5L), .Label = c("[53.0, 1]",
"[54.0, 1]", "[54.0, 2]", "[55.0, 0]", "[55.0, 1]"), class = "factor"),
C = c(94L, 1L, 9L, 1L, 7L)), class = "data.frame", row.names = c(NA, -5L))


问:
How to read bunch of message from Azure Service Bus - subscription using Python?
I am new to python, I am trying to pull data from Azure Service Bus from subscription using python

I am running below code but throwing error

```<code>with subscription_client.get_receiver() as queue_receiver:
    messages = queue_receiver.fetch_next(timeout=3)
    for message in messages:
        print(message)
        message.complete()
</code>```

Error:-

azure.servicebus.common.errors.ServiceBusConnectionError: Failed to
  open handler: Unable to open authentication session on connection

Thanks in advance

答: Seems you need to open up the  specific ports, could be 5671 and 5672

Body:
I am new to python, I am trying to pull data from Azure Service Bus from subscription using python

I am running below code but throwing error

with subscription_client.get_receiver() as queue_receiver:
    messages = queue_receiver.fetch_next(timeout=3)
    for message in messages:
        print(message)
        message.complete()

Error:-

azure.servicebus.common.errors.ServiceBusConnectionError: Failed to
  open handler: Unable to open authentication session on connection

Thanks in advance


问:
Recommended MySQL INDEX for storing domain names
I'm trying to store about 100 Million domain names in a MySQL database, but I can't figure out the right INDEX method to use on the domain names.

The issue being that LIKE queries will also be executed:

```<code>SELECT id FROM domains WHERE domain LIKE '%.example.com'
</code>```

or

```<code>SELECT id FROM domains WHERE domain LIKE 'example.%'
</code>```

If it makes it easier, '%example%' is not a requirement, but at best a nice to have / be able to.

What would be the proper index to use? Left to right (example.%) should be realitivly straight forward, but right to left (%.example.com) is problematic but the most common query.

I'm using MariaDB 10.3 on Linux. DB running on a PCI-e SSD, lookup times longer then 10 seconds should be coincided "unacceptable"

答:
You can spend one virtual permanent column (rdomain) in your table where the virtual function stores the domainname in reverse order like REVERSE(domain). so it is possible to search from start of string i.e. search for '%.mydomain.com' -> WHERE rdomain like REVERSE('%.mydomain.com

the table

```<code>CREATE TABLE `myreverse` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `domain` varchar(64) CHARACTER SET latin1 DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_domain` (`domain`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
</code>```

add the column

```<code>ALTER TABLE myreverse
ADD COLUMN rdomain VARCHAR(64) AS  (REVERSE(domain)),
ADD KEY idx_rdomain (rdomain);
</code>```

insert some data

```<code>INSERT INTO `myreverse` (`id`, `domain`)
VALUES
    (2, 'img.google.com'),
    (3, 'w3.google.com'),
    (1, 'www.coogle.com'),
    (4, 'www.google.de'),
    (5, 'www.mydomain.com');
</code>```

see the data

```<code>mysql> SELECT * from myreverse;
+----+------------------+------------------+
| id | domain           | rdomain          |
+----+------------------+------------------+
|  1 | www.google.com   | moc.elgoog.www   |
|  2 | img.google.com   | moc.elgoog.gmi   |
|  3 | w3.coogle.com    | moc.elgooc.3w    |
|  4 | www.google.de    | ed.elgoog.www    |
|  5 | www.mydomain.com | moc.niamodym.www |
+----+------------------+------------------+
5 rows in set (0.01 sec)

mysql>
</code>```

now you can query with reverse order and MySQL can use the index.

query

```<code>mysql> select * from myreverse WHERE rdomain like REVERSE('%.google.com');
+----+----------------+----------------+
| id | domain         | rdomain        |
+----+----------------+----------------+
|  3 | w3.google.com  | moc.elgoog.3w  |
|  2 | img.google.com | moc.elgoog.gmi |
+----+----------------+----------------+
2 rows in set (0.00 sec)

mysql>
</code>```

Here you can see that the optimizer use the index.

```<code>mysql> EXPLAIN select * from myreverse WHERE rdomain like REVERSE('%.google.com');
+----+-------------+-----------+------------+-------+---------------+-------------+---------+------+------+----------+-------------+
| id | select_type | table     | partitions | type  | possible_keys | key         | key_len | ref  | rows | filtered | Extra       |
+----+-------------+-----------+------------+-------+---------------+-------------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | myreverse | NULL       | range | idx_rdomain   | idx_rdomain | 195     | NULL |    2 |   100.00 | Using where |
+----+-------------+-----------+------------+-------+---------------+-------------+---------+------+------+----------+-------------+
1 row in set, 1 warning (0.01 sec)

mysql>
</code>```

Body:
I'm trying to store about 100 Million domain names in a MySQL database, but I can't figure out the right INDEX method to use on the domain names.

The issue being that LIKE queries will also be executed:

SELECT id FROM domains WHERE domain LIKE '%.example.com'

or

SELECT id FROM domains WHERE domain LIKE 'example.%'

If it makes it easier, '%example%' is not a requirement, but at best a nice to have / be able to.

What would be the proper index to use? Left to right (example.%) should be realitivly straight forward, but right to left (%.example.com) is problematic but the most common query.

I'm using MariaDB 10.3 on Linux. DB running on a PCI-e SSD, lookup times longer then 10 seconds should be coincided "unacceptable"

Body:
You can spend one virtual permanent column (rdomain) in your table where the virtual function stores the domainname in reverse order like REVERSE(domain). so it is possible to search from start of string i.e. search for '%.mydomain.com' -> WHERE rdomain like REVERSE('%.mydomain.com

the table

CREATE TABLE `myreverse` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `domain` varchar(64) CHARACTER SET latin1 DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_domain` (`domain`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

add the column

ALTER TABLE myreverse
ADD COLUMN rdomain VARCHAR(64) AS  (REVERSE(domain)),
ADD KEY idx_rdomain (rdomain);

insert some data

INSERT INTO `myreverse` (`id`, `domain`)
VALUES
    (2, 'img.google.com'),
    (3, 'w3.google.com'),
    (1, 'www.coogle.com'),
    (4, 'www.google.de'),
    (5, 'www.mydomain.com');

see the data

mysql> SELECT * from myreverse;
+----+------------------+------------------+
| id | domain           | rdomain          |
+----+------------------+------------------+
|  1 | www.google.com   | moc.elgoog.www   |
|  2 | img.google.com   | moc.elgoog.gmi   |
|  3 | w3.coogle.com    | moc.elgooc.3w    |
|  4 | www.google.de    | ed.elgoog.www    |
|  5 | www.mydomain.com | moc.niamodym.www |
+----+------------------+------------------+
5 rows in set (0.01 sec)

mysql>

now you can query with reverse order and MySQL can use the index.

query

mysql> select * from myreverse WHERE rdomain like REVERSE('%.google.com');
+----+----------------+----------------+
| id | domain         | rdomain        |
+----+----------------+----------------+
|  3 | w3.google.com  | moc.elgoog.3w  |
|  2 | img.google.com | moc.elgoog.gmi |
+----+----------------+----------------+
2 rows in set (0.00 sec)

mysql>

Here you can see that the optimizer use the index.

mysql> EXPLAIN select * from myreverse WHERE rdomain like REVERSE('%.google.com');
+----+-------------+-----------+------------+-------+---------------+-------------+---------+------+------+----------+-------------+
| id | select_type | table     | partitions | type  | possible_keys | key         | key_len | ref  | rows | filtered | Extra       |
+----+-------------+-----------+------------+-------+---------------+-------------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | myreverse | NULL       | range | idx_rdomain   | idx_rdomain | 195     | NULL |    2 |   100.00 | Using where |
+----+-------------+-----------+------------+-------+---------------+-------------+---------+------+------+----------+-------------+
1 row in set, 1 warning (0.01 sec)

mysql>


问:
Compute execution time of membership search of generator in python
I'm currently working with generators and factorials in python.
As an example:
itertools.permutations(range(100))
Meaning, I receive a generator object containing 100! values.

In reality, this code does look a bit more complicated; I'm using a list of sublists instead of range(100), with the goal to find a combination of those sublists meeting my conditions.

This is the code:

```<code>mylist = [[0, 0, 1], ..., [5, 7, 3]] # random numbers
x = True in (combination for combination in itertools.permutations(mylist)
             if compare(combination))
# Compare() does return True for one or a few combination in that generator
</code>```

I realized this is very time-consuming. Is there a more efficient way to do this, and, moreover, a way to compute how many time it is going to take?

I've done a few %timeit using ipython:

```<code>%timeit (combination for combination in itertools.permutations(mylist) if compare(combination))
 --> 697 ns

%timeit (combination for combination in itertools.permutations(range(100)) if compare(combination))
 --> 572 ns
</code>```

Note: I do understand that the generator is just being created, when it's "consumed", meaning the genertor comprehension needs to be executed at first, to start the creaton of itself at all.

I've seen a lot of tutorials explaining how generators do work, but I've found nothing about the execution time.
Moreover I don't need an exact value, like timing the execution time using time-module in my program, hence I need a rough value before execution.

Edit:
I've also tested this for a smaller amount of values, for a list containing 24 sublists, 10 sublists and 5 sublists. Doing this, I receive an instant output.
This means, the program does work, it is just a matter of time.

My problem is (said more clarified): How much time is this going to take, and: Is there a less time consuming way to do it?

答:
A comparison of generators, generator expression, lists and list comprehensions:

```<code>In [182]: range(5)
Out[182]: range(0, 5)
In [183]: list(range(5))
Out[183]: [0, 1, 2, 3, 4]
In [184]: (x for x in range(5))
Out[184]: <generator object <genexpr> at 0x7fc18cd88a98>
In [186]: [x for x in range(5)]
Out[186]: [0, 1, 2, 3, 4]
</code>```

Some timings:

```<code>In [187]: timeit range(1000)
248 ns ± 2.79 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [188]: timeit (x for x in range(1000))
802 ns ± 6.97 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [189]: timeit [x for x in range(1000)]
43.4 µs ± 27.2 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [190]: timeit list(range(1000))
23.6 µs ± 1.03 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
</code>```

time for setting up a generator is (practically) independent of the parameter.  Populating the list scales roughly with the size.

```<code>In [193]: timeit range(100000)
252 ns ± 1.57 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [194]: timeit list(range(100000))
4.41 ms ± 103 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code>```

edit

Timings show that a in test on a generator is somewhat faster than a list, but it still scales with the len:

```<code>In [264]: timeit True in  (True for x in itertools.permutations(range(15),2) if x==(14,4))
17.1 µs ± 17.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [265]: timeit list (True for x in itertools.permutations(range(15),2) if x==(14,4))
18.5 µs ± 158 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [266]: timeit (14,4) in itertools.permutations(range(15),2)
8.85 µs ± 8.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [267]: timeit list(itertools.permutations(range(15),2))
11.3 µs ± 21.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code>```

Body:
I'm currently working with generators and factorials in python.
As an example:
itertools.permutations(range(100))
Meaning, I receive a generator object containing 100! values.

In reality, this code does look a bit more complicated; I'm using a list of sublists instead of range(100), with the goal to find a combination of those sublists meeting my conditions.

This is the code:

mylist = [[0, 0, 1], ..., [5, 7, 3]] # random numbers
x = True in (combination for combination in itertools.permutations(mylist)
             if compare(combination))
# Compare() does return True for one or a few combination in that generator

I realized this is very time-consuming. Is there a more efficient way to do this, and, moreover, a way to compute how many time it is going to take?

I've done a few %timeit using ipython:

%timeit (combination for combination in itertools.permutations(mylist) if compare(combination))
 --> 697 ns

%timeit (combination for combination in itertools.permutations(range(100)) if compare(combination))
 --> 572 ns

Note: I do understand that the generator is just being created, when it's "consumed", meaning the genertor comprehension needs to be executed at first, to start the creaton of itself at all.

I've seen a lot of tutorials explaining how generators do work, but I've found nothing about the execution time.
Moreover I don't need an exact value, like timing the execution time using time-module in my program, hence I need a rough value before execution.

Edit:
I've also tested this for a smaller amount of values, for a list containing 24 sublists, 10 sublists and 5 sublists. Doing this, I receive an instant output.
This means, the program does work, it is just a matter of time.

My problem is (said more clarified): How much time is this going to take, and: Is there a less time consuming way to do it?

Body:
A comparison of generators, generator expression, lists and list comprehensions:

In [182]: range(5)
Out[182]: range(0, 5)
In [183]: list(range(5))
Out[183]: [0, 1, 2, 3, 4]
In [184]: (x for x in range(5))
Out[184]: <generator object <genexpr> at 0x7fc18cd88a98>
In [186]: [x for x in range(5)]
Out[186]: [0, 1, 2, 3, 4]

Some timings:

In [187]: timeit range(1000)
248 ns ± 2.79 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [188]: timeit (x for x in range(1000))
802 ns ± 6.97 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [189]: timeit [x for x in range(1000)]
43.4 µs ± 27.2 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [190]: timeit list(range(1000))
23.6 µs ± 1.03 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

time for setting up a generator is (practically) independent of the parameter.  Populating the list scales roughly with the size.

In [193]: timeit range(100000)
252 ns ± 1.57 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [194]: timeit list(range(100000))
4.41 ms ± 103 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

edit

Timings show that a in test on a generator is somewhat faster than a list, but it still scales with the len:

In [264]: timeit True in  (True for x in itertools.permutations(range(15),2) if x==(14,4))
17.1 µs ± 17.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [265]: timeit list (True for x in itertools.permutations(range(15),2) if x==(14,4))
18.5 µs ± 158 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [266]: timeit (14,4) in itertools.permutations(range(15),2)
8.85 µs ± 8.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [267]: timeit list(itertools.permutations(range(15),2))
11.3 µs ± 21.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)


问:
Unsupported architecture - Shared Enum between Metal and Swift
I try to share an Enum that I defined in an Header File between metal and my swift project:

```<code>#ifndef SharedIndizes_h
#define SharedIndizes_h
#import <Foundation/Foundation.h>

#endif /* SharedIndizes_h */

typedef NS_ENUM(NSInteger, VertexAttribute)
{
    VertexAttributePosition = 0,
    VertexAttributeNormal  = 1,
};
</code>```

```<code>#include <metal_stdlib>
#import "ExchangeTypes/SharedIndizes.h"
using namespace metal;

struct VertexIn {
    float3 position [[ attribute(VertexAttributePosition) ]];
    float3 normal [[ attribute(VertexAttributeNormal) ]];
};
</code>```

```<code>vertexDescriptor.attributes[VertexAttribute.position.rawValue]
vertexDescriptor.attributes[VertexAttribute.normal.rawValue]
</code>```

But all I get is some unexpected Errors:

Unsupported architecture

unknown type name '_int64_t'

unknown type name '_int32_t'

...

Removing #import "ExchangeTypes/SharedIndizes.h" from my metal File also removes the errors.

答:
Replace this:

```<code>#ifndef SharedIndizes_h
#define SharedIndizes_h
#import <Foundation/Foundation.h>

#endif /* SharedIndizes_h */

typedef NS_ENUM(NSInteger, VertexAttribute)
{
    VertexAttributePosition = 0,
    VertexAttributeNormal  = 1,
};
</code>```

with this:

```<code>#ifndef SharedIndizes_h
#define SharedIndizes_h

#ifdef __METAL_VERSION__
#define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type
#define NSInteger metal::int32_t
#else

#import <Foundation/Foundation.h>

#endif /* __METAL_VERSION__ */
#endif /* SharedIndizes_h */

typedef NS_ENUM(NSInteger, VertexAttribute)
{
    VertexAttributePosition = 0,
    VertexAttributeNormal  = 1,
};
</code>```

Body:
I try to share an Enum that I defined in an Header File between metal and my swift project:

#ifndef SharedIndizes_h
#define SharedIndizes_h
#import <Foundation/Foundation.h>

#endif /* SharedIndizes_h */

typedef NS_ENUM(NSInteger, VertexAttribute)
{
    VertexAttributePosition = 0,
    VertexAttributeNormal  = 1,
};

#include <metal_stdlib>
#import "ExchangeTypes/SharedIndizes.h"
using namespace metal;

struct VertexIn {
    float3 position [[ attribute(VertexAttributePosition) ]];
    float3 normal [[ attribute(VertexAttributeNormal) ]];
};

vertexDescriptor.attributes[VertexAttribute.position.rawValue]
vertexDescriptor.attributes[VertexAttribute.normal.rawValue]

But all I get is some unexpected Errors:

Unsupported architecture

unknown type name '_int64_t'

unknown type name '_int32_t'

...

Removing #import "ExchangeTypes/SharedIndizes.h" from my metal File also removes the errors.

Body:
Replace this:

#ifndef SharedIndizes_h
#define SharedIndizes_h
#import <Foundation/Foundation.h>

#endif /* SharedIndizes_h */

typedef NS_ENUM(NSInteger, VertexAttribute)
{
    VertexAttributePosition = 0,
    VertexAttributeNormal  = 1,
};

with this:

#ifndef SharedIndizes_h
#define SharedIndizes_h

#ifdef __METAL_VERSION__
#define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type
#define NSInteger metal::int32_t
#else

#import <Foundation/Foundation.h>

#endif /* __METAL_VERSION__ */
#endif /* SharedIndizes_h */

typedef NS_ENUM(NSInteger, VertexAttribute)
{
    VertexAttributePosition = 0,
    VertexAttributeNormal  = 1,
};


问:
How necessary are activation functions after dense layer in neural networks?
I'm currently training multiple recurrent convolutional neural networks with deep q-learning for the first time.

Input is a 11x11x1 matrix, each network consists of 4 convolutional layer with dimensions 3x3x16, 3x3x32, 3x3x64, 3x3x64. I use stride=1 and padding=1. Each convLayer is followed by ReLU activation. The output is fed into a feedforward fully-connected dense layer with 128 units and after that into an LSTM layer, also containing 128 units. Two following dense layer produce separate advantage and value steams.

So training is running for a couple of days now and now I've realized (after I've read some related paper), I didn't add an activation function after the first dense layer (as in most of the papers). I wonder if adding one would significantly improve my network? Since I'm training the networks for university, I don't have unlimited time for training, because of a deadline for my work. However, I don't have enough experience in training neural networks, to decide on what to do...
What do you suggest? I'm thankful for every answer!

答:
If I have to talk in general using an activation function helps you to include some non-linear property in your network.

The purpose of an activation function is to add some kind of non-linear property to the function, which is a neural network. Without the activation functions, the neural network could perform only linear mappings from inputs x to the outputs y. Why is this so?

Without the activation functions, the only mathematical operation during the forward propagation would be dot-products between an input vector and a weight matrix. Since a single dot product is a linear operation, successive dot products would be nothing more than multiple linear operations repeated one after the other. And successive linear operations can be considered as a one single learn operation.

A neural network without any activation function would not be able to realize such complex mappings mathematically and would not be able to solve tasks we want the network to solve.