问:
Merge columns with multiple delimiters
how can I merge columns with variable number of delimiters so I can obtain something like the output (assuming everything is a character)?</p>
```<code> dt1
   letter
1       a
2     b+c
3       c
4 d+e+f+g
5   a+g+e

 dt2
  letter number
1      a      1
2      b      2
3      c      3
4      d      4
5      e      5
6      f      6
7      g      7

> output
   letter  number
1       a       1
2     b+c     2+3
3       c       3
4 d+e+f+g 4+5+6+7
5   a+g+e   1+7+5
</code>```
```<code>dt1<-data.frame(letter=c("a","b+c","c","d+e+f+g","a+g+e"))

dt2<-data.frame(letter=c("a","b","c","d","e","f","g"),number=c("1","2","3","4","5","6","7"))

output<-data.frame(letter=c("a","b+c","c","d+e+f+g","a+g+e"), number=c("1","2+3","3","4+5+6+7","1+7+5"))
</code>```

答:
A fast and readable library(stringi) approach:

```<code>library(stringi)

dt1 <- data.frame(letter=c("a","b+c","c","d+e+f+g","a+g+e"))
dt2 <- data.frame(letter=c("a","b","c","d","e","f","g"), number=c("1","2","3","4","5","6","7"))

dt1$number <- stri_replace_all_fixed(dt1$letter, pattern = dt2$letter, replacement = dt2$number, vectorize_all = FALSE)

dt1
</code>```

Result:

```<code>> dt1
   letter  number
1       a       1
2     b+c     2+3
3       c       3
4 d+e+f+g 4+5+6+7
5   a+g+e   1+7+5
</code>```

Also see this related answer.

Edit: A Benchmark of the currently available answers:

```<code>Unit: microseconds
             expr     min      lq    mean  median      uq     max neval
            Sotos  2689.6  2689.6  2689.6  2689.6  2689.6  2689.6     1
    ismirsehregal    26.4    26.4    26.4    26.4    26.4    26.4     1
              www 42247.8 42247.8 42247.8 42247.8 42247.8 42247.8     1
 MerijnvanTilborg  1723.5  1723.5  1723.5  1723.5  1723.5  1723.5     1
    YuriySaraykin 21859.2 21859.2 21859.2 21859.2 21859.2 21859.2     1
          danlooo  4165.7  4165.7  4165.7  4165.7  4165.7  4165.7     1
</code>```

To reproduce the benchmark:

```<code>library(microbenchmark)
library(tidyverse)
library(stringi)

dt1 <- data.frame(letter=c("a","b+c","c","d+e+f+g","a+g+e"))
dt2 <- data.frame(letter=c("a","b","c","d","e","f","g"), number=c("1","2","3","4","5","6","7"))

microbenchmark(
  Sotos = {
    sapply(strsplit(dt1$letter, '+', fixed = TRUE), function(i)
      paste(dt2$number[dt2$letter %in% i], collapse = '+'))
  },
  ismirsehregal = {
    stri_replace_all_fixed(
      dt1$letter,
      pattern = dt2$letter,
      replacement = dt2$number,
      vectorize_all = FALSE
    )
  },
  www = {
    dt1 %>%
      mutate(ID = 1:n()) %>%
      separate_rows(letter, sep = "\\+") %>%
      left_join(dt2, by = "letter") %>%
      group_by(ID) %>%
      summarize(across(.fns = ~ paste0(., collapse = "+"))) %>%
      ungroup() %>%
      select(-ID)
  },
  MerijnvanTilborg = {
    dt1 %>% mutate(MerijnvanTilborg = stri_replace_all_regex(letter, dt2$letter, dt2$number, vectorize_all = F))
  },
  YuriySaraykin = {
    dt1 %>%
      rowwise() %>%
      mutate(tmp = str_split(letter, pattern = "\\+")) %>%
      ungroup() %>%
      mutate(number = map_chr(tmp, ~ paste0(match(.x, dt2$letter), collapse = "+"))) %>%
      select(-tmp)
  },
  danlooo = {
    dt1 %>%
      as_tibble() %>%
      mutate(number = letter %>% map_chr(
        ~ .x %>%
          str_split("[+]") %>%
          simplify() %>%
          map_chr( ~ deframe(dt2)[.x]) %>%
          paste0(collapse = "+")
      ))
  },
  times = 1L
)
</code>```

Title: Merge columns with multiple delimiters

Body:
how can I merge columns with variable number of delimiters so I can obtain something like the output (assuming everything is a character)?

 dt1
   letter
1       a
2     b+c
3       c
4 d+e+f+g
5   a+g+e

 dt2
  letter number
1      a      1
2      b      2
3      c      3
4      d      4
5      e      5
6      f      6
7      g      7

> output
   letter  number
1       a       1
2     b+c     2+3
3       c       3
4 d+e+f+g 4+5+6+7
5   a+g+e   1+7+5

dt1<-data.frame(letter=c("a","b+c","c","d+e+f+g","a+g+e"))

dt2<-data.frame(letter=c("a","b","c","d","e","f","g"),number=c("1","2","3","4","5","6","7"))

output<-data.frame(letter=c("a","b+c","c","d+e+f+g","a+g+e"), number=c("1","2+3","3","4+5+6+7","1+7+5"))

Body:
A fast and readable library(stringi) approach:

library(stringi)

dt1 <- data.frame(letter=c("a","b+c","c","d+e+f+g","a+g+e"))
dt2 <- data.frame(letter=c("a","b","c","d","e","f","g"), number=c("1","2","3","4","5","6","7"))

dt1$number <- stri_replace_all_fixed(dt1$letter, pattern = dt2$letter, replacement = dt2$number, vectorize_all = FALSE)

dt1

Result:

> dt1
   letter  number
1       a       1
2     b+c     2+3
3       c       3
4 d+e+f+g 4+5+6+7
5   a+g+e   1+7+5

Also see this related answer.

Edit: A Benchmark of the currently available answers:

Unit: microseconds
             expr     min      lq    mean  median      uq     max neval
            Sotos  2689.6  2689.6  2689.6  2689.6  2689.6  2689.6     1
    ismirsehregal    26.4    26.4    26.4    26.4    26.4    26.4     1
              www 42247.8 42247.8 42247.8 42247.8 42247.8 42247.8     1
 MerijnvanTilborg  1723.5  1723.5  1723.5  1723.5  1723.5  1723.5     1
    YuriySaraykin 21859.2 21859.2 21859.2 21859.2 21859.2 21859.2     1
          danlooo  4165.7  4165.7  4165.7  4165.7  4165.7  4165.7     1

To reproduce the benchmark:

library(microbenchmark)
library(tidyverse)
library(stringi)

dt1 <- data.frame(letter=c("a","b+c","c","d+e+f+g","a+g+e"))
dt2 <- data.frame(letter=c("a","b","c","d","e","f","g"), number=c("1","2","3","4","5","6","7"))

microbenchmark(
  Sotos = {
    sapply(strsplit(dt1$letter, '+', fixed = TRUE), function(i)
      paste(dt2$number[dt2$letter %in% i], collapse = '+'))
  },
  ismirsehregal = {
    stri_replace_all_fixed(
      dt1$letter,
      pattern = dt2$letter,
      replacement = dt2$number,
      vectorize_all = FALSE
    )
  },
  www = {
    dt1 %>%
      mutate(ID = 1:n()) %>%
      separate_rows(letter, sep = "\\+") %>%
      left_join(dt2, by = "letter") %>%
      group_by(ID) %>%
      summarize(across(.fns = ~ paste0(., collapse = "+"))) %>%
      ungroup() %>%
      select(-ID)
  },
  MerijnvanTilborg = {
    dt1 %>% mutate(MerijnvanTilborg = stri_replace_all_regex(letter, dt2$letter, dt2$number, vectorize_all = F))
  },
  YuriySaraykin = {
    dt1 %>%
      rowwise() %>%
      mutate(tmp = str_split(letter, pattern = "\\+")) %>%
      ungroup() %>%
      mutate(number = map_chr(tmp, ~ paste0(match(.x, dt2$letter), collapse = "+"))) %>%
      select(-tmp)
  },
  danlooo = {
    dt1 %>%
      as_tibble() %>%
      mutate(number = letter %>% map_chr(
        ~ .x %>%
          str_split("[+]") %>%
          simplify() %>%
          map_chr( ~ deframe(dt2)[.x]) %>%
          paste0(collapse = "+")
      ))
  },
  times = 1L
)


来源: stackexchange

问:
Using xarray interp to reproject a dataarray?
I have looked a lot at the xarray documentation of the interp function and I cannot really make sense of it. I see it is a reprojection but it doesn't really fit a real case example.
Is their someone that could make sense of it for example by reprojecting this dataset on a webmercator datum?

Something like the example:

import xarray as xr
from pyproj import Transformer

ds = xr.tutorial.open_dataset("air_temperature").isel(time=0)
fig, axes = plt.subplots(ncols=2, figsize=(10, 4))
lon, lat = np.meshgrid(ds.lon, ds.lat)
shp = lon.shape
# reproject the grid
gcs_to_3857 = Transformer.from_crs(4326, 3857, always_xy=True)
x, y = gcs_to_3857.transform(lon.ravel(), lat.ravel())
# future index for a regular raster
X= np.linspace(x.min(), x.max(), shp[1])
Y= np.linspace(y.min(), y.max(), shp[0])
data["x"] = xr.DataArray(np.reshape(x, shp), dims=("lat", "lon"))
data["y"] = xr.DataArray(np.reshape(y, shp), dims=("lat", "lon"))

```

And here, I am stuck

Should be something like ds.interp(x=X,y=Y) but the array is indexed on lat lon

It is all a bit confusing to me...

答:
You could also use reproject from rioxarray as suggested.
Here is the code:

```<code>import xarray as xr
import numpy as np
from rasterio.enums import Resampling
import matplotlib.pyplot as plt

ds = xr.tutorial.open_dataset('air_temperature').isel(time=0)
ds = ds.rio.write_crs('EPSG:4326')
dst = ds.rio.reproject('EPSG:3857', shape=(250, 250), resampling=Resampling.bilinear, nodata=np.nan)

fig, ax = plt.subplots(1, 2, figsize=(14, 5))
ds.air.plot(ax=ax[0])
dst.air.plot(ax=ax[1])
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have looked a lot at the xarray documentation of the interp function and I cannot really make sense of it. I see it is a reprojection but it doesn't really fit a real case example.
Is their someone that could make sense of it for example by reprojecting this dataset on a webmercator datum?

Something like the example:

import xarray as xr
from pyproj import Transformer

ds = xr.tutorial.open_dataset("air_temperature").isel(time=0)
fig, axes = plt.subplots(ncols=2, figsize=(10, 4))
lon, lat = np.meshgrid(ds.lon, ds.lat)
shp = lon.shape
# reproject the grid
gcs_to_3857 = Transformer.from_crs(4326, 3857, always_xy=True)
x, y = gcs_to_3857.transform(lon.ravel(), lat.ravel())
# future index for a regular raster
X= np.linspace(x.min(), x.max(), shp[1])
Y= np.linspace(y.min(), y.max(), shp[0])
data["x"] = xr.DataArray(np.reshape(x, shp), dims=("lat", "lon"))
data["y"] = xr.DataArray(np.reshape(y, shp), dims=("lat", "lon"))

And here, I am stuck

Should be something like ds.interp(x=X,y=Y) but the array is indexed on lat lon

It is all a bit confusing to me...

Body:
You could also use reproject from rioxarray as suggested.
Here is the code:

import xarray as xr
import numpy as np
from rasterio.enums import Resampling
import matplotlib.pyplot as plt

ds = xr.tutorial.open_dataset('air_temperature').isel(time=0)
ds = ds.rio.write_crs('EPSG:4326')
dst = ds.rio.reproject('EPSG:3857', shape=(250, 250), resampling=Resampling.bilinear, nodata=np.nan)

fig, ax = plt.subplots(1, 2, figsize=(14, 5))
ds.air.plot(ax=ax[0])
dst.air.plot(ax=ax[1])


问:
SCons builder changes working directory to target file directory
I'm faced with the following situation. There is the simplest example of SCons builder (that does almost nothing) and pseudobuilder:

```<code>#------------------------------------------------
#
#   Builder
#
def slon(target, source, env):

    print(os.getcwd())

    return None

#------------------------------------------------
#
#   Pseudobuilder
#
def launch_slon(env, src):

    trg = src + '.kot'

    return env.Slon(trg, src, env)

#------------------------------------------------

#------------------------------------------------
#
#   Register builders
#
Slon     = Builder(action = slon)

Builders = { 'Slon' : Slon }

env.Append(BUILDERS = Builders)

env.AddMethod(launch_slon, 'LaunchSlon')

...

#------------------------------------------------
#
#   SConsript
#

Import('envx')

...
slon  = envx.LaunchSlon('/opt/pro/fw-snmp/src/sw/main.cpp')

envx.Alias('slon', slon)
</code>```

And launch scons:

```<code>$scons --debug=explain slon

scons: building `src/sw/main.cpp.kot' because it doesn't exist
os.chdir('src/sw')
slon(["src/sw/main.cpp.kot"], ["src/sw/main.cpp"])
/opt/pro/fw-snmp/src/sw
os.chdir('/opt/pro/fw-snmp')
</code>```

As said in SCons documentation the build process is performed from project root directory - where SConstruct resides (/opt/pro/fw-snmp in this case). But SCons performs working directory change to target file directory. That is SCons behavior is as if the chdir=1 option was specified for builder. But is wasn't. This breaks my build process (first, file path lookup doesn't work).

What is the reason of such SCons behavior?

Thank you.

UPDATE.

Here is an archive with the above example: https://drive.google.com/file/d/1USBbMrXtldrYyz0pc49QYmfV0kcZowzs/view?usp=sharing.

Just launch from terminal:

```<code>SCONSFLAGS=-D scons variant=slon1 slon
</code>```

The result:

```<code>scons: Reading SConscript files ...
********************************************************************************
                           build variant: slon1
********************************************************************************

target: ../../../src/sw/main.cpp.kot    |   source: ../../../src/sw/main.cpp
scons: done reading SConscript files.
scons: Building targets ...
os.chdir('src/sw')
slon(["src/sw/main.cpp.kot"], ["src/sw/main.cpp"])
/opt/ssd/pro/slon/scons-bugs/2/scons-chdir/src/sw
os.chdir('/opt/ssd/pro/slon/scons-bugs/2/scons-chdir')
scons: done building targets.

</code>```

UPDATE2.

The above example code as git repo:

https://github.com/harryzhurov/scons-chdir

答:
I've exercised some tests and found that Top directory (where SConstruct should be resided) also changed to target build directory during build phase. To see this I've added debug prints to the builder action function:

```<code>#
# The action function
#
def slon(target, source, env):

    print('>>> Project root directory:   ', os.path.abspath(str(env.Dir('#'))))
    print('>>> Current working directory:', os.getcwd())

    return None

</code>```

Output is (project absolute path is '/opt/scons-chdir'):

```<code>$ scons
scons: Entering directory `/opt/scons-chdir`
...
os.chdir('build')
slon(["build/main.cpp.kot"], ["src/sw/main.cpp"])
>>> Project root directory:    /opt/scons-chdir/build
>>> Current working directory: /opt/scons-chdir/build
os.chdir('/opt/scons-chdir')
</code>```

SConstruct file is resided in '/opt/scons-chdir'.

This explains why scons change directory to build during build phase, but it's still not clear why scons thinks that build is project root directory.

Can anybody explains such behavior?

The above code example is available here: https://github.com/harryzhurov/scons-chdir

Body:
I'm faced with the following situation. There is the simplest example of SCons builder (that does almost nothing) and pseudobuilder:

#------------------------------------------------
#
#   Builder
#
def slon(target, source, env):

    print(os.getcwd())

    return None

#------------------------------------------------
#
#   Pseudobuilder
#
def launch_slon(env, src):

    trg = src + '.kot'

    return env.Slon(trg, src, env)

#------------------------------------------------

#------------------------------------------------
#
#   Register builders
#
Slon     = Builder(action = slon)

Builders = { 'Slon' : Slon }

env.Append(BUILDERS = Builders)

env.AddMethod(launch_slon, 'LaunchSlon')

...

#------------------------------------------------
#
#   SConsript
#

Import('envx')

...
slon  = envx.LaunchSlon('/opt/pro/fw-snmp/src/sw/main.cpp')

envx.Alias('slon', slon)

And launch scons:

$scons --debug=explain slon

scons: building `src/sw/main.cpp.kot' because it doesn't exist
os.chdir('src/sw')
slon(["src/sw/main.cpp.kot"], ["src/sw/main.cpp"])
/opt/pro/fw-snmp/src/sw
os.chdir('/opt/pro/fw-snmp')

As said in SCons documentation the build process is performed from project root directory - where SConstruct resides (/opt/pro/fw-snmp in this case). But SCons performs working directory change to target file directory. That is SCons behavior is as if the chdir=1 option was specified for builder. But is wasn't. This breaks my build process (first, file path lookup doesn't work).

What is the reason of such SCons behavior?

Thank you.

UPDATE.

Here is an archive with the above example: https://drive.google.com/file/d/1USBbMrXtldrYyz0pc49QYmfV0kcZowzs/view?usp=sharing.

Just launch from terminal:

SCONSFLAGS=-D scons variant=slon1 slon

The result:

scons: Reading SConscript files ...
********************************************************************************
                           build variant: slon1
********************************************************************************

target: ../../../src/sw/main.cpp.kot    |   source: ../../../src/sw/main.cpp
scons: done reading SConscript files.
scons: Building targets ...
os.chdir('src/sw')
slon(["src/sw/main.cpp.kot"], ["src/sw/main.cpp"])
/opt/ssd/pro/slon/scons-bugs/2/scons-chdir/src/sw
os.chdir('/opt/ssd/pro/slon/scons-bugs/2/scons-chdir')
scons: done building targets.

UPDATE2.

The above example code as git repo:

https://github.com/harryzhurov/scons-chdir

Body:
I've exercised some tests and found that Top directory (where SConstruct should be resided) also changed to target build directory during build phase. To see this I've added debug prints to the builder action function:

#
# The action function
#
def slon(target, source, env):

    print('>>> Project root directory:   ', os.path.abspath(str(env.Dir('#'))))
    print('>>> Current working directory:', os.getcwd())

    return None

Output is (project absolute path is '/opt/scons-chdir'):

$ scons
scons: Entering directory `/opt/scons-chdir`
...
os.chdir('build')
slon(["build/main.cpp.kot"], ["src/sw/main.cpp"])
>>> Project root directory:    /opt/scons-chdir/build
>>> Current working directory: /opt/scons-chdir/build
os.chdir('/opt/scons-chdir')

SConstruct file is resided in '/opt/scons-chdir'.

This explains why scons change directory to build during build phase, but it's still not clear why scons thinks that build is project root directory.

Can anybody explains such behavior?

The above code example is available here: https://github.com/harryzhurov/scons-chdir


问:
Geodjango + PostGIS. Aggregate polygon area in square meters
I am using geodjango(3.1) + postgis and I want to receive the area of a polygon in square meteres. Therefore, I am using the Geographic Database Functions of Django.

My code looks the following:

City.objects.annotate(area=Area('geom'))

I think the result I am reciving is in degree. When I use the distance function the same way, I get the right result in square meters.

When I am executing ST_Area(geom, use_spheroid=true) as RawSQL, the result also fits and is in square meteres but I would like the avoid RawSQL.

Thanks for any help =)

答:
Note that if you store your geom field as a geography type, the Area function should return square meters instead of degrees.

from django.contrib.gis.db import models as gis_models

class City(gis_models.Model):
    geom = gis_models.PolygonField(geography=True)

…
cities = City.objects.annotate(area=Area('geom'))
cities[0].area.sq_m  # square meters
```


问:
Iteration over data.table
I have a table A with column names: Var1, Var2, Var3.

```<code>Var1 = c("N1", "N2", "0", "0", "N3", "N4", "0", "0")
Var2 = c("0", "A", "0", "0", "0", "B", "0", "0")
Var3 = c("0", "Yes", "No", "All", "0", "x", "y", "z")
</code>```

I would like to obtain vectors based on Table A,  which contains values from column eg: N2 = (Yes, No, All), N4 = (x, y, z).
I have tried few iterations with "for loop" and "logical if" but with no success. Please, give me some hint.

答:
With data.table:

replace the 0s in Var1 by NA

carry forward last occurence of non NA values (using for example zoo::na.locf because data.table::nafill doesnt yet work for characters).

filter according to Var1:

```<code>library(data.table)
data <- data.table(Var1 = c("N1", "N2", "0", "0", "N3", "N4", "0", "0"), Var2 = c("0", "A", "0", "0", "0", "B", "0", "0"), Var3 = c("0", "Yes", "No", "All", "0", "x", "y", "z"))

# replace 0s by NA for next step
data[Var1==0,Var1:=NA]

# last occurence carried forward
data[,Var1:=zoo::na.locf(Var1)]

data[Var1=='N2',Var3]
#[1] "Yes" "No"  "All"

data[Var1=='N4',Var3]
#[1] "x" "y" "z"
</code>```

Title: Iteration over data.table

Body:
I have a table A with column names: Var1, Var2, Var3.

Var1 = c("N1", "N2", "0", "0", "N3", "N4", "0", "0")
Var2 = c("0", "A", "0", "0", "0", "B", "0", "0")
Var3 = c("0", "Yes", "No", "All", "0", "x", "y", "z")

I would like to obtain vectors based on Table A,  which contains values from column eg: N2 = (Yes, No, All), N4 = (x, y, z).
I have tried few iterations with "for loop" and "logical if" but with no success. Please, give me some hint.

Body:
With data.table:

replace the 0s in Var1 by NA

carry forward last occurence of non NA values (using for example zoo::na.locf because data.table::nafill doesnt yet work for characters).

filter according to Var1:

library(data.table)
data <- data.table(Var1 = c("N1", "N2", "0", "0", "N3", "N4", "0", "0"), Var2 = c("0", "A", "0", "0", "0", "B", "0", "0"), Var3 = c("0", "Yes", "No", "All", "0", "x", "y", "z"))

# replace 0s by NA for next step
data[Var1==0,Var1:=NA]

# last occurence carried forward
data[,Var1:=zoo::na.locf(Var1)]

data[Var1=='N2',Var3]
#[1] "Yes" "No"  "All"

data[Var1=='N4',Var3]
#[1] "x" "y" "z"


问:
Understanding C runtimes
I am learning C Language and I have a question.
If I compile and make an executable for C program in say BorlandC on one Windows PC and then transfer this file to another Windows PC which does not have the compiler, how does it run where there is no C runtime and how does the memory management work?</p>

答:
You can do this in a relatively painless way if you use static linking. That means the run time libraries are bound into your executable when you compile/link (on your machine), rather than being loaded up dynamically at run time (on the other machine).

If you use dynamic linking, then the libraries have to be available at run time where you're running the code, so the loader (part of the OS) can find them and link them in.

For a good explanation of the static/dynamic linking differences, see here.

ContentLicense: CC BY-SA 3.0

Title: Understanding C runtimes


问:
Typescript Unsafe return of an `any` typed value
I am creating few date functions for my app and for date validation I am using luxon. All of the functions, I first convert them into string then I am formatting the date. Instead of writing same line every time(to convert them into string), I have decided to create a separate function for this. When add this function my format function, I am getting typescripts error: Unsafe return of an any typed value

Error image

import { DateTime } from 'luxon'

const dateToStrings = (date: Date): string => DateTime.fromISO(new Date(date).toISOString())

export const formatDateMonthYear = (date: string | number | Date): string =>
  dateToStrings(date).toFormat(DEFAULT_DATE_FORMAT)

export const formatTime = (date: string | number | Date): string =>
dateToStrings(date).toFormat(SHORT_TIME_FORMAT)

export const formatYearMonthDate = (date: string | number | Date): string =>
  DateTime.fromISO(new Date(date).toISOString()).toFormat(ISO_DATE_FORMAT)```

答:
Fixing the types in your function should fix you issues :</p>
```<code>const dateToStrings = (date: string | number | Date): DateTime =>
  DateTime.fromISO(new Date(date).toISOString());

export const formatDateMonthYear = (date: string | number | Date): string =>
  dateToStrings(date).toFormat(DEFAULT_DATE_FORMAT);

export const formatTime = (date: string | number | Date): string =>
  dateToStrings(date).toFormat(SHORT_TIME_FORMAT);
</code>```

Body:
Fixing the types in your function should fix you issues :

const dateToStrings = (date: string | number | Date): DateTime =>
  DateTime.fromISO(new Date(date).toISOString());

export const formatDateMonthYear = (date: string | number | Date): string =>
  dateToStrings(date).toFormat(DEFAULT_DATE_FORMAT);

export const formatTime = (date: string | number | Date): string =>
  dateToStrings(date).toFormat(SHORT_TIME_FORMAT);


问:
Replying to a specific msg in telegraf framework
I'm making a telegram bot with telegraf frame work ( it means Node.js )
So I want when someone send good morning The bot will reply to his own msg, I searched alot but i didn't find the answer

Example:-
I want the reply to be like this

答:
The documentation for telegraf is here: https://www.npmjs.com/package/telegraf

From what I have read, this should work:

```<code>const { Telegraf } = require('telegraf')

const bot = new Telegraf(process.env.BOT_TOKEN)
bot.hears('good morning', (ctx) => ctx.reply('Good morning to you too!'))
bot.launch()

// Enable graceful stop
process.once('SIGINT', () => bot.stop('SIGINT'))
process.once('SIGTERM', () => bot.stop('SIGTERM'))
</code>```

This is edited code from the first example in the docs.

Body:
The documentation for telegraf is here: https://www.npmjs.com/package/telegraf

From what I have read, this should work:

const { Telegraf } = require('telegraf')

const bot = new Telegraf(process.env.BOT_TOKEN)
bot.hears('good morning', (ctx) => ctx.reply('Good morning to you too!'))
bot.launch()

// Enable graceful stop
process.once('SIGINT', () => bot.stop('SIGINT'))
process.once('SIGTERM', () => bot.stop('SIGTERM'))

This is edited code from the first example in the docs.


问:
SVG - how to center a rectangle?
I have a simple SVG with two rectangles. I want the "inner" rectangle to be exactly in the middle of the SVG. By setting x and y attributes to 50% the upper left corner is centred. Instead, I want to center the middle of the rectangle. I've tried setting transform-origin to center but it doesn't work.

<svg width="100" height="100">
   <rect width="100%" height="100%" fill="gold" />

   <rect width="30" height="30" x="50%" y="50%" fill="green" />
</svg> ```

How to achieve such functionality without manually specifying x and y attributes?

答:
Here is an alternative that may work in some cases:

<svg width="100" height="100" viewBox="0 0 100 100">
   <rect width="100%" height="100%" fill="gold" />
   <rect width="100%" height="100%" transform-origin="50% 50%" transform="scale(0.3)" fill="green" />
</svg>```

Title: SVG - how to center a rectangle?

Body:
I have a simple SVG with two rectangles. I want the "inner" rectangle to be exactly in the middle of the SVG. By setting x and y attributes to 50% the upper left corner is centred. Instead, I want to center the middle of the rectangle. I've tried setting transform-origin to center but it doesn't work.

<svg width="100" height="100">
   <rect width="100%" height="100%" fill="gold" />

   <rect width="30" height="30" x="50%" y="50%" fill="green" />
</svg>

How to achieve such functionality without manually specifying x and y attributes?


问:
Get function pointers for array appending
I want to determine whether an item should be looped and pushed, or directly pushed to an array.

For this, I have created the following code:

```<code>interface Item {
  prop1: string;
  prop2: string;
  prop3: string[];
}
</code>```

For prop1, prop2, prop3 I need its data in a single string array for each property. So I want to get the corresponding function pointer:

```<code>const items = [...] as Item[];
const collectProperties = ["prop1", "prop2", "prop3"];

// Contains the function pointers for every prop in collectProperties
const appendOperations = [] as ((array: string[], element: any) => void)[];

// Extract function pointers for each prop-type
collectProperties.forEach((element, index) => {
  appendOperations.push(
    Array.isArray(items[0][element as keyof Item])
      ? (array: string[], element: any) =>
          element.forEach((value) => array.push(String(value)));
      : (array: string[], element: any) =>
          array.push(String(element))
  );
});

// Appending items based on its type
items.forEach((item) => {
  appendOperations.forEach((fn, index) => {
    fn(
      // ... some array,
      // ... some value
    );
  });
});
</code>```

I feel like there should be a more compact, elegant way of doing this. I know this can be done in the loop itself as well, but this means there will be an if-check in every property of every element, which is not desired when processing huge chunks of data. Help is appreciated.

答:
There are a couple of things you can do to tighten up the first bit:

Make collectProperties an array of keyof Item rather than an array of strings, so you don't have to use a type assertion later

Use map to build appendProperties rather than creating the array and pushing to it, since it's a one-to-one operation; this also lets you infer its type from the map return type

// *** Use the type on the array so you don't have to use a type assertion later
const collectProperties: (keyof Item)[] = ["prop1", "prop2", "prop3"];

// Contains the function pointers for every prop in collectProperties
// *** `map` is a bit more idiomatic and helps a bit with setting types
const appendOperations = collectProperties.map(propName => {
    // *** Avoiding using `items` for this check since there's no need to make this function
    // dependent on `items`
    return propName === "prop3"
        ? (array: string[], element: any) =>
            element.forEach((value: any) => array.push(String(value)))
        : (array: string[], element: any) =>
            array.push(String(element));
});

// Appending items based on its type
// *** `forEach` is fine, but you could also avoid making functions using `for-of`
for (const item of items) {
    for (const fn of appendOperations) {
        fn(
            // ... some array,
            // ... some value
        );
    }
}
```

For the loop at the end, I couldn't get enough of an idea what it should be doing, but you might consider for-of rather than forEach just to avoid creating unnecessary functions, etc.

Playground link

Body:
I want to determine whether an item should be looped and pushed, or directly pushed to an array.

For this, I have created the following code:

interface Item {
  prop1: string;
  prop2: string;
  prop3: string[];
}

For prop1, prop2, prop3 I need its data in a single string array for each property. So I want to get the corresponding function pointer:

const items = [...] as Item[];
const collectProperties = ["prop1", "prop2", "prop3"];

// Contains the function pointers for every prop in collectProperties
const appendOperations = [] as ((array: string[], element: any) => void)[];

// Extract function pointers for each prop-type
collectProperties.forEach((element, index) => {
  appendOperations.push(
    Array.isArray(items[0][element as keyof Item])
      ? (array: string[], element: any) =>
          element.forEach((value) => array.push(String(value)));
      : (array: string[], element: any) =>
          array.push(String(element))
  );
});

// Appending items based on its type
items.forEach((item) => {
  appendOperations.forEach((fn, index) => {
    fn(
      // ... some array,
      // ... some value
    );
  });
});

I feel like there should be a more compact, elegant way of doing this. I know this can be done in the loop itself as well, but this means there will be an if-check in every property of every element, which is not desired when processing huge chunks of data. Help is appreciated.

Body:
There are a couple of things you can do to tighten up the first bit:

Make collectProperties an array of keyof Item rather than an array of strings, so you don't have to use a type assertion later

Use map to build appendProperties rather than creating the array and pushing to it, since it's a one-to-one operation; this also lets you infer its type from the map return type

// *** Use the type on the array so you don't have to use a type assertion later
const collectProperties: (keyof Item)[] = ["prop1", "prop2", "prop3"];

// Contains the function pointers for every prop in collectProperties
// *** `map` is a bit more idiomatic and helps a bit with setting types
const appendOperations = collectProperties.map(propName => {
    // *** Avoiding using `items` for this check since there's no need to make this function
    // dependent on `items`
    return propName === "prop3"
        ? (array: string[], element: any) =>
            element.forEach((value: any) => array.push(String(value)))
        : (array: string[], element: any) =>
            array.push(String(element));
});

// Appending items based on its type
// *** `forEach` is fine, but you could also avoid making functions using `for-of`
for (const item of items) {
    for (const fn of appendOperations) {
        fn(
            // ... some array,
            // ... some value
        );
    }
}

For the loop at the end, I couldn't get enough of an idea what it should be doing, but you might consider for-of rather than forEach just to avoid creating unnecessary functions, etc.

<a href="https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgJKQLbIN4FgBQyyADlAPbECMAXMgM5hSgDmA3AUaRQEy0NMg2HEuWIBmPoxYBtALrt8AXwIEA9KuQAVABbA6yPcgBWAVwbIYZKMjDaUxADZwAns3ImQAEwA09MsgB3FABrEAD-AO04MGQAA2BMOliDfQCE7TITGKiANxZ6YggEYBhgBGQIBwgMCHB9S2sEgk8ipygUBDIQcwTqulp0arkFNQ0AKgnkAFU6FFs550LkLps7ZDgoKBc-ZGdM5E8ugHJsuBy5-zMUOBtF67pZqDBgFadIKAJO7pjOhyqEMAABVE0GeEH6yAAFMEIHsYGhMABKOTIAC8yGkACIuFRMb5saJuHjkASKGJMfIVPh1MgAMJdMBwUD6eYWDwAl4gEhkUDvepWCrnKDOEQUAxc37-IEgp7AcGjZATMZxDBwYjJQw3ABGCWQGCsKGAnheque5TgXmQdgcxH02t1aVs9AgYGegluhTony65jVhS8AHlCltnj60chJUVpRRQXK6AA6VXESE4gBycBqaIAfDhhEQaUrkABBHI843usz5eKJZINVaGBB2BDBeigJCraAQI76ED+EAQCCeGz+VUw+v1dmhkB55A0lr+lrgZZc6t9WIz9pgExQLlpjMoVGHkk48kzohEAD8UI2W2ckgEzDkvkq1VqYFoFuciOzZ-Pf5fNTgPGDQAKKINokKQjkcAOCYEAfiAX7ZusmwuPGxBmBBADKUiCFBMFwYiRG-kQtCQjeLj3jIsjPlUgHvusiHfqiWYkX+KG3uhmGQjhD6QgBb5EQoiiIiM1IaEWxALvkvQYPoWpwLMQ4rAkLJ3AqhaxKB4EavUoAQL4WpZLs+ydCYDhDjBdD+GcZZ6nAwT5DAk6cvolbulpVgALRkDA674HWkJfD0mDLPCsl0N+eCEOegXBTEMBcr56xSbUnhBtA0SuVFbGJZCbF-jS8bFX4mYUc43gFeeRUldZmbQbBEBsaJM7KEoBBAA" rel="nofollow noreferrer">Playground link


问:
Typescript dynamic runtime type
I have a typescript file containing a list of typed exported functions that looks like that:

// File hooks.tsx
export function useBookQuery(...) {
...
}
export function useAuthorQuery(...) {
...
}
```
<p>I also have a class defined as follow (it stores the various exported function from the previous file and resolve function from a type).</p>
<pre class="lang-js prettyprint-override"><code>// File TypeRegistry.tsx
class TypeRegistry {
    constructor(hooks) {
        this.hooks = hooks
    }

    getHook(type: string) {
        return this.hooks[`use${type}Query`];
    }
}
</code>```

The class is instanced as follow:

import * as hooks from './hooks'
const typeRegistry = new TypeRegistry(hooks);
const queryBook = typeRegistry.getHook('Book');
const queryAuthor = typeRegistry.getHook('Author');
```

Here, I want the queryBook variable type to be the one of the useBookQuery from the hooks.tsx file and the queryAuthor to be the type of useAuthorQuery.

I don't know how to type the getHook method to achieve the desired behavior and I don't know if it's even possible.

答:
You can type this using typeof import to get the type of the import. You can then manipulate this type as you would any other. In this case getHook will need to be generic, and we will need to use template literal types and conditional types to extract the union of possible values for type:

```<code>// @filename: TypeRegistry.tsx
type AllHooks = typeof import('./hooks');
type ExtractName<T extends `use${string}Query`> =  T extends `use${infer Type}Query` ? Type: never
class TypeRegistry {
    hooks: AllHooks;
    constructor(hooks: AllHooks) {
        this.hooks = hooks
    }

    getHook<K extends ExtractName<keyof AllHooks>>(type: K): AllHooks[`use${K}Query`] {
        return this.hooks[`use${type}Query`];
    }
}

// @filename: usage.tsx
import * as hooks from './hooks'
const typeRegistry = new TypeRegistry(hooks);
const queryBook = typeRegistry.getHook('Book'); // correct type for book
const queryAuthor = typeRegistry.getHook('Author'); // correct type for author

</code>```

Workbench link

You can also make TypeRegistry generic, so the type of hooks can be passed in when you build the registry:

```<code>type ExtractName<T extends string> =  T extends `use${infer Type}Query` ? Type: never
class TypeRegistry<T extends Record<`use${string}Query`, () => any>> {
    hooks: T;
    constructor(hooks: T) {
        this.hooks = hooks
    }

    getHook<K extends ExtractName<keyof T & string>>(type: K): T[`use${K}Query`] {
        return this.hooks[`use${type}Query`];
    }
}
</code>```

Workbench link

Title: Typescript dynamic runtime type

Body:
I have a typescript file containing a list of typed exported functions that looks like that:

// File hooks.tsx
export function useBookQuery(...) {
...
}
export function useAuthorQuery(...) {
...
}

I also have a class defined as follow (it stores the various exported function from the previous file and resolve function from a type).

// File TypeRegistry.tsx
class TypeRegistry {
    constructor(hooks) {
        this.hooks = hooks
    }

    getHook(type: string) {
        return this.hooks[`use${type}Query`];
    }
}

The class is instanced as follow:

import * as hooks from './hooks'
const typeRegistry = new TypeRegistry(hooks);
const queryBook = typeRegistry.getHook('Book');
const queryAuthor = typeRegistry.getHook('Author');

Here, I want the queryBook variable type to be the one of the useBookQuery from the hooks.tsx file and the queryAuthor to be the type of useAuthorQuery.

I don't know how to type the getHook method to achieve the desired behavior and I don't know if it's even possible.

Body:
You can type this using typeof import to get the type of the import. You can then manipulate this type as you would any other. In this case getHook will need to be generic, and we will need to use template literal types and conditional types to extract the union of possible values for type:

// @filename: TypeRegistry.tsx
type AllHooks = typeof import('./hooks');
type ExtractName<T extends `use${string}Query`> =  T extends `use${infer Type}Query` ? Type: never
class TypeRegistry {
    hooks: AllHooks;
    constructor(hooks: AllHooks) {
        this.hooks = hooks
    }

    getHook<K extends ExtractName<keyof AllHooks>>(type: K): AllHooks[`use${K}Query`] {
        return this.hooks[`use${type}Query`];
    }
}

// @filename: usage.tsx
import * as hooks from './hooks'
const typeRegistry = new TypeRegistry(hooks);
const queryBook = typeRegistry.getHook('Book'); // correct type for book
const queryAuthor = typeRegistry.getHook('Author'); // correct type for author

<a href="https://www.typescriptlang.org/dev/bug-workbench/?ts=4.5.4#code/PTAEAEDMEsBsFMB2BDAtvAXKAFge1wNYDOAdAC5EAeAUNfJQA64BOZokArogMZnS6JQHIvABC+AgEUO8ZgE8AFAEosAb1B8yCLETLNoiAOYBfUKuqhLoZvDIdmgxB1iwAhAG5qxuoxZtOPHwCQiIAghxkeMzSsooqZqAo6Dp6BoagpuZW1rb2js5unt7UIBAwCEmYoAAqcgzwAErwhtC68uRUtGR18KChLgASEkSgALwaPbiQoNCoTKwKAOQkwHiERItKnt31oACilHrIvAByaPAAPNWg9GRIACYjAAbC8AAkqm1pxjHyTwB8Y0s11uD2erw+BkgshqPR+Mj+oAA-LD6lhEPAAG6yajcWDIIgjWr1JotNpyMwWKxrYhYfqwIbrTzZbgCNocXgsBQ0oh0wbDJSU7LZSKtEg8oE8qmWYrZQy2RkEC4AaRuhzB+0OzGOZDO6AuBHgcimfX563+-wUOyqyvi9MVRAA2i8RB9lfDYk8ALpC4WWGx2BwabBinnOiGqa0ev5e5lWbzFUpQOBIc5YYTIeUdGizeZsABUoAJOGG7GYuFQoGWq2Gi1xbLY1tJrT0FPGGIA7qjGs0W-JuQLPKzELpQABHBFycSEIFN3vkkjysiKpbTgibIcN8eT8KRFiznrNhdLleLXdRDdAA" rel="nofollow noreferrer">Workbench link

You can also make TypeRegistry generic, so the type of hooks can be passed in when you build the registry:

type ExtractName<T extends string> =  T extends `use${infer Type}Query` ? Type: never
class TypeRegistry<T extends Record<`use${string}Query`, () => any>> {
    hooks: T;
    constructor(hooks: T) {
        this.hooks = hooks
    }

    getHook<K extends ExtractName<keyof T & string>>(type: K): T[`use${K}Query`] {
        return this.hooks[`use${type}Query`];
    }
}

<a href="https://www.typescriptlang.org/dev/bug-workbench/?ts=4.5.4#code/PTAEAEDMEsBsFMB2BDAtvAXKAFge1wNYDOAdAC5EAeAUNfJQA64BOZokArogMZnS6JQHIvABC+AgEUO8ZgE8AFAEosAb1B8yCLETLNoiAOYBfUKuqhLoZvDIdmgxB1iwAhAG5qxuoxZtOPHwCQiIAghxkeMzSsooqZqAo6Dp6BoagpuZW1rb2js5unt7UIBAwCEmYoAAqcgzwAErwhtC68uRUtGR18KAAopR6yLwAcmjwADzVoPRkSAAmRKBtaQB8oAC8ltOzC0sABsLwACSqBpCyNT3GMfL7oAD8V-VYiPAAbrLU3LDIREu1epNFptORTGaDPagJrcFjzCaHESnFZGG4yO4AGlAyk262QiDkq3WWSseEIRCw1U82VhiDaHF4LAUZOIlKUZgs2SskVaJBZSy2-M5lmK2UMtgAEhIJgBpCFzRCLfqDZjDMhjdATAjwOS4SA1UAAMmWqSMRIU3ReoBl8WqAG1ESdVDK0bF9gBdDlcqw2OwODTYXn8h1HU6W+Cuu7u6lWbzFUpQOBIcZYYTIcUdGjQVBMVigABUoD+OAkS0gzFwqFAAHISMB+dXvgJdBoesDWno5JtEvAAO7PRrNDvyZmlpTuUBNulsACO6Lk4kI3fD7dBJHFZClhAU1cXBGr46nLbnsXCkRYy7bQ7XG63BB3Z6iB-cQA" rel="nofollow noreferrer">Workbench link


问:
How to convert two vectors into dataframe (wide format)
I want to convert two vectors into a wide format dataframe. The fist vector represent the column names and the second vector the values.
Here is my reproduceable example:

```<code>vector1<-c("Reply","Reshare","Like","Share","Search")
vector2<-c(2,1,0,4,3)
</code>```

Now I want to convert these two vector into a wide format dataframe:

```<code># A tibble: 1 x 5
   Reply Reshare  Like Share Search
   <dbl>   <dbl> <dbl> <dbl>  <dbl>
1     2       1     0     4      3
</code>```

I have found some examples for the long format, but none simple solution for the wide format. Can anyone help me?

答:
We can use map_dfc and set_names

```<code>library(purrr)

set_names(map_dfc(vector2, ~.x), vector1)

# A tibble: 1 × 5
  Reply Reshare  Like Share Search
  <dbl>   <dbl> <dbl> <dbl>  <dbl>
1     2       1     0     4      3
</code>```

Body:
I want to convert two vectors into a wide format dataframe. The fist vector represent the column names and the second vector the values.
Here is my reproduceable example:

vector1<-c("Reply","Reshare","Like","Share","Search")
vector2<-c(2,1,0,4,3)

Now I want to convert these two vector into a wide format dataframe:

# A tibble: 1 x 5
   Reply Reshare  Like Share Search
   <dbl>   <dbl> <dbl> <dbl>  <dbl>
1     2       1     0     4      3

I have found some examples for the long format, but none simple solution for the wide format. Can anyone help me?

Body:
We can use map_dfc and set_names

library(purrr)

set_names(map_dfc(vector2, ~.x), vector1)

# A tibble: 1 × 5
  Reply Reshare  Like Share Search
  <dbl>   <dbl> <dbl> <dbl>  <dbl>
1     2       1     0     4      3


问:
How to Invert column values in pandas - pythonic way?
I have a dataframe like as shown below

```<code>cdf = pd.DataFrame({'Id':[1,2,3,4,5],
                    'Label':[1,1,1,0,0]})
</code>```

My objective is to

a) replace 0s as 1s AND 1s as 0s in Label column

I was trying something like the below

```<code>cdf.assign(invert_label=cdf.Label.loc[::-1].reset_index(drop=True)) #not work
cdf['invert_label'] = np.where(cdf['Label']==0, '1', '0')
</code>```

'
but this doesn't work. It reverses the order

I expect my output to be like as shown below

```<code>    Id  Label
0   1   0
1   2   0
2   3   0
3   4   1
4   5   1
</code>```

答:
One maybe obvious answer might be to use 1-value:

```<code>cdf['Label2'] = 1-cdf['Label']
</code>```

output:

```<code>   Id  Label  Label2
0   1      1       0
1   2      1       0
2   3      1       0
3   4      0       1
4   5      0       1
</code>```

Body:
I have a dataframe like as shown below

cdf = pd.DataFrame({'Id':[1,2,3,4,5],
                    'Label':[1,1,1,0,0]})

My objective is to

a) replace 0s as 1s AND 1s as 0s in Label column

I was trying something like the below

cdf.assign(invert_label=cdf.Label.loc[::-1].reset_index(drop=True)) #not work
cdf['invert_label'] = np.where(cdf['Label']==0, '1', '0')

'
but this doesn't work. It reverses the order

I expect my output to be like as shown below

    Id  Label
0   1   0
1   2   0
2   3   0
3   4   1
4   5   1

Body:
One maybe obvious answer might be to use 1-value:

cdf['Label2'] = 1-cdf['Label']

output:

   Id  Label  Label2
0   1      1       0
1   2      1       0
2   3      1       0
3   4      0       1
4   5      0       1


问:
Is there a way to include whole folder with changelogs in Liquibase db versioning?
I have a problem with Liquibase database versioning, because I want to include all changelog files in folder, without specifing its names and do update using them. Is that possible? My structure:

db--

```<code>|

--release-v1

     |

     --fistchangelog.sql

     --secondchangelog.sql

|

--release-v2

     |

     --newchangelog.sql
</code>```

...

And with every release I want to use all *.sql files from its folder. I don't want to hardcode names of sql files. I use only liquibase command lines for CI/CD in Azure.

I found something like  (liquibase.org/get-started/best-practices), but it only works with xml files and I use sql extension.

I have one idea but it seems bad for me and I ll use it as a last resort. Just making a loop, for every file in folder, in cmd...

Does someone know is there a simpler and better way?

答:
i think you should just use "includeAll" tag. Then liquibase will execute all .sql files inside the folder. but remember that if you not specifying every single file, Liquibase will execute those files in alphabetical order.
Sth like:

```<code><includeAll path="com/example/changelogs/"/>
</code>```

Read here -> https://docs.liquibase.com/concepts/changelogs/attributes/includeall.html

Body:
I have a problem with Liquibase database versioning, because I want to include all changelog files in folder, without specifing its names and do update using them. Is that possible? My structure:

db--

|

--release-v1

     |

     --fistchangelog.sql

     --secondchangelog.sql

|

--release-v2

     |

     --newchangelog.sql

...

And with every release I want to use all *.sql files from its folder. I don't want to hardcode names of sql files. I use only liquibase command lines for CI/CD in Azure.

I found something like  (liquibase.org/get-started/best-practices), but it only works with xml files and I use sql extension.

I have one idea but it seems bad for me and I ll use it as a last resort. Just making a loop, for every file in folder, in cmd...

Does someone know is there a simpler and better way?

Body:
i think you should just use "includeAll" tag. Then liquibase will execute all .sql files inside the folder. but remember that if you not specifying every single file, Liquibase will execute those files in alphabetical order.
Sth like:

<includeAll path="com/example/changelogs/"/>

Read here -> https://docs.liquibase.com/concepts/changelogs/attributes/includeall.html


问:
Hiding and showing labels on MouseHover
I have labels that I want to appear and disappear based on if the mouse is over it. I have a subroutine that's called when the mouse hovers over any label. It works when going from visible to not visible but not the other way around, and it also doesn't  go back to the original state when the mouse is no longer on top of the label</p>
```<code>Private Sub valueboxes_MouseHover(sender As Object, e As EventArgs)
    Dim thislabel As Label = sender

    thislabel.Visible = False
End Sub
</code>```

答:
Invert it instead of giving Visible property value as False

```<code>Private Sub label1_MouseHover(ByVal sender As Object, ByVal e As EventArgs)
    label2.Visible = Not label2.Visible
End Sub
</code>```

Ref: How to toggle visibility in Windows Forms C#

Title: Hiding and showing labels on MouseHover

Body:
I have labels that I want to appear and disappear based on if the mouse is over it. I have a subroutine that's called when the mouse hovers over any label. It works when going from visible to not visible but not the other way around, and it also doesn't  go back to the original state when the mouse is no longer on top of the label

Private Sub valueboxes_MouseHover(sender As Object, e As EventArgs)
    Dim thislabel As Label = sender

    thislabel.Visible = False
End Sub

Body:
Invert it instead of giving Visible property value as False

Private Sub label1_MouseHover(ByVal sender As Object, ByVal e As EventArgs)
    label2.Visible = Not label2.Visible
End Sub

Ref: How to toggle visibility in Windows Forms C#


问:
How open the emulator on Android studio with the old way ? (Before bumblebee)
In bumblebee version of android studio the emulator is display like in the screen. I cannot move it on an other screen of something like that.

In the old way the emulator was detached from the ide.

How can I get the view of the old way with bumblebee version ?

EDIT :
I don't have access to "View Mode" when clicking on three Dots

答:
File > Settings > Tools > Emulator and deselect Launch in a tool window.

For Windows


问:
How can I save a number in Firestore instead of a String?
I have this array where it has a color and a quantity. And when saving in Firestore, it saves as a string. How can I save the colorStocks in Firestore as a number?

This is how I save this in Firestore:

```<code>  const [productName, setProductName] = useState();
  const [size, setSize] = useState();
  const [price, setPrice] = useState();
  const [colorList, setColorList] = useState([{ color: "", colorStocks: "" }]);

  const handleColorChange = (e, index) => {
    const { name, value } = e.target;
    const list = [...colorList];
    list[index] = { ...list[index] }; // copy the item too
    list[index][name] = value;
    setColorList(list);
  };

const handleSubmit = async (e) => {
    e.preventDefault();
    const docRef = await addDoc(collection(db, "products"), {
      prodName: productName,
      size: size + "-" + size1,
      colorList,
    });
    console.log("Document written with ID: ", docRef.id);
  };
</code>```

The colors text fields are dynamic, hence, I used an array:

```<code><form onSubmit={handleSubmit}>
          <Grid>
            <Grid item xs>
              //product textfield here
            </Grid>

            <Grid item xs>
              //some select here
            </Grid>
            <Grid item xs>
              size
              />

            </Grid>
          </Grid>

          <Typography variant="h6">Colors</Typography>
          {colorList.map((singleColor, index) => (
            <div key={index}>
              <div>
                <Grid>
                  <TextField
                    label="color"
                    name="color"
                    type="text"
                    id="color"
                    required
                    value={singleColor.color}
                    onChange={(e) => handleColorChange(e, index)}
                  />
                </Grid>
                <br />
                <Grid>
                  <TextField
                    label="Stocks"
                    name="colorStocks"
                    type="text"
                    id="colorStocks"
                    required
                    value={singleColor.colorStocks}
                    onChange={(e) => handleColorChange(e, index)}
                  />
                </Grid>
              </div>
              <br />
              <Grid item xs>
               //button to remove color
              </Grid>
              <br />
              //button to add color
            </div>
          ))}
          <br />
          <Divider />
          <br />
          <Grid item xs>
            <Button type="submit">Submit</Button>
          </Grid>
        </form>
</code>```

Is there way where I could destructure colorList to save it as a Number() in firestore? Or what are the other ways this would be solved? This should be as a number since this would be subtracted later on.

The colorList in console:

答:
Just convert colorStocks to number before sending to Firestore.

```<code>const handleColorChange = (e, index) => {
    const { name, value } = e.target;
    setColorList(prevState => {
        let list = [...prevState];
        list[index][name] = name === 'colorStocks' ? +value : value;
        return list;
    });
  };
</code>```

Body:
I have this array where it has a color and a quantity. And when saving in Firestore, it saves as a string. How can I save the colorStocks in Firestore as a number?

This is how I save this in Firestore:

  const [productName, setProductName] = useState();
  const [size, setSize] = useState();
  const [price, setPrice] = useState();
  const [colorList, setColorList] = useState([{ color: "", colorStocks: "" }]);

  const handleColorChange = (e, index) => {
    const { name, value } = e.target;
    const list = [...colorList];
    list[index] = { ...list[index] }; // copy the item too
    list[index][name] = value;
    setColorList(list);
  };

const handleSubmit = async (e) => {
    e.preventDefault();
    const docRef = await addDoc(collection(db, "products"), {
      prodName: productName,
      size: size + "-" + size1,
      colorList,
    });
    console.log("Document written with ID: ", docRef.id);
  };

The colors text fields are dynamic, hence, I used an array:

<form onSubmit={handleSubmit}>
          <Grid>
            <Grid item xs>
              //product textfield here
            </Grid>

            <Grid item xs>
              //some select here
            </Grid>
            <Grid item xs>
              size
              />

            </Grid>
          </Grid>

          <Typography variant="h6">Colors</Typography>
          {colorList.map((singleColor, index) => (

                <Grid>
                  <TextField
                    label="color"
                    name="color"
                    type="text"
                    id="color"
                    required
                    value={singleColor.color}
                    onChange={(e) => handleColorChange(e, index)}
                  />
                </Grid>

                <Grid>
                  <TextField
                    label="Stocks"
                    name="colorStocks"
                    type="text"
                    id="colorStocks"
                    required
                    value={singleColor.colorStocks}
                    onChange={(e) => handleColorChange(e, index)}
                  />
                </Grid>

              <Grid item xs>
               //button to remove color
              </Grid>

              //button to add color

          ))}

          <Divider />

          <Grid item xs>
            <Button type="submit">Submit</Button>
          </Grid>
        </form>

Is there way where I could destructure colorList to save it as a Number() in firestore? Or what are the other ways this would be solved? This should be as a number since this would be subtracted later on.

The colorList in console:

Body:
Just convert colorStocks to number before sending to Firestore.

const handleColorChange = (e, index) => {
    const { name, value } = e.target;
    setColorList(prevState => {
        let list = [...prevState];
        list[index][name] = name === 'colorStocks' ? +value : value;
        return list;
    });
  };


问:
Advantage of using mx:Text over mx:Label
What is the advantage of using mx:Text over mx:Label in Flex?</p>

答:
The Text control displays multiline, noneditable text. Use the Label
  control if you need only a single line of text.

From here.


问:
plot multiple curves on same plot inside function
I have a following function with takes 2 arguments psi,lam and returns 1 array y.

```<code>lam=np.arange(0,1,0.1)
psi=np.deg2rad(np.arange(0,361,1))

def test(psi,lam):

    y=[]

    for i in range(len(lam)):
        sin_psi  = np.sin(psi)
        cos_psi  = np.cos(psi)
        sin_beta = lam*sin_psi
        cos_beta = np.sqrt(1.0 - sin_beta**2)
        ssin_pb  = sin_psi*sin_beta
        y.append((lam*(cos_psi/cos_beta)**2 - ssin_pb)/cos_beta + cos_psi)
        plt.plot(psi,y[i])

return y
</code>```

I would like the function to return range(len(lam))=10 plots of y on the vertical axis  against psi on x axis.

However, it seems to be only plotting the same curve multiple times. Not sure what I am missing?

答:
Your code has several problems the main being that the return function was inside the loop interrupting it after the first iteration. Imitating your code structure as closely as possible, we can rewrite the code as:

```<code>import numpy as np
import matplotlib.pyplot as plt

def test(psi,lam):
    y=[]

    for curr_lam in lam:
        sin_psi  = np.sin(psi)
        cos_psi  = np.cos(psi)
        sin_beta = curr_lam*sin_psi
        cos_beta = np.sqrt(1.0 - sin_beta**2)
        ssin_pb  = sin_psi*sin_beta
        val = (curr_lam * (cos_psi/cos_beta)**2 - ssin_pb)/cos_beta + cos_psi
        y.append(val)
        plt.plot(psi, val)

    plt.show()
    return y

lam=np.arange(0, 1, 0.1)
psi=np.deg2rad(np.arange(0,361,1))

y = test(psi, lam)
print(y)
</code>```

Sample output:

As Johan mentioned in the comments, you should also directly iterate over list/arrays. If you need to combine arrays, use

```<code>for x1, x2 in zip(arr1, arr2):
</code>```

If you absolutely need the index value, use

```<code>for i, x in enumerate(arr):
</code>```

Body:
I have a following function with takes 2 arguments psi,lam and returns 1 array y.

lam=np.arange(0,1,0.1)
psi=np.deg2rad(np.arange(0,361,1))

def test(psi,lam):

    y=[]

    for i in range(len(lam)):
        sin_psi  = np.sin(psi)
        cos_psi  = np.cos(psi)
        sin_beta = lam*sin_psi
        cos_beta = np.sqrt(1.0 - sin_beta**2)
        ssin_pb  = sin_psi*sin_beta
        y.append((lam*(cos_psi/cos_beta)**2 - ssin_pb)/cos_beta + cos_psi)
        plt.plot(psi,y[i])

return y

I would like the function to return range(len(lam))=10 plots of y on the vertical axis  against psi on x axis.

However, it seems to be only plotting the same curve multiple times. Not sure what I am missing?

Body:
Your code has several problems the main being that the return function was inside the loop interrupting it after the first iteration. Imitating your code structure as closely as possible, we can rewrite the code as:

import numpy as np
import matplotlib.pyplot as plt

def test(psi,lam):
    y=[]

    for curr_lam in lam:
        sin_psi  = np.sin(psi)
        cos_psi  = np.cos(psi)
        sin_beta = curr_lam*sin_psi
        cos_beta = np.sqrt(1.0 - sin_beta**2)
        ssin_pb  = sin_psi*sin_beta
        val = (curr_lam * (cos_psi/cos_beta)**2 - ssin_pb)/cos_beta + cos_psi
        y.append(val)
        plt.plot(psi, val)

    plt.show()
    return y

lam=np.arange(0, 1, 0.1)
psi=np.deg2rad(np.arange(0,361,1))

y = test(psi, lam)
print(y)

Sample output:

As Johan mentioned in the comments, you should also directly iterate over list/arrays. If you need to combine arrays, use

for x1, x2 in zip(arr1, arr2):

If you absolutely need the index value, use

for i, x in enumerate(arr):


问:
Navlink - React Router Dom not working in React.Js
I am using redux with react. I have a map method on my navigation menu and I want to navigate to /products using Navlink - react router v5.2. But when I click on shop link button it goes to products page but again I click on my logo and come back on homepage and again I click on shop link button then it doesn't navigate. What is the issue in my code? Below is the code and screenshot attached for your reference.

```<code>import React, { useEffect, useState } from "react";
import "./header.css";
import { useDispatch, useSelector } from "react-redux";
import { setHeaderData } from "../../redux/actions/header-actions/HeaderActions";
import { setBgColor } from "../../redux/actions/header-actions/HeaderActions";
import Loading from "../other/loading/Loading";
import PageNotFound from "../other/page-not-found/PageNotFound";
import { NavLink } from "react-router-dom";

const Header = () => {
  const [isLoading, setIsLoading] = useState(true);
  const headerData = useSelector((state) => state.header.headerData);
  const bgColor = useSelector((state) => state.header.bgColor);
  const { bgColour, borderColor, iconColor } = bgColor;
  const dispatch = useDispatch();

  useEffect(() => {
    // get header data
    getHeaderData();

    // send object for changing bg colour
    window.addEventListener("scroll", () => {
      changeNavBg({
        bgColour: "bg-black",
        borderColor: "border-white",
        iconColor: "text-white",
      });
    });

    return () => {
      // remove changeNavBg event on scroll
      window.removeEventListener("scroll", changeNavBg);
    };
  }, []);

  // change nav bg colour on scroll
  const changeNavBg = (bgColor) => {
    if (window.scrollY > 0) {
      dispatch(setBgColor(bgColor));
    } else {
      dispatch(
        setBgColor({
          bgColour: "bg-transparent",
          borderColor: "",
          iconColor: "",
        })
      );
    }
  };

  // get header data
  const getHeaderData = async () => {
    try {
      const response = await fetch("http://localhost:8000/navLinks");
      const data = await response.json();
      if (data) {
        setIsLoading(false);
        dispatch(setHeaderData(data));
      } else {
        setIsLoading(true);
      }
    } catch (error) {
      console.log(error);
    }
  };

  // if loading is true return Loading
  if (isLoading) {
    return <Loading loadingHeader={"header"} />;
  }

  // console.log(bgColor);

  return (
    <>
      {headerData ? (
        <div className="dvHeader">
          <nav
            className={`navbar navbar-expand-lg ${bgColour} navbar-light fixed-top`}
          >
            <div className="container">
              <div>
                <button
                  className="navbar-toggler"
                  type="button"
                  data-toggle="collapse"
                  data-target="#slideDownMenu"
                  aria-controls="slideDownMenu"
                  aria-expanded="false"
                  aria-label="Toggle navigation"
                >
                  <span className="">
                    <i className={`fa fa-bars ${iconColor}`}></i>
                  </span>
                </button>
              </div>
              <div className="order-lg-0">
                <NavLink to="/">
                  <img
                    width="50"
                    src={headerData.logo.url}
                    className="img-fluid"
                    alt=""
                  />
                </NavLink>
              </div>
              <div className="order-lg-2 d-lg-none">
                <span
                  className="d-flex"
                  data-toggle="modal"
                  data-target="#mobileCartModal"
                >
                  <span className="d-inline-block mr-1">
                    <i className={`fa fa-shopping-cart ${iconColor}`}></i>
                  </span>
                  <span className={`d-inline-block ${iconColor}`}>0</span>
                </span>
              </div>
              <div
                className="collapse navbar-collapse order-lg-1"
                id="slideDownMenu"
              >
                <ul className="navbar-nav mr-auto px-3">
                  {headerData.parentLinks &&
                    headerData.parentLinks.map((parentLink) => {
                      const { id, link, subLinks } = parentLink;
                      return (
                        <li key={id} className="nav-item dropdown">
                          <NavLink
                            className={
                              id !== 2 ? "nav-link" : "nav-link dropdown-toggle"
                            }
                            to={id === 1 ? "/products" : ""}
                            id="navbarDropdown"
                            role="button"
                            data-toggle="dropdown"
                            aria-haspopup="true"
                            aria-expanded="false"
                          >
                            {link}
                          </NavLink>
                          <div
                            className={id === 2 ? "dropdown-menu" : "d-none"}
                            aria-labelledby="navbarDropdown"
                          >
                            {subLinks &&
                              subLinks.map((subLink) => {
                                const { id, link } = subLink;
                                return (
                                  <a
                                    key={id}
                                    className="dropdown-item"
                                    href="#"
                                  >
                                    {link}
                                  </a>
                                );
                              })}
                          </div>
                        </li>
                      );
                    })}
                </ul>
                <form className="dvSearch my-2 my-lg-0 px-3">
                  <input
                    className={`form-control border-top-0 border-right-0 border-left-0 mr-sm-2 ${
                      window.innerWidth > 991 ? borderColor : ""
                    }`}
                    type="text"
                    placeholder="Search"
                    aria-label="Search"
                  />
                  <button className="btn my-2 my-sm-0" type="submit">
                    <i className={`fa fa-search ${iconColor}`}></i>
                  </button>
                </form>
              </div>
            </div>
          </nav>
        </div>
      ) : (
        <PageNotFound />
      )}
    </>
  );
};

export default Header;
</code>```

APP.JS

```<code>import React from "react";
import "./App.css";
import { BrowserRouter, Switch, Route } from "react-router-dom";
import Homepage from "./containers/home-page/index";
import Header from "./containers/header/Header";
import Footer from "./containers/footer/Footer";
import ProductListing from "./containers/products/product-list/ProductList";
import ProductDetail from "./containers/products/product-detail/ProductDetail";
import PageNotFound from "./containers/other/page-not-found/PageNotFound";
import Account from "./containers/account/index";
import Checkout from "./containers/checkout/Index";
import LoginModal from "./containers/auth/modal/login-modal/LoginModal";
import SignupModal from "./containers/auth/modal/signup-modal/SignupModal";
import MobileCartModal from "./containers/products/mobile-cart-modal/MobileCartModal";

const App = () => {
  return (
    <>
      <BrowserRouter>
        <Header />
        <Switch>
          <Route path="/" exact component={Homepage} />
          <Route path="/products" exact component={ProductListing} />
          <Route path="/productdetail" exact component={ProductDetail} />
          <Route path="/checkout" exact component={Checkout} />
          <Route path="/account" exact component={Account} />
          <Route path="*" component={PageNotFound} />
        </Switch>
        <Footer />
        <LoginModal />
        <SignupModal />
        <MobileCartModal />
      </BrowserRouter>
    </>
  );
};

export default App;
</code>```

DB.JSON

```<code>"navLinks": {
    "logo": {
      "url": "LOGO"
    },
    "parentLinks": [
      {
        "id": 1,
        "link": "Shop"
      },
      {
        "id": 2,
        "link": "Learn",
        "subLinks": [
          { "id": 1, "link": "Process" },
          { "id": 2, "link": "About Us" },
          { "id": 3, "link": "Blog" },
          { "id": 4, "link": "News" },
          { "id": 5, "link": "Beyond The Bottle" }
        ]
      },
      { "id": 3, "link": "Sign Up" },
      { "id": 4, "link": "Login" }
    ]
  }
</code>```

答:
I found the answer. I removed the bootstrap attribute "data-toggle" when id is 1. Check the code below now it's working. The Bootstrap Toggle Attribute was causing an issue.</p>
```<code><NavLink
   className={
    id !== 2 ? "nav-link" : "nav-link dropdown-toggle"
    }
   to={id === 1 ? "/products" : ""}
   id="navbarDropdown"
   role="button"
   // removed bootstrap attribute
   data-toggle={id !== 1 ? "dropdown" : ""}
   aria-haspopup="true"
   aria-expanded="false"
 >
   {link}
</NavLink>
</code>```

Body:
I am using redux with react. I have a map method on my navigation menu and I want to navigate to /products using Navlink - react router v5.2. But when I click on shop link button it goes to products page but again I click on my logo and come back on homepage and again I click on shop link button then it doesn't navigate. What is the issue in my code? Below is the code and screenshot attached for your reference.

import React, { useEffect, useState } from "react";
import "./header.css";
import { useDispatch, useSelector } from "react-redux";
import { setHeaderData } from "../../redux/actions/header-actions/HeaderActions";
import { setBgColor } from "../../redux/actions/header-actions/HeaderActions";
import Loading from "../other/loading/Loading";
import PageNotFound from "../other/page-not-found/PageNotFound";
import { NavLink } from "react-router-dom";

const Header = () => {
  const [isLoading, setIsLoading] = useState(true);
  const headerData = useSelector((state) => state.header.headerData);
  const bgColor = useSelector((state) => state.header.bgColor);
  const { bgColour, borderColor, iconColor } = bgColor;
  const dispatch = useDispatch();

  useEffect(() => {
    // get header data
    getHeaderData();

    // send object for changing bg colour
    window.addEventListener("scroll", () => {
      changeNavBg({
        bgColour: "bg-black",
        borderColor: "border-white",
        iconColor: "text-white",
      });
    });

    return () => {
      // remove changeNavBg event on scroll
      window.removeEventListener("scroll", changeNavBg);
    };
  }, []);

  // change nav bg colour on scroll
  const changeNavBg = (bgColor) => {
    if (window.scrollY > 0) {
      dispatch(setBgColor(bgColor));
    } else {
      dispatch(
        setBgColor({
          bgColour: "bg-transparent",
          borderColor: "",
          iconColor: "",
        })
      );
    }
  };

  // get header data
  const getHeaderData = async () => {
    try {
      const response = await fetch("http://localhost:8000/navLinks");
      const data = await response.json();
      if (data) {
        setIsLoading(false);
        dispatch(setHeaderData(data));
      } else {
        setIsLoading(true);
      }
    } catch (error) {
      console.log(error);
    }
  };

  // if loading is true return Loading
  if (isLoading) {
    return <Loading loadingHeader={"header"} />;
  }

  // console.log(bgColor);

  return (
    <>
      {headerData ? (

          <nav
            className={`navbar navbar-expand-lg ${bgColour} navbar-light fixed-top`}
          >

                <button
                  className="navbar-toggler"
                  type="button"
                  data-toggle="collapse"
                  data-target="#slideDownMenu"
                  aria-controls="slideDownMenu"
                  aria-expanded="false"
                  aria-label="Toggle navigation"
                >

                    <i className={`fa fa-bars ${iconColor}`}>

                </button>

                <NavLink to="/">

                </NavLink>

                    <i className={`fa fa-shopping-cart ${iconColor}`}>

                  <span className={`d-inline-block ${iconColor}`}>0

                  {headerData.parentLinks &&
                    headerData.parentLinks.map((parentLink) => {
                      const { id, link, subLinks } = parentLink;
                      return (

                          <NavLink
                            className={
                              id !== 2 ? "nav-link" : "nav-link dropdown-toggle"
                            }
                            to={id === 1 ? "/products" : ""}
                            id="navbarDropdown"
                            role="button"
                            data-toggle="dropdown"
                            aria-haspopup="true"
                            aria-expanded="false"
                          >
                            {link}
                          </NavLink>

                            {subLinks &&
                              subLinks.map((subLink) => {
                                const { id, link } = subLink;
                                return (

                                    {link}

                                );
                              })}

                      );
                    })}

                <form className="dvSearch my-2 my-lg-0 px-3">
                  <input
                    className={`form-control border-top-0 border-right-0 border-left-0 mr-sm-2 ${
                      window.innerWidth > 991 ? borderColor : ""
                    }`}
                    type="text"
                    placeholder="Search"
                    aria-label="Search"
                  />
                  <button className="btn my-2 my-sm-0" type="submit">
                    <i className={`fa fa-search ${iconColor}`}>
                  </button>
                </form>

      ) : (
        <PageNotFound />
      )}
    </>
  );
};

export default Header;

APP.JS

import React from "react";
import "./App.css";
import { BrowserRouter, Switch, Route } from "react-router-dom";
import Homepage from "./containers/home-page/index";
import Header from "./containers/header/Header";
import Footer from "./containers/footer/Footer";
import ProductListing from "./containers/products/product-list/ProductList";
import ProductDetail from "./containers/products/product-detail/ProductDetail";
import PageNotFound from "./containers/other/page-not-found/PageNotFound";
import Account from "./containers/account/index";
import Checkout from "./containers/checkout/Index";
import LoginModal from "./containers/auth/modal/login-modal/LoginModal";
import SignupModal from "./containers/auth/modal/signup-modal/SignupModal";
import MobileCartModal from "./containers/products/mobile-cart-modal/MobileCartModal";

const App = () => {
  return (
    <>
      <BrowserRouter>

        <Switch>
          <Route path="/" exact component={Homepage} />
          <Route path="/products" exact component={ProductListing} />
          <Route path="/productdetail" exact component={ProductDetail} />
          <Route path="/checkout" exact component={Checkout} />
          <Route path="/account" exact component={Account} />
          <Route path="*" component={PageNotFound} />
        </Switch>

        <LoginModal />
        <SignupModal />
        <MobileCartModal />
      </BrowserRouter>
    </>
  );
};

export default App;

DB.JSON

"navLinks": {
    "logo": {
      "url": "LOGO"
    },
    "parentLinks": [
      {
        "id": 1,
        "link": "Shop"
      },
      {
        "id": 2,
        "link": "Learn",
        "subLinks": [
          { "id": 1, "link": "Process" },
          { "id": 2, "link": "About Us" },
          { "id": 3, "link": "Blog" },
          { "id": 4, "link": "News" },
          { "id": 5, "link": "Beyond The Bottle" }
        ]
      },
      { "id": 3, "link": "Sign Up" },
      { "id": 4, "link": "Login" }
    ]
  }

Body:
I found the answer. I removed the bootstrap attribute "data-toggle" when id is 1. Check the code below now it's working. The Bootstrap Toggle Attribute was causing an issue.

<NavLink
   className={
    id !== 2 ? "nav-link" : "nav-link dropdown-toggle"
    }
   to={id === 1 ? "/products" : ""}
   id="navbarDropdown"
   role="button"
   // removed bootstrap attribute
   data-toggle={id !== 1 ? "dropdown" : ""}
   aria-haspopup="true"
   aria-expanded="false"
 >
   {link}
</NavLink>


问:
Good pattern or framework for adding auditing to an existing app?
I have an existing J2EE enterprise application to which I need to add auditing, i.e. be able to record CRUD operations on several important domain types (Employee, AdministratorRights, etc.).

The application has a standard n-tier architecture:

Web interface

Business operations encapsulated within a mixture of stateless session beans and transactional POJOs (using Spring)

persistence is a mixture of direct JDBC (from within the business layer) and EJB 2.x BMP entity beans (I know, I know)

My question is: are there any standard patterns or (better still) frameworks/libraries specifically for adding auditing as a cross-cutting concern? I know AOP can be used to implement cross-cutting concerns in general; I want to know if there's something specifically aimed at auditing.

答:
For all EJBs you can use EJB 3.0 Interceptors (This is something similar to Servlet filter) and another similar interceptor for Spring (not familiar with spring)
As you are using EJBs as well as Spring that may not cover the whole transactions. Another approach could be using a Front Controller however that requires some modification in the client side. Yet another approach could be using a Servlet Filter however that means implementing the domain logic in the presentation layer.

I would recommend the Front Controller in this case.

OwnerDisplayName: Andrew Swan

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Rejeev Divakaran


问:
Is there a silver bullet to importing XML data into SQL Server 2008 Express?
I've tried the Import/Export wizard, but there is no XML driver under the Data source drop down. Is there a way to import XML data into SQL Express without writing an app to do it explicitly?</p>

答: See OPENXML.</p>

OwnerDisplayName: brian

Body: See OPENXML.

OwnerDisplayName: John Saunders


问:
I want to display the message when I push send button. And want be reset message form
I am making a contact form using React.js and emailjs, but I input a form that says "Message sent !!" after sending a message and "Failed to send message!" When the message cannot be sent. I'd like to make it appear on the top, but I'm a little stucking in the CSS styling method at that time.

JS

```<code>    import React, { useState } from "react";
    import { useForm } from "react-hook-form";
    import "./Contact.css";
    import { init, send } from 'emailjs-com';
    init('MY USER ACCOUNT');

    const Contact = () => {

      const [contactNumber, setContactNumber] = useState('000000')
      const [statusMessage, setStatusMessage] = useState('message')
      const generateContactNumber = () => {
        const numStr = '000000' + (Math.random() * 1000000 | 0);
        setContactNumber(numStr.substring(numStr.length - 6))
      }

  const { register, handleSubmit, watch, formState: { errors } } = useForm();
  const onSubmit = (data) => {
    const form = document.querySelector('#contact-form')
    generateContactNumber();
    send('service', 'template', data)
      .then(function (response) {
        console.log('SUCCESS!', response.status, response.text);
        setStatusMessage("Message sent!!")
        statusMessage.className = 'status-message success'
        setTimeout(() => {
          statusMessage.className = 'status-message'
        }, 5000)
        form.reset();

      }, function (error) {
        console.log('FAILED...', error);
        setStatusMessage('Failed to send message! Please try again :-(')
        statusMessage.className = "status-message failure"
        setTimeout(() => {
          statusMessage.className = 'status-message'
        }, 5000)
      })
  }

  const message = watch('message') || "";
  const messageCharsLeft = 1500 - message.length;

  return (

    <body>

      <div className="Contact" >
        <h1>Contact me</h1>
        <p>Please talk me any question if you have </p>
        <p className="status-message">{statusMessage}</p>
      </div>

      <form id='contact-form' onSubmit={handleSubmit(onSubmit)} >
        <input type='hidden' name='contact_number' value={contactNumber} />

        {errors.user_name && errors.user_name.type === "required" && (
          <div role="alert">Name is required<br /></div>)}
        <input type='text' name='user_name' placeholder='Name' maxLength='30'
          aria-invalid={errors.user_name ? "true" : "false"}{...register("user_name", ({ required: true }))} />
        <br />

        {errors.user_email && errors.user_email.type === "required" && (
          <div role="alert">Email is required<br /></div>)}
        <input type='email' name='user_email' placeholder='Email'{...register("user_email", ({ required: true }))} />
        <br />

        {errors.message && errors.message.type === "required" && (
          <div role="alert">Message is required<br /></div>)}
        <textarea name='message' {...register("message", ({ required: true }))} placeholder='Message' maxLength='1500' />
        {/* <p className='message-chars-left'>{messageCharsLeft}</p> */}
        <br />

        <input type='submit' className="submit" value='Send' />
      </form>

    </body>
  )
}
</code>```

CSS

```<code>body{
  background-color: black;

}

input, textarea{
  margin-bottom: 20px;
  width: 600px;

}

textarea {
  height: 10em;
  width: 600px;
}

div[role='alert'] {
  color: red;
  margin-top: 5px;
  font-size: larger;
}

.message-chars-left {
  width: 600px;
  margin: auto;
  text-align: left;
}

.Contact h1{
  font-size: 2em;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
  'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
  sans-serif;
  color: aliceblue;
  font-weight:900;
}
.Contact p{
  font-size: 2em;
  text-align: center;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
  'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
  sans-serif;
  color: aliceblue;
}

.submit:hover{
  background:rgb(176, 180, 180);
  transition: 0.5 s;
}

.status-message {
  opacity: 0;
  text-align: center;
  font-size: 1.0em;
  transition: 0.3;
}

.success{
  opacity: 1;
  color: green;
}

.failure{
  opacity: 1;
  color: red;
}

@media screen and (max-width: 480px) {
  .Contact h1 {
    width: 100%;
    font-size: x-large;
  }
}
@media screen and (max-width: 480px) {
  .Contact p {
    width: 100%;
    font-size: x-large;
  }
}

@media screen and (max-width: 480px) {
  input{
    width: 360px;

  }
}

@media screen and (max-width: 480px) {
  textarea {
    width: 360px;

  }
}
</code>```

When I run it with the code above, the .status-message css seems to be working and the text doesn't appear in the form, but when I cut the wifi beforehand and send it ("Failed to send message "I want to show the message"! ...) The .failure css doesn't work and nothing shows up.
When I set the opacity of .status-message to 1 and do the same thing, it shows "message" on the form before submitting and changes to "Failed to send message!..." after submitting. ..
So I think the function itself is done, but it's chock full of how to make css work.
Also, when I try to send it, I get the error "Uncaught type error (in promise): Cannot create property 'class name' on string 'message'" in the check console, but it works.
and, use reset() on .then so that Form can return the form to the state before the message was entered after submission, but the message remains even after submission.

Thank you.

答:
You're setting the .className property on a string, and strings doesn't have that property. So that's why you get the type error. It only stops the execution of your eventhandler and thus. Per example, does your form reset on success? It shouldn't.

What you need to do instead, is to introduce some new boolean states, one for success and one for errors. Now in the
 tag that contains your status message, test for those booleans. If success is true, apply the success class to the
 tag. Same thing for errors.

Body:
I am making a contact form using React.js and emailjs, but I input a form that says "Message sent !!" after sending a message and "Failed to send message!" When the message cannot be sent. I'd like to make it appear on the top, but I'm a little stucking in the CSS styling method at that time.

JS

    import React, { useState } from "react";
    import { useForm } from "react-hook-form";
    import "./Contact.css";
    import { init, send } from 'emailjs-com';
    init('MY USER ACCOUNT');

    const Contact = () => {

      const [contactNumber, setContactNumber] = useState('000000')
      const [statusMessage, setStatusMessage] = useState('message')
      const generateContactNumber = () => {
        const numStr = '000000' + (Math.random() * 1000000 | 0);
        setContactNumber(numStr.substring(numStr.length - 6))
      }

  const { register, handleSubmit, watch, formState: { errors } } = useForm();
  const onSubmit = (data) => {
    const form = document.querySelector('#contact-form')
    generateContactNumber();
    send('service', 'template', data)
      .then(function (response) {
        console.log('SUCCESS!', response.status, response.text);
        setStatusMessage("Message sent!!")
        statusMessage.className = 'status-message success'
        setTimeout(() => {
          statusMessage.className = 'status-message'
        }, 5000)
        form.reset();

      }, function (error) {
        console.log('FAILED...', error);
        setStatusMessage('Failed to send message! Please try again :-(')
        statusMessage.className = "status-message failure"
        setTimeout(() => {
          statusMessage.className = 'status-message'
        }, 5000)
      })
  }

  const message = watch('message') || "";
  const messageCharsLeft = 1500 - message.length;

  return (

Contact me

Please talk me any question if you have

{statusMessage}

      <form id='contact-form' onSubmit={handleSubmit(onSubmit)} >
        <input type='hidden' name='contact_number' value={contactNumber} />

        {errors.user_name && errors.user_name.type === "required" && (

Name is required

)}
        <input type='text' name='user_name' placeholder='Name' maxLength='30'
          aria-invalid={errors.user_name ? "true" : "false"}{...register("user_name", ({ required: true }))} />

        {errors.user_email && errors.user_email.type === "required" && (

Email is required

)}
        <input type='email' name='user_email' placeholder='Email'{...register("user_email", ({ required: true }))} />

        {errors.message && errors.message.type === "required" && (

Message is required

)}
        <textarea name='message' {...register("message", ({ required: true }))} placeholder='Message' maxLength='1500' />
        {/*
{messageCharsLeft}
 */}

        <input type='submit' className="submit" value='Send' />
      </form>

  )
}

CSS

body{
  background-color: black;

}

input, textarea{
  margin-bottom: 20px;
  width: 600px;

}

textarea {
  height: 10em;
  width: 600px;
}

div[role='alert'] {
  color: red;
  margin-top: 5px;
  font-size: larger;
}

.message-chars-left {
  width: 600px;
  margin: auto;
  text-align: left;
}

.Contact h1{
  font-size: 2em;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
  'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
  sans-serif;
  color: aliceblue;
  font-weight:900;
}
.Contact p{
  font-size: 2em;
  text-align: center;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
  'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
  sans-serif;
  color: aliceblue;
}

.submit:hover{
  background:rgb(176, 180, 180);
  transition: 0.5 s;
}

.status-message {
  opacity: 0;
  text-align: center;
  font-size: 1.0em;
  transition: 0.3;
}

.success{
  opacity: 1;
  color: green;
}

.failure{
  opacity: 1;
  color: red;
}

@media screen and (max-width: 480px) {
  .Contact h1 {
    width: 100%;
    font-size: x-large;
  }
}
@media screen and (max-width: 480px) {
  .Contact p {
    width: 100%;
    font-size: x-large;
  }
}

@media screen and (max-width: 480px) {
  input{
    width: 360px;

  }
}

@media screen and (max-width: 480px) {
  textarea {
    width: 360px;

  }
}

When I run it with the code above, the .status-message css seems to be working and the text doesn't appear in the form, but when I cut the wifi beforehand and send it ("Failed to send message "I want to show the message"! ...) The .failure css doesn't work and nothing shows up.
When I set the opacity of .status-message to 1 and do the same thing, it shows "message" on the form before submitting and changes to "Failed to send message!..." after submitting. ..
So I think the function itself is done, but it's chock full of how to make css work.
Also, when I try to send it, I get the error "Uncaught type error (in promise): Cannot create property 'class name' on string 'message'" in the check console, but it works.
and, use reset() on .then so that Form can return the form to the state before the message was entered after submission, but the message remains even after submission.

Thank you.

Body:
You're setting the .className property on a string, and strings doesn't have that property. So that's why you get the type error. It only stops the execution of your eventhandler and thus. Per example, does your form reset on success? It shouldn't.

What you need to do instead, is to introduce some new boolean states, one for success and one for errors. Now in the <p> tag that contains your status message, test for those booleans. If success is true, apply the success class to the <p> tag. Same thing for errors.


问:
Why change of sequence in cmd command gives different result?
I'm new in using cmd and batch script. Here is what I was trying to do with a .bat file.

go to a folder

open that folder in file explorer

open that folder in vscode

start Firefox browser

Sequence doesn't matter here. Doing these tasks in any sequence is fine.

Here are the commands that I initially wrote

```<code>cd/
E:
cd folder1/folder2/folder3
code .
start .
start firefox
</code>```

But with these commands the result I got is

Only vscode started with the folder I wanted to open with vscode

File explorer and Firefox was not starting

cmd.exe continued to run. But it seems like it only executed upto code . command

When I closed vscode, cmd.exe would be closed with it too

Then I changed the sequence of the commands as below

```<code>cd/
E:
cd folder1/folder2/folder3
start .
start firefox
code .
</code>```

This time everything worked as expected. I've looked up documentation for start command but didn't find anything(or maybe I didn't understand) about start . command.

Can anyone explain me why the result changed when I changed the sequence of the commands?

答:
As already mentioned in the comments, code is really a batch file, code.cmd.

If your VSCode installer added a location to your %PATH%, take a look there and you should see code.cmd in that \bin directory.

When you run a batch file from another, if you want control to pass back to the initial script upon completion, you need to run it using the call command.

@CD /D "E:\folder1\folder2\folder3" 2>NUL || Exit /B
@Call "%ProgramFiles%\Microsoft VS Code\bin\code.cmd" .
@Start "" "%SystemRoot%\explorer.exe" .
@Start "" "%ProgramFiles%\Mozilla Firefox\firefox.exe"
```
<p>If you do not want robust code, and wish to assume file extensions and environment settings, the above could be simplified to this:</p>
<pre class="lang-sh prettyprint-override"><code>@CD /D E:\folder1\folder2\folder3
@Call code .
@Start explorer .
@Start firefox
</code>```

Body:
I'm new in using cmd and batch script. Here is what I was trying to do with a .bat file.

go to a folder

open that folder in file explorer

open that folder in vscode

start Firefox browser

Sequence doesn't matter here. Doing these tasks in any sequence is fine.

Here are the commands that I initially wrote

cd/
E:
cd folder1/folder2/folder3
code .
start .
start firefox

But with these commands the result I got is

Only vscode started with the folder I wanted to open with vscode

File explorer and Firefox was not starting

cmd.exe continued to run. But it seems like it only executed upto code . command

When I closed vscode, cmd.exe would be closed with it too

Then I changed the sequence of the commands as below

cd/
E:
cd folder1/folder2/folder3
start .
start firefox
code .

This time everything worked as expected. I've looked up documentation for start command but didn't find anything(or maybe I didn't understand) about start . command.

Can anyone explain me why the result changed when I changed the sequence of the commands?

Body:
As already mentioned in the comments, code is really a batch file, code.cmd.

If your VSCode installer added a location to your %PATH%, take a look there and you should see code.cmd in that \bin directory.

When you run a batch file from another, if you want control to pass back to the initial script upon completion, you need to run it using the call command.

@CD /D "E:\folder1\folder2\folder3" 2>NUL || Exit /B
@Call "%ProgramFiles%\Microsoft VS Code\bin\code.cmd" .
@Start "" "%SystemRoot%\explorer.exe" .
@Start "" "%ProgramFiles%\Mozilla Firefox\firefox.exe"

If you do not want robust code, and wish to assume file extensions and environment settings, the above could be simplified to this:

@CD /D E:\folder1\folder2\folder3
@Call code .
@Start explorer .
@Start firefox


问:
Oracle SQL Developer: Arial Unicode MS and other fonts not available
In SQL Developer's (version 21.2.1.204 under Windows 10) Preferences, under Code Editor \ Fonts, several expected entries do not show up in the list of available fonts even though the limitation to monospaced fonts is lifted, and Environment \ Encoding is set to 'UTF-8'. Among these are "Arial Unicode MS" and Google's Noto fonts.

According to this post...
how to make sql developer display non-English character correctly instread of displaying squares?
... and others, at least "Arial Unicode MS" should be available.

And yes, these fonts are installed and work fine in all other applications that allow font selection.

What's going on?

答: I have been able to verify on another workstation that fonts installed with local admin privileges ("for all users") DO show up in SQL Developer. I guess this means the original question can be considered as "answered", though a real solution is pending.</p>


问:
Status check on the deployed lambda failed. A GET request to '/' yielded a 502 response code
trying to simple zappa app built with Flask, but after zappa deploy dev I get the following error :

Error: Warning! Status check on the deployed lambda failed. A GET request to '/' yielded a 502 response code.

▼ Struct

```<code>.
├── app
│   ├── env
│   └── main.py
└── zappa_settings.json
</code>```

▼ app/main.py

#main.py
import sys
from flask import Flask, redirect, request, jsonify, url_for, render_template

app = Flask(__name__)

@app.route('/', methods=['GET'])
def index():
     return 'hello zappa!'

if __name__ == '__main__':
 if len(sys.argv) > 1:
     app.debug = True
     app.jinja_env.auto_reload = True
     app.config['TEMPLATES_AUTO_RELOAD'] = True
     app.run(host='0.0.0.0', port=4000)
 else:
     app.run(host='0.0.0.0')
```
<p>▼ zappa_settings.json</p>
<pre class="lang-js prettyprint-override"><code>{
    "dev": {
        "app_function": "app.main",
        "profile_name": null,
        "project_name": "app",
        "runtime": "python3.8",
        "s3_bucket": "zappa-kgikw9e6r"
    }
}
</code>```

▼ zappa tail

```<code>[1644312001414] [ERROR] TypeError: the 'package' argument is required to perform a relative import for '.app'
Traceback (most recent call last):
  File "/var/task/handler.py", line 657, in lambda_handler
    return LambdaHandler.lambda_handler(event, context)
  File "/var/task/handler.py", line 251, in lambda_handler
    handler = cls()
  File "/var/task/handler.py", line 148, in __init__
    self.app_module = importlib.import_module(self.settings.APP_MODULE)
  File "/var/lang/lib/python3.8/importlib/__init__.py", line 122, in import_module
    raise TypeError(msg.format(name))
</code>```

Zappa version used: 0.54.1

Ubuntu 20.04, Python 3.8

Anyone here to help?

答:
try to use this hope this works for you although I haven't used zappa before but I don't see any issue with your config file.</p>
```<code>#main.py
import sys
from flask import Flask, redirect, request, jsonify, url_for, render_template

app = Flask(__name__)
app.config['TEMPLATES_AUTO_RELOAD'] = True

@app.route('/', methods=['GET'])
def index():
     return 'hello zappa!'

if __name__ == '__main__':
    if len(sys.argv) > 1:
         app.run(host='0.0.0.0', port=4000, debug='True')
    else:
         app.run(host='0.0.0.0')
</code>```

Body:
trying to simple zappa app built with Flask, but after zappa deploy dev I get the following error :

Error: Warning! Status check on the deployed lambda failed. A GET request to '/' yielded a 502 response code.

▼ Struct

.
├── app
│   ├── env
│   └── main.py
└── zappa_settings.json

▼ app/main.py

#main.py
import sys
from flask import Flask, redirect, request, jsonify, url_for, render_template

app = Flask(__name__)

@app.route('/', methods=['GET'])
def index():
     return 'hello zappa!'

if __name__ == '__main__':
 if len(sys.argv) > 1:
     app.debug = True
     app.jinja_env.auto_reload = True
     app.config['TEMPLATES_AUTO_RELOAD'] = True
     app.run(host='0.0.0.0', port=4000)
 else:
     app.run(host='0.0.0.0')

▼ zappa_settings.json

{
    "dev": {
        "app_function": "app.main",
        "profile_name": null,
        "project_name": "app",
        "runtime": "python3.8",
        "s3_bucket": "zappa-kgikw9e6r"
    }
}

▼ zappa tail

[1644312001414] [ERROR] TypeError: the 'package' argument is required to perform a relative import for '.app'
Traceback (most recent call last):
  File "/var/task/handler.py", line 657, in lambda_handler
    return LambdaHandler.lambda_handler(event, context)
  File "/var/task/handler.py", line 251, in lambda_handler
    handler = cls()
  File "/var/task/handler.py", line 148, in __init__
    self.app_module = importlib.import_module(self.settings.APP_MODULE)
  File "/var/lang/lib/python3.8/importlib/__init__.py", line 122, in import_module
    raise TypeError(msg.format(name))

Zappa version used: 0.54.1

Ubuntu 20.04, Python 3.8

Anyone here to help?

Body:
try to use this hope this works for you although I haven't used zappa before but I don't see any issue with your config file.

#main.py
import sys
from flask import Flask, redirect, request, jsonify, url_for, render_template

app = Flask(__name__)
app.config['TEMPLATES_AUTO_RELOAD'] = True

@app.route('/', methods=['GET'])
def index():
     return 'hello zappa!'

if __name__ == '__main__':
    if len(sys.argv) > 1:
         app.run(host='0.0.0.0', port=4000, debug='True')
    else:
         app.run(host='0.0.0.0')