答:
If you are using numpy you can use list.flatten. https://numpy.org/doc/1.18/reference/generated/numpy.ndarray.flatten.html

If you have a list of numpy arrays you can use np.hstack. https://numpy.org/doc/stable/reference/generated/numpy.hstack.html

Also see How to make a flat list out of list of lists? for general Python.

Title: How to convert list of arrays to single list in python?

Body:
I have a list of arrays as follows:

list = [
         array([4.1,3.2,5.2]),
         array([4.1,8.5]),
         array([1.2,4.5,7.4])
        ]

I want to convert the above list into a single list as below:

list = [4.1,3.2,5.2,4.1,8.5,1.2,4.5,7.4]

I want to do the above thing in python.

EDIT:

The code I used to generate the list is

  result = []
  result.append(mfccs_processed)
  result.append(chroma_processed)
  result.append(mel_processed)

Now result is showing as follows:

[array([-445.43651286,  111.90097184,  -21.00590592,   31.34361885,
      9.39596702,   -4.40772227,    2.3648624 ,   -1.68017743,
     -6.39975114,   -1.12694295,   -9.34500736,   -1.13545822,
     -7.88168904,  -10.9743485 ,   -2.77344424,   -1.23599528,
     -7.39119564,   -2.44394294,   -3.75691633,   -4.80426688,
     -1.94571499,   -3.95747011,   -5.72427054,   -4.81378321,
     -3.70200738,   -5.19167481,   -4.47207894,   -4.2216418 ,
     -4.1305041 ,   -5.10309738,   -3.89591536,   -2.67058964,
     -4.04656319,   -4.78655754,   -2.44667325,   -3.05293339,
     -4.17915009,   -2.90706455,   -2.8132492 ]), array([0.548945  , 0.59981299, 0.58249648, 0.5834056 , 0.62918682,
   0.58651369, 0.51776701, 0.5152288 , 0.56039473, 0.5606346 ,
   0.59585897, 0.56108877]), array([5.36600691e-05, 3.20399714e-04, 1.19905308e-03, 3.57715592e-03,
   5.45226355e-03, 7.65769149e-02, 9.67304585e-01, 1.37048258e+00,
   2.20317190e+00, 1.47716846e+00, 7.10145651e-01, 7.23264577e-02,
   3.20378431e-02, 2.13741716e-01, 3.50276892e-01, 3.25545211e-01,
   8.23071739e-01, 1.10485735e+00, 5.16918943e-01, 8.84181377e-01,
   9.06340752e-01, 3.95779410e-01, 3.13891357e-01, 1.13048804e-01,
   6.61881599e-01, 1.70450985e+00, 1.82170031e+00, 6.18310782e-01,
   4.05325714e-01, 5.89335840e-01, 4.31023403e-01, 9.29283876e-02,
   4.11129880e-02, 1.71606268e-01, 1.41923368e-01, 9.29835332e-02,
   1.45740019e-01, 1.27688893e-01, 2.34819748e-02, 9.72517361e-03,
   3.63473003e-02, 5.93138929e-02, 3.11671706e-02, 1.18442648e-02,
   8.33423898e-03, 1.87190944e-02, 3.29460414e-02, 2.69168857e-02,
   9.29586223e-03, 6.80686607e-03, 9.94785389e-03, 1.27595168e-02,
   8.88170288e-03, 7.44158290e-03, 9.98228524e-03, 1.63925465e-02,
   9.53423946e-03, 1.05554487e-02, 1.54851110e-02, 2.05146191e-02,
   1.30264012e-02, 7.20523041e-03, 1.83835207e-02, 1.00800192e-02,
   9.16292185e-03, 2.75197205e-02, 1.26532376e-02, 5.50722000e-03,
   8.06991937e-03, 4.67484356e-03, 9.11601494e-03, 9.94969137e-03,
   8.82691376e-03, 1.35812921e-02, 3.38891723e-02, 5.48777803e-02,
   5.47833810e-02, 3.91788967e-02, 2.34909778e-02, 1.59119884e-02,
   1.76145638e-02, 2.31054147e-02, 2.95776919e-02, 4.17103322e-02,
   2.07705960e-02, 1.08400124e-02, 6.43834017e-03, 4.46195474e-03,
   4.44256498e-03, 5.25020141e-03, 1.14951221e-02, 1.41466409e-02,
   1.73377342e-02, 1.41098637e-02, 7.04262356e-03, 3.99505900e-03,
   2.48446049e-03, 1.61739298e-03, 9.00339387e-04, 3.25213392e-04,
   2.93450309e-04, 3.10071719e-04, 2.85876075e-04, 1.78957305e-04,
   1.38316595e-04, 1.07859368e-04, 1.15453318e-04, 8.50033585e-05,
   7.25839567e-05, 3.80280533e-05, 3.57639077e-05, 2.47069514e-05,
   1.57980270e-05, 1.50489378e-05, 1.12732923e-05, 1.08223414e-05,
   1.21111000e-05, 1.57062296e-05, 1.11814270e-05, 9.70704523e-06,
   8.27147728e-06, 6.56079447e-06, 5.53983257e-06, 5.31472585e-06,
   2.77939077e-06, 1.77413323e-06, 1.03589758e-06, 6.50496670e-08])]

Since I already converted my whole dataset using this code above. Now I want to convert the above generated lists into a single list as I explained above. I hope this clarifies the problem. Could you help me out.


来源: stackexchange

问:
PHP Redis extension is installed and enabled in laravel 6 version
When I am trying To installing redis  in larvel  6 version I can not install redis and it extension it show me the error.

答:
For ubuntu

```<code>sudo apt-get install php7.2-redis //7.2 is php version
</code>```

then

```<code>sudo systemctl restart php7.2-fpm
</code>```

ContentLicense: CC BY-SA 4.0

Body:
For ubuntu

sudo apt-get install php7.2-redis //7.2 is php version

then

sudo systemctl restart php7.2-fpm


问:
How to get the itself path for an Automator application?
I'm creating an Application in Mac Automator (MacOs Catalina) that creates a file in the same directory where the .app is.

To get the .app path I'm using:

for apple script: POSIX path of (path to me)

for javascript: app.pathTo(this).toString()

It is works great...

... until send the .app to someone in internet.

If the app was download from internet and run, it shows this error

/private/var/folders/.../.../... read-only file system

How to solve this?

答:
It took me some time to find it out, so I'm creating this Q&A.

It seems that MacOS adds the extended attribute com.apple.quarantine for downloaded apps. I think apps with this attribute run in some kind of sandbox.

To remove it just run:

```<code>$ xattr -r -d com.apple.quarantine my_app.app/
</code>```

Body:
It took me some time to find it out, so I'm creating this Q&A.

It seems that MacOS adds the extended attribute com.apple.quarantine for downloaded apps. I think apps with this attribute run in some kind of sandbox.

To remove it just run:

$ xattr -r -d com.apple.quarantine my_app.app/


问:
Postgres not accepting connection in Docker
I am running the docker project on docker toolbox windows 7 sp1 and the project does not give any error but still due to postgres not working the whole project in not functional.
The code of Docker compose file is :

```<code>version: '3'
services:
  postgres:
    image: 'postgres:latest'
    restart: always
    ports:
      - "5432:5432"
    environment:
      POSTGRES_DB: "db"
      POSTGRES_PASSWORD: postgres_password
      POSTGRES_HOST_AUTH_METHOD: "trust"
      DATABASE_URL: postgresql://postgres:p3wrd@postgres:5432/postgres
    deploy:
      restart_policy:
        condition: on-failure
        window: 15m
  redis:
    image: 'redis:latest'
  nginx:
    restart: always
    build:
      dockerfile: Dockerfile.dev
      context: ./nginx
    ports:
      - '3050:80'
  api:
    depends_on:
      - "postgres"
    build:
      dockerfile: Dockerfile.dev
      context: ./server
    volumes:
      - ./server/copy:/usr/src/app/data
    environment:
      - REDIS_HOST=redis
      - REDIS_PORT=6379
      - PGUSER=postgres
      - PGHOST=postgres
      - PGDATABASE=postgres
      - PGPASSWORD=postgres_password
      - PGPORT=5432
  client:
    depends_on:
      - "postgres"
    build:
      dockerfile: Dockerfile.dev
      context: ./client
    volumes:
      - ./client/copy:/usr/src/app/data
      - /usr/src/app/node_modules
  worker:
    build:
      dockerfile: Dockerfile.dev
      context: ./worker
    volumes:
      - ./worker/copy:/usr/src/app/data
      - /usr/src/app/node_modules
    depends_on:
      - "postgres"
</code>```

But when i run the project i get this :

```<code>redis_1     | 1:C 29 May 2020 05:07:37.909 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
redis_1     | 1:C 29 May 2020 05:07:37.910 # Redis version=6.0.3, bits=64, commit=00000000, modified=0, pid=1, just started
redis_1     | 1:C 29 May 2020 05:07:37.911 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
redis_1     | 1:M 29 May 2020 05:07:37.922 * Running mode=standalone, port=6379.
redis_1     | 1:M 29 May 2020 05:07:37.928 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
redis_1     | 1:M 29 May 2020 05:07:37.929 # Server initialized
redis_1     | 1:M 29 May 2020 05:07:37.929 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
redis_1     | 1:M 29 May 2020 05:07:37.933 * Loading RDB produced by version 6.0.3
redis_1     | 1:M 29 May 2020 05:07:37.934 * RDB age 8 seconds
redis_1     | 1:M 29 May 2020 05:07:37.934 * RDB memory usage when created 0.81 Mb
redis_1     | 1:M 29 May 2020 05:07:37.934 * DB loaded from disk: 0.001 seconds
postgres_1  |
postgres_1  | PostgreSQL Database directory appears to contain a database; Skipping initialization
postgres_1  |
postgres_1  | 2020-05-29 05:07:38.927 UTC [1] LOG:  starting PostgreSQL 12.3 (Debian 12.3-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit
postgres_1  | 2020-05-29 05:07:38.928 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
postgres_1  | 2020-05-29 05:07:38.929 UTC [1] LOG:  listening on IPv6 address "::", port 5432
postgres_1  | 2020-05-29 05:07:38.933 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgres_1  | 2020-05-29 05:07:38.993 UTC [24] LOG:  database system was shut down at 2020-05-29 05:07:29 UTC
api_1       |
api_1       | > @ dev /usr/src/app
api_1       | > nodemon
api_1       |
api_1       | [nodemon] 1.18.3
api_1       | [nodemon] to restart at any time, enter `rs`
api_1       | [nodemon] watching: *.*
</code>```

With or without data volumes the same error comes and due to which the project is not running. Please Help

答:
I would assume that once the API starts, it attempts to connect to the Postgres. If yes,  this is a typical error that many Docker developers experience where the Postgres DB is not yet ready to accept connections and apps are trying to connect to it.

You can solve the problem by trying either of the following approaches:

Make your API layer wait for a certain amount of time (Enough for the Postgres DB to boot up)

```<code>Thread.Sleep(60); # should be enough so that Postgres DB can start
</code>```

Implement a retry mechanism that will wait for let's say 10 seconds everytime the connection fails to establish.

If this doesn't work, I would recommend for you to check whether there is a Postgres DB installed outside of the container that owns the port you were trying to access.

Body:
I am running the docker project on docker toolbox windows 7 sp1 and the project does not give any error but still due to postgres not working the whole project in not functional.
The code of Docker compose file is :

version: '3'
services:
  postgres:
    image: 'postgres:latest'
    restart: always
    ports:
      - "5432:5432"
    environment:
      POSTGRES_DB: "db"
      POSTGRES_PASSWORD: postgres_password
      POSTGRES_HOST_AUTH_METHOD: "trust"
      DATABASE_URL: postgresql://postgres:p3wrd@postgres:5432/postgres
    deploy:
      restart_policy:
        condition: on-failure
        window: 15m
  redis:
    image: 'redis:latest'
  nginx:
    restart: always
    build:
      dockerfile: Dockerfile.dev
      context: ./nginx
    ports:
      - '3050:80'
  api:
    depends_on:
      - "postgres"
    build:
      dockerfile: Dockerfile.dev
      context: ./server
    volumes:
      - ./server/copy:/usr/src/app/data
    environment:
      - REDIS_HOST=redis
      - REDIS_PORT=6379
      - PGUSER=postgres
      - PGHOST=postgres
      - PGDATABASE=postgres
      - PGPASSWORD=postgres_password
      - PGPORT=5432
  client:
    depends_on:
      - "postgres"
    build:
      dockerfile: Dockerfile.dev
      context: ./client
    volumes:
      - ./client/copy:/usr/src/app/data
      - /usr/src/app/node_modules
  worker:
    build:
      dockerfile: Dockerfile.dev
      context: ./worker
    volumes:
      - ./worker/copy:/usr/src/app/data
      - /usr/src/app/node_modules
    depends_on:
      - "postgres"

But when i run the project i get this :

redis_1     | 1:C 29 May 2020 05:07:37.909 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
redis_1     | 1:C 29 May 2020 05:07:37.910 # Redis version=6.0.3, bits=64, commit=00000000, modified=0, pid=1, just started
redis_1     | 1:C 29 May 2020 05:07:37.911 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
redis_1     | 1:M 29 May 2020 05:07:37.922 * Running mode=standalone, port=6379.
redis_1     | 1:M 29 May 2020 05:07:37.928 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
redis_1     | 1:M 29 May 2020 05:07:37.929 # Server initialized
redis_1     | 1:M 29 May 2020 05:07:37.929 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
redis_1     | 1:M 29 May 2020 05:07:37.933 * Loading RDB produced by version 6.0.3
redis_1     | 1:M 29 May 2020 05:07:37.934 * RDB age 8 seconds
redis_1     | 1:M 29 May 2020 05:07:37.934 * RDB memory usage when created 0.81 Mb
redis_1     | 1:M 29 May 2020 05:07:37.934 * DB loaded from disk: 0.001 seconds
postgres_1  |
postgres_1  | PostgreSQL Database directory appears to contain a database; Skipping initialization
postgres_1  |
postgres_1  | 2020-05-29 05:07:38.927 UTC [1] LOG:  starting PostgreSQL 12.3 (Debian 12.3-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit
postgres_1  | 2020-05-29 05:07:38.928 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
postgres_1  | 2020-05-29 05:07:38.929 UTC [1] LOG:  listening on IPv6 address "::", port 5432
postgres_1  | 2020-05-29 05:07:38.933 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgres_1  | 2020-05-29 05:07:38.993 UTC [24] LOG:  database system was shut down at 2020-05-29 05:07:29 UTC
api_1       |
api_1       | > @ dev /usr/src/app
api_1       | > nodemon
api_1       |
api_1       | [nodemon] 1.18.3
api_1       | [nodemon] to restart at any time, enter `rs`
api_1       | [nodemon] watching: *.*

With or without data volumes the same error comes and due to which the project is not running. Please Help

Body:
I would assume that once the API starts, it attempts to connect to the Postgres. If yes,  this is a typical error that many Docker developers experience where the Postgres DB is not yet ready to accept connections and apps are trying to connect to it.

You can solve the problem by trying either of the following approaches:

Make your API layer wait for a certain amount of time (Enough for the Postgres DB to boot up)

Thread.Sleep(60); # should be enough so that Postgres DB can start

Implement a retry mechanism that will wait for let's say 10 seconds everytime the connection fails to establish.

If this doesn't work, I would recommend for you to check whether there is a Postgres DB installed outside of the container that owns the port you were trying to access.


问:
Missing DLL in docker image after copying published tree inside
I am currently experimenting with using JIB for packaging and deploying a dotnet project not written by me (I am not very familiar with dotnet).

I have the dotnet SDK installed (and visual studio 19) on my windows machine and after invoking "dotnet publish -c Release" on my solution which contain a project X and a test project X_test I end up with a bin/Release/netcoreapp2.1\publish folder.

In here I can run "dotnet X.dll" and the application starts.

Now I want to deploy said published folder to a docker image.  My first attempt was using mcr.microsoft.com/dotnet/core/runtime:2.1 which caused

```<code>It was not possible to find any compatible framework version
The specified framework 'Microsoft.AspNetCore.App', version '2.1.1' was not found.
  - Check application dependencies and target a framework version installed at:
      /usr/share/dotnet/
  - Installing .NET Core prerequisites might help resolve this problem:
      https://go.microsoft.com/fwlink/?LinkID=798306&clcid=0x409
  - The .NET Core framework and SDK can be installed from:
      https://aka.ms/dotnet-download
</code>```

I then tried using mcr.microsoft.com/dotnet/core/aspnet:2.1 which gave

```<code>C:\Users\m86194\git\microsvc-operational-information>docker run -it  operational-information-ms:0.0.1-SNAPSHOT bash
Error:
  An assembly specified in the application dependencies manifest (Operational_Information.deps.json) was not found:
    package: 'Elasticsearch.Net', version: '6.0.0'
    path: 'lib/netstandard1.3/Elasticsearch.Net.dll'
</code>```

There is an "Elasticsearch.Net.dll" file in the root of bin\Release\netcoreapp21\publish folder, but not elsewhere.

I believe there is something about the build process I am missing.

Suggestions?

答:
I had the same problem with Asp.Net Core 3 and since I'm neither well versed in Docker nor the .Net build system, I used the default Dockerfile Visual Studio creates.

```<code>FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build
WORKDIR /src
COPY ["Application/Application.csproj", "Application/"]
COPY ["Dependency1/Dependency1.csproj", "Dependency1/"]
RUN dotnet restore "Application/Application.csproj"
COPY . .
WORKDIR "/src/Application"
RUN dotnet build "Application.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "Application.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "application.dll"]
</code>```

By default it only runs dotnet restore for the main application. After adding the same for the dependent projects, it works.

```<code>FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build
WORKDIR /src
COPY ["Application/Application.csproj", "Application/"]
COPY ["Dependency1/Dependency1.csproj", "Dependency1/"]
RUN dotnet restore "Dependency1/Dependency1.csproj" <-- this one is new
RUN dotnet restore "Application/Application.csproj"
COPY . .
WORKDIR "/src/Application"
RUN dotnet build "Application.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "Application.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "application.dll"]
</code>```

Body:
I am currently experimenting with using JIB for packaging and deploying a dotnet project not written by me (I am not very familiar with dotnet).

I have the dotnet SDK installed (and visual studio 19) on my windows machine and after invoking "dotnet publish -c Release" on my solution which contain a project X and a test project X_test I end up with a bin/Release/netcoreapp2.1\publish folder.

In here I can run "dotnet X.dll" and the application starts.

Now I want to deploy said published folder to a docker image.  My first attempt was using mcr.microsoft.com/dotnet/core/runtime:2.1 which caused

It was not possible to find any compatible framework version
The specified framework 'Microsoft.AspNetCore.App', version '2.1.1' was not found.
  - Check application dependencies and target a framework version installed at:
      /usr/share/dotnet/
  - Installing .NET Core prerequisites might help resolve this problem:
      https://go.microsoft.com/fwlink/?LinkID=798306&clcid=0x409
  - The .NET Core framework and SDK can be installed from:
      https://aka.ms/dotnet-download

I then tried using mcr.microsoft.com/dotnet/core/aspnet:2.1 which gave

C:\Users\m86194\git\microsvc-operational-information>docker run -it  operational-information-ms:0.0.1-SNAPSHOT bash
Error:
  An assembly specified in the application dependencies manifest (Operational_Information.deps.json) was not found:
    package: 'Elasticsearch.Net', version: '6.0.0'
    path: 'lib/netstandard1.3/Elasticsearch.Net.dll'

There is an "Elasticsearch.Net.dll" file in the root of bin\Release\netcoreapp21\publish folder, but not elsewhere.

I believe there is something about the build process I am missing.

Suggestions?

Body:
I had the same problem with Asp.Net Core 3 and since I'm neither well versed in Docker nor the .Net build system, I used the default Dockerfile Visual Studio creates.

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build
WORKDIR /src
COPY ["Application/Application.csproj", "Application/"]
COPY ["Dependency1/Dependency1.csproj", "Dependency1/"]
RUN dotnet restore "Application/Application.csproj"
COPY . .
WORKDIR "/src/Application"
RUN dotnet build "Application.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "Application.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "application.dll"]

By default it only runs dotnet restore for the main application. After adding the same for the dependent projects, it works.

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build
WORKDIR /src
COPY ["Application/Application.csproj", "Application/"]
COPY ["Dependency1/Dependency1.csproj", "Dependency1/"]
RUN dotnet restore "Dependency1/Dependency1.csproj" <-- this one is new
RUN dotnet restore "Application/Application.csproj"
COPY . .
WORKDIR "/src/Application"
RUN dotnet build "Application.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "Application.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "application.dll"]


问:
bash script to find unique value in a file with index
I have a text file ,test.txt, like

```<code>shekhar cbv
ravi cbv
ravi sdf
asd df
ravi Df
ravi dfg
ravi df
ravi dfg
ravi df
afas cvb
sdf hgh
sasdg cfg
</code>```

I want to sort based on 2nd field and want to write 2nd field only on "result.txt"
 Currently I am doing following:

sort -k 2,2 test.txt| uniq -i -f 1 | cut -d ' ' -f2 > result.txt

which is writing 2n field i.e.

```<code>cbv
cfg
cvb
df
dfg
hgh
sdf
</code>```

Corresponding to every unique 2nd field value I want its,all, index in original file.
How this is possible ?

Desired Output:

```<code>cbv 1 2
cfg 12
cvb 10
df 4 5 7 9
dfg 6 8
hgh 11
sdf 3
</code>```

One more thing if say there is 3rd field also. How to achieve the above only mean while sorting and finding uniqueness only 2nd field is used.

input With 3rd field

```<code>    shekhar cbv rg
    ravi cbv fdf
    ravi sdf dfh
    asd df dfhdfh
    ravi Df fgh
    ravi dfg dfh
    ravi df dfgh
    ravi dfg dfgh
    ravi df dfhg
    afas cvb fhfg
    sdf hgh cgfhfg
    sasdg cfg fgh
</code>```

Desired o/p same .
Thanks,
Ravi

答:
I think you want to use cut to extract the column you want and then do the sort and uniq stuff:

```<code>cut -f2 -d' ' test.txt | sort -f | uniq -i > result.txt
</code>```

This assumes that the columns are separated by a single space.

Note that you'll want -f switch on sort so that the sorting will be case insensitive, otherwise rows that differ only in case won't be beside each other and uniq -i probably won't do what you want it to do.

ContentLicense: CC BY-SA 3.0

Body:
I have a text file ,test.txt, like

shekhar cbv
ravi cbv
ravi sdf
asd df
ravi Df
ravi dfg
ravi df
ravi dfg
ravi df
afas cvb
sdf hgh
sasdg cfg

I want to sort based on 2nd field and want to write 2nd field only on "result.txt"
 Currently I am doing following:

sort -k 2,2 test.txt| uniq -i -f 1 | cut -d ' ' -f2 > result.txt

which is writing 2n field i.e.

cbv
cfg
cvb
df
dfg
hgh
sdf

Corresponding to every unique 2nd field value I want its,all, index in original file.
How this is possible ?

Desired Output:

cbv 1 2
cfg 12
cvb 10
df 4 5 7 9
dfg 6 8
hgh 11
sdf 3

One more thing if say there is 3rd field also. How to achieve the above only mean while sorting and finding uniqueness only 2nd field is used.

input With 3rd field

    shekhar cbv rg
    ravi cbv fdf
    ravi sdf dfh
    asd df dfhdfh
    ravi Df fgh
    ravi dfg dfh
    ravi df dfgh
    ravi dfg dfgh
    ravi df dfhg
    afas cvb fhfg
    sdf hgh cgfhfg
    sasdg cfg fgh

Desired o/p same .
Thanks,
Ravi

Body:
I think you want to use cut to extract the column you want and then do the sort and uniq stuff:

cut -f2 -d' ' test.txt | sort -f | uniq -i > result.txt

This assumes that the columns are separated by a single space.

Note that you'll want -f switch on sort so that the sorting will be case insensitive, otherwise rows that differ only in case won't be beside each other and uniq -i probably won't do what you want it to do.


问:
Copy Cell With Line Breaks - Paste Values Into Separate Cells
Is there a way in VBA to copy the contents of a cell that has multiple items in it (broken up by carriage returns), and pasting the contents into another Worksheet with each original cell value in their own cell / row?

The only way I know how to do this is double-clicking into the cell (or copying from the text box when highlighting the cell), and just pasting it into a single cell elsewhere. I wish I could do this manually, but i'm dealing with a bunch of data and doing this automatically would be wonderful.

Example:

答:
Here's an example of splitting cell contents in A1 on Sheet 1, into a variable x splitting on a VBA line-feed (normally the result of ALT+ENTER in an Excel cell)

```<code>x = Split(Worksheets("Sheet 1").Range("A1").Value2, vbLf)
</code>```

Then you can cycle through the elements of x using a counter i and put each element into column B, where i+1 can be the row. Sample working routine:

```<code>Sub e()
Dim x As Variant
Dim i As Long
x = Split(Worksheets("Sheet 1").Range("A1").Value2, vbLf)
For i = LBound(x) To UBound(x)
    Worksheets("Sheet 2").Range("A" & i + 1).Value2 = x(i)
Next i
End Sub
</code>```

You could avoid looping by transposing the array directly into a Range e.g. below taking split contents of A1 and placing them in column B:

```<code>Sub e()
Dim x As Variant
x = Split(Range("A1").Value2, vbLf)
Range("B1:B" & UBound(x) + 1).Value2 = Application.WorksheetFunction.Transpose(x)
End Sub
</code>```

Body:
Here's an example of splitting cell contents in A1 on Sheet 1, into a variable x splitting on a VBA line-feed (normally the result of ALT+ENTER in an Excel cell)

x = Split(Worksheets("Sheet 1").Range("A1").Value2, vbLf)

Then you can cycle through the elements of x using a counter i and put each element into column B, where i+1 can be the row. Sample working routine:

Sub e()
Dim x As Variant
Dim i As Long
x = Split(Worksheets("Sheet 1").Range("A1").Value2, vbLf)
For i = LBound(x) To UBound(x)
    Worksheets("Sheet 2").Range("A" & i + 1).Value2 = x(i)
Next i
End Sub

You could avoid looping by transposing the array directly into a Range e.g. below taking split contents of A1 and placing them in column B:

Sub e()
Dim x As Variant
x = Split(Range("A1").Value2, vbLf)
Range("B1:B" & UBound(x) + 1).Value2 = Application.WorksheetFunction.Transpose(x)
End Sub


问:
Set background color of autocomplete on a chrome extension
I have create a chrome extension to autocomplete forms.

The code I'm using to autocomplete is basically the once from this site

```<code>$( function() {
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    $( "#tags" ).autocomplete({
      source: availableTags
    });
  } );
</code>```

It does its job, but I'm having issues to read the suggestion because the background is transparent as shown in the below image:

Is it possible from the extension to set a solid white background color?

EDIT:

I'm trying to change it as suggested. This changes work:

```<code>document.querySelector("[id='tags']").style.color="Red"
document.querySelector("[id='tags']").style.backgroundColor="Red"
</code>```

But that only changes the text box:

And I want to chang the background on the options only.

I tried this one:

```<code>document.querySelector("[id='tags']").background-color =  "Red"
</code>```

And got the following error:

```<code>Uncaught SyntaxError: Invalid left-hand side in assignment
</code>```

答:
the website you have referenced adds
 when showing autocomplete. You need to add a css for ul to have a background-color. So the following code works for me.

```<code>  ul#ui-id-1 {
   background-color: red;
  }
</code>```

Body:
I have create a chrome extension to autocomplete forms.

The code I'm using to autocomplete is basically the once from this site

$( function() {
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    $( "#tags" ).autocomplete({
      source: availableTags
    });
  } );

It does its job, but I'm having issues to read the suggestion because the background is transparent as shown in the below image:

Is it possible from the extension to set a solid white background color?

EDIT:

I'm trying to change it as suggested. This changes work:

document.querySelector("[id='tags']").style.color="Red"
document.querySelector("[id='tags']").style.backgroundColor="Red"

But that only changes the text box:

And I want to chang the background on the options only.

I tried this one:

document.querySelector("[id='tags']").background-color =  "Red"

And got the following error:

Uncaught SyntaxError: Invalid left-hand side in assignment

Body:
the website you have referenced adds <ul> when showing autocomplete. You need to add a css for ul to have a background-color. So the following code works for me.

  ul#ui-id-1 {
   background-color: red;
  }


问:
How do I crop an image in Flutter?
Let's say I have a rectangular, portrait image:

I'd like to crop it, such that it's rendered like this:

How can I do this in Flutter?

(I don't need to resize the image.)

(Image from https://flic.kr/p/nwXTDb)

答: There is a new package called ImageCropper. I would recommend everyone to use this instead as it has many features and makes everything easier. It allows you to crop the image to any or specified aspect ratio you want and can even compress the image. Here is the link to the package: https://pub.dev/packages/image_cropper

Title: How do I crop an image in Flutter?


问:
How to check and remove if string in one column matches with string in another column in R
I have a large dataframe.
Sample Data:

```<code>> df <- data.frame(MAKE = c('FORD','FORD','FORD','BMW','BMW'),
+                    MODEL = c('ECO SPORT','ECO SPORT','ECO SPORT','3 SERIES','5 SERIES'),
+                  VARIANT = c('ECOSPORT 1.0','ECOSPORT 1.5','ECOSPORT 1.5','E90','5 SERIES F(10)'),
                   stringsAsFactors = 0)
>
> df
  MAKE     MODEL        VARIANT
1 FORD ECO SPORT   ECOSPORT 1.0
2 FORD ECO SPORT   ECOSPORT 1.5
3 FORD ECO SPORT   ECOSPORT 1.5
4  BMW  3 SERIES            E90
5  BMW  5 SERIES   5 SERIES F(10)
>
</code>```

I need to find and remove the strings in "VARIANT" column that are there in "MODEL" column. I initially tried to identify the rows first using below command but it doesn't work.

```<code>> df[df$MODEL %in% df$VARIANT,]
[1] MAKE    MODEL   VARIANT
<0 rows> (or 0-length row.names)
>
</code>```

Could anyone let me know how to accomplish the same.
Expected Output:

```<code>> df
  MAKE     MODEL        VARIANT
1 FORD  ECO SPORT         1.0
2 FORD  ECO SPORT         1.5
3 FORD  ECO SPORT         1.5
4  BMW   3 SERIES         E90
5  BMW   5 SERIES         F(10)
>
</code>```

答:
We could use str_remove

```<code>library(dplyr)
library(stringr)
df %>%
    mutate_if(is.factor, as.character) %>%
    mutate(VARIANT  = str_remove_all(VARIANT,
              str_remove(MODEL, '(?<=[A-Z]) (?=[A-Z])')))
#  MAKE     MODEL VARIANT
#1 FORD ECO SPORT     1.0
#2 FORD ECO SPORT     1.5
#3 FORD ECO SPORT     1.5
#4  BMW  3 SERIES     E90
#5  BMW  5 SERIES   F(10)
</code>```

Body:
I have a large dataframe.
Sample Data:

> df <- data.frame(MAKE = c('FORD','FORD','FORD','BMW','BMW'),
+                    MODEL = c('ECO SPORT','ECO SPORT','ECO SPORT','3 SERIES','5 SERIES'),
+                  VARIANT = c('ECOSPORT 1.0','ECOSPORT 1.5','ECOSPORT 1.5','E90','5 SERIES F(10)'),
                   stringsAsFactors = 0)
>
> df
  MAKE     MODEL        VARIANT
1 FORD ECO SPORT   ECOSPORT 1.0
2 FORD ECO SPORT   ECOSPORT 1.5
3 FORD ECO SPORT   ECOSPORT 1.5
4  BMW  3 SERIES            E90
5  BMW  5 SERIES   5 SERIES F(10)
>

I need to find and remove the strings in "VARIANT" column that are there in "MODEL" column. I initially tried to identify the rows first using below command but it doesn't work.

> df[df$MODEL %in% df$VARIANT,]
[1] MAKE    MODEL   VARIANT
<0 rows> (or 0-length row.names)
>

Could anyone let me know how to accomplish the same.
Expected Output:

> df
  MAKE     MODEL        VARIANT
1 FORD  ECO SPORT         1.0
2 FORD  ECO SPORT         1.5
3 FORD  ECO SPORT         1.5
4  BMW   3 SERIES         E90
5  BMW   5 SERIES         F(10)
>

Body:
We could use str_remove

library(dplyr)
library(stringr)
df %>%
    mutate_if(is.factor, as.character) %>%
    mutate(VARIANT  = str_remove_all(VARIANT,
              str_remove(MODEL, '(?<=[A-Z]) (?=[A-Z])')))
#  MAKE     MODEL VARIANT
#1 FORD ECO SPORT     1.0
#2 FORD ECO SPORT     1.5
#3 FORD ECO SPORT     1.5
#4  BMW  3 SERIES     E90
#5  BMW  5 SERIES   F(10)


问:
What is the fastest way to perform FFT on a large file?
I am working on a C++ project that needs to perform FFT on a large 2D raster data (10 to 100 GB). In particular, the performance is quite bad when applying FFT for each column, whose elements are not contiguous in memory (placed with a stride of the width of the data).

Currently, I'm doing this. Since the data does not fit in the memory, I read several columns, namely n columns, into the memory with its orientation transposed (so that a column in the file becomes a row in the memory) and apply FFT with an external library (MKL). I read (fread) n pixels, move on to the next row (fseek as much as width - n), read n pixels, jump to the next row, and so on. When the operation (FFT) is done with the column chunk, I write it back to the file in the same manner. I write n pixels, jump to the next row, and so on. This way of reading and writing file takes too much time, so I want to find some way of boosting it.

I have considered transposing the whole file beforehand, but the entire process includes both row-major and column-major FFT operations and transposing will not benefit.

I'd like to hear any experiences or idea about this kind of column-major operations on a large data. Any suggestions related particularly to FFT or MKL will help as well.

答: Consider switching to a Hadamard Transformation. As a complete IPS, the transform offers no multiplications, since all of the coefficients in the transform are plus or minus one. If you need the resultant transform in a fourier basis, a matrix multiplication will change bases.</p>


问:
C# Sorting a DataTableCollection by a common column in each table
I'm having some troubles figuring out how to sort a DataTableCollection.  The scenario is that each table in the collection would have the same schema and have a column called "JobNumber" which I want to sort on.  The data in these tables would need to be processed in that order.

Any suggestions?

答:
I would use SortedList fill it with rows from all DataTables, that's if your JobNumer is unique, something like that :</p>

```<code>public SortedList<int, DataRow> SortDataTableCollection(DataTableCollection col)
{
  SortedList<int, DataRow> result = new SortedList<int, DataRow>();
  foreach(DataTable tbl in col)
  {
    foreach(DataRow rw in tbl.Rows)
    {
      result.Add((int)rw["JobNumber"], rw);
    }
  }
}
</code>```

Body:
I would use SortedList fill it with rows from all DataTables, that's if your JobNumer is unique, something like that :

public SortedList<int, DataRow> SortDataTableCollection(DataTableCollection col)
{
  SortedList<int, DataRow> result = new SortedList<int, DataRow>();
  foreach(DataTable tbl in col)
  {
    foreach(DataRow rw in tbl.Rows)
    {
      result.Add((int)rw["JobNumber"], rw);
    }
  }
}


问:
how to connect to flutter app from dart devTools
when i run "flutter pub global run devtools"
enter image description here

where i can find  URL to a running Dart or Flutter application. to connect to??

答:
You can follow the Dart documentation on how to do that via the link below:

https://dart.dev/tools/dart-devtools


问:
Understanding Coefficient of Determination
I was going through the documentation to understand the Coefficient of Determination and from the document i got an understanding that Coefficient of Determination is nothing but R x R (correlation coefficient)

so i took the housing price dataset from kaggle.com and started to try on it for better understanding, this is my code

took the correlation coefficient

```<code>test_data=pd.read_csv(r'\house_price\test.csv')
_d=test_data.loc[:,['MSSubClass','LotFrontage']]
_d.fillna(0,inplace=True)
_d.corr()
</code>```

now, taking the Coefficient of Determination like this

```<code>from sklearn.metrics import r2_score
r2_score(_d['MSSubClass'],_d['LotFrontage'])
</code>```

for which, i got the value -0.9413195412943647

ideally shouldnt it be 0.060531252961 ? as -0.246031 x -0.246031 = 0.060531252961

答:
What you are referencing as the "documentation" is just a blogpost describing one of the many variations of R2. I recommend reading the official scikit-learn documentation to understand their implementation in the r2_score.

In short, a value of 0 means that the model does not perform any different from a model that simply predicts the expected value (i.e. the mean) of the target variable. A value of 1 on the other hand means that the model is perfect with no errors in its predictions. However, and this is the main difference to what your provided blogpost states, you will see that it allows for negative values as a model can perform arbitrarily worse than simply predicting the expected value of the target variable.

And this is what the r2_score of scikit-learn is telling you in your case: the model you fit is worse, i.e. produces a higher error on average, than just predicting the mean of the house prices.

Body:
I was going through the documentation to understand the Coefficient of Determination and from the document i got an understanding that Coefficient of Determination is nothing but R x R (correlation coefficient)

so i took the housing price dataset from kaggle.com and started to try on it for better understanding, this is my code

took the correlation coefficient

test_data=pd.read_csv(r'\house_price\test.csv')
_d=test_data.loc[:,['MSSubClass','LotFrontage']]
_d.fillna(0,inplace=True)
_d.corr()

now, taking the Coefficient of Determination like this

from sklearn.metrics import r2_score
r2_score(_d['MSSubClass'],_d['LotFrontage'])

for which, i got the value -0.9413195412943647

ideally shouldnt it be 0.060531252961 ? as -0.246031 x -0.246031 = 0.060531252961


问:
Suggestion regarding Cost reduction on Using Dynamodb
I'm newbie to dynamodb, I have just 10 items and 1 global secondary Index with Read/write capacity units 5(minimum) which cost around $6/2days which is unacceptable for me because I have used only  0.01% of my actual needs I have gone through some documentation in aws dynamodb price reduction non helped me, because AWS recommend to avoid sudden spike read using query or scan, which is impossible to get more than one item with Partition key alone.

Tables as follows

Add_Employee

Add_Stocks

Add_vendor

All above table have read/write capacity units 1 and each have one global secondary index read/write capacity units 1. All tables are config within specified region Asia Pacific (Mumbai)

Here is my billing for reference

$0.00 per hour for 25 units of read capacity for a month (free tier)18,600 ReadCapacityUnit-Hrs $0.00

$0.00 per hour for 25 units of write capacity for a month (free tier)18,600 WriteCapacityUnit-Hrs $0.00

$0.000148 per hour for units of read capacity beyond the free tier 6,723 ReadCapacityUnit-Hrs $1.00

$0.00074 per hour for units of write capacity beyond the free tier 6,723 WriteCapacityUnit-Hrs $4.98

Thanks in advance

答:
You're not just paying for actual throughput, you're paying for provisioned throughput.

Looking at The Dynamo cost page, this means you are paying $0.0065 per throughput-hour each table exists per month, minus the free-tier hours.

Based on your table names, I'm guessing you are not following the best practice of using 1 de-normalized table table for everything.  You may be better off using an RDS instance, which will not charge by the table, but by the hour (it's an EC2 instance behind the scenes).

Cost Breakdown

The default is 5 provisioned read/write units, and there are 720 hours in a 30-day month

$0.0065 * 5 * 720 = $24.37 a month per table

The free tier generally allows one table for free a month.

Per AWS docs you must have at least 1 provisioned unit.

How to Save

Make sure you're following the best practice of using 1 de-normalized table

For any dev work, make sure both read and write provisions are set to 1 ($0.0065 * 1 * 720 = $4.68 a month per table)

If you know you're going to be away for a while, remove the stack from AWS.  You're only charged while the table(s) exists.

By limiting read/write units you should be able to bring the cost down to ~$5.00 a table per dev.

DO NOT TURN ON AUTO-SCALING

A commenter suggested auto-scaling.  Per docs, you'll be charged for at least 5 units, which is what you are paying now.

This AWS forum link is about the same thing.


问:
ISO 3779 vehicle VIN decoder in PHP?
Does anyone know of a ISO 3779 vehicle VIN decoder library in PHP, or Perl, or Python (or any other language, I can convert code easily) available as open source/freeware?

Even just something to decode the WMI portion (first 3 positions) would save me a lot of time.  Thanks in advance.

http://en.wikipedia.org/wiki/Vehicle_identification_number

答:
I'll let you scrape the data from Wikipedia, but below is a quick (modular) sample you can expand upon (finish off the WMI->Init() method). I would also probably make the VINLookup class a singleton or break off the WMI in to a database (normalize the data somewhere and treat it like a base-33 number like I have [possibly]).

```<code>// http://en.wikipedia.org/wiki/Vehicle_identification_number#World_Manufacturer_Identifier

define('VIN_CHARACTERS', 'ABCDEFGHJKLMNPRSTUVWXYZ1234567890'); // no I, O or Q & 0 is last.

class WMI
{
  public $country;
  public $region;
  public $low;
  public $high;

  public function __construct($country,$region,$low,$high)
  {
    $this->country = $country;
    $this->region = $region;
    $this->low = $low;
    $this->high = $high;
  }

  private static function CodeToDec($code)
  {
    if (strlen($code) != 2)
      return false;

    return (strpos(VIN_CHARACTERS, $code{0}) * strlen(VIN_CHARACTERS)) + strpos(VIN_CHARACTERS, $code{1});
  }

  public function IsMatch($vin)
  {
    // first, grab the first 2 characters
    $code = substr($vin,0,2);

    // next, see if it's in range
    // we do this by converting it to a numeric
    $_low = WMI::CodeToDec($this->low);
    $_high = WMI::CodeToDec($this->high);
    $_code = WMI::CodeToDec($code);

    return (($_code >= $_low) && ($_code <= $_high));
  }

  public function __toString()
  {
    return sprintf("%s, %s (%s, %s)", $this->country, $this->region, $this->low, $this->high);
  }
}

class VINLookup
{
  private $vin;
  private $wmis = array();

  public function __construct($vin)
  {
    if (!VINLookup::IsValid($vin))
      throw new Exception('Invalid VIN specified');

    $this->vin = $vin;

    $this->Init();
  }

  private function Init()
  {
    $this->wmis = array(
      new WMI('South Africa',     'Africa',         'AA', 'AH'),
      new WMI('Ivory Coast',      'Africa',         'AJ', 'AN'),
      new WMI('(not assigned)',   'Africa',         'AP', 'A0'),
      new WMI('Angola',           'Africa',         'BA', 'BE'),
      new WMI('Kenya',            'Africa',         'BF', 'BK'),

      new WMI('United States',    'North America',  '1A', '10'),
      new WMI('Canada',           'North America',  '2A', '20'),
      new WMI('Mexico',           'North America',  '3A', '3W'),
      new WMI('Costa Rica',       'North America',  '3X', '37'),
    );
  }

  public function GetCountry()
  {
    foreach ($this->wmis as $wmi)
    {
      if ($wmi->IsMatch($this->vin))
        return $wmi;
    }
    return false;
  }

  public static function IsValid($vin)
  {
    return preg_match('/^[A-HJ-NPR-Z0-9]{17}$/',$vin);
  }
}
</code>```

Usage:

```<code>// check for a valid VIN number supplied
VINLookup::IsValid(<vin>);

// create a new VINLookup with the specified VIN
$lookup = new VINLookup(<vin>);

// retrieve the _Country_ object (above), or FALSE if no country match was found.
$lookup->GetCountry();
</code>```

Title: ISO 3779 vehicle VIN decoder in PHP?

Body:
I'll let you scrape the data from Wikipedia, but below is a quick (modular) sample you can expand upon (finish off the WMI->Init() method). I would also probably make the VINLookup class a singleton or break off the WMI in to a database (normalize the data somewhere and treat it like a base-33 number like I have [possibly]).

// http://en.wikipedia.org/wiki/Vehicle_identification_number#World_Manufacturer_Identifier

define('VIN_CHARACTERS', 'ABCDEFGHJKLMNPRSTUVWXYZ1234567890'); // no I, O or Q & 0 is last.

class WMI
{
  public $country;
  public $region;
  public $low;
  public $high;

  public function __construct($country,$region,$low,$high)
  {
    $this->country = $country;
    $this->region = $region;
    $this->low = $low;
    $this->high = $high;
  }

  private static function CodeToDec($code)
  {
    if (strlen($code) != 2)
      return false;

    return (strpos(VIN_CHARACTERS, $code{0}) * strlen(VIN_CHARACTERS)) + strpos(VIN_CHARACTERS, $code{1});
  }

  public function IsMatch($vin)
  {
    // first, grab the first 2 characters
    $code = substr($vin,0,2);

    // next, see if it's in range
    // we do this by converting it to a numeric
    $_low = WMI::CodeToDec($this->low);
    $_high = WMI::CodeToDec($this->high);
    $_code = WMI::CodeToDec($code);

    return (($_code >= $_low) && ($_code <= $_high));
  }

  public function __toString()
  {
    return sprintf("%s, %s (%s, %s)", $this->country, $this->region, $this->low, $this->high);
  }
}

class VINLookup
{
  private $vin;
  private $wmis = array();

  public function __construct($vin)
  {
    if (!VINLookup::IsValid($vin))
      throw new Exception('Invalid VIN specified');

    $this->vin = $vin;

    $this->Init();
  }

  private function Init()
  {
    $this->wmis = array(
      new WMI('South Africa',     'Africa',         'AA', 'AH'),
      new WMI('Ivory Coast',      'Africa',         'AJ', 'AN'),
      new WMI('(not assigned)',   'Africa',         'AP', 'A0'),
      new WMI('Angola',           'Africa',         'BA', 'BE'),
      new WMI('Kenya',            'Africa',         'BF', 'BK'),

      new WMI('United States',    'North America',  '1A', '10'),
      new WMI('Canada',           'North America',  '2A', '20'),
      new WMI('Mexico',           'North America',  '3A', '3W'),
      new WMI('Costa Rica',       'North America',  '3X', '37'),
    );
  }

  public function GetCountry()
  {
    foreach ($this->wmis as $wmi)
    {
      if ($wmi->IsMatch($this->vin))
        return $wmi;
    }
    return false;
  }

  public static function IsValid($vin)
  {
    return preg_match('/^[A-HJ-NPR-Z0-9]{17}$/',$vin);
  }
}

Usage:

// check for a valid VIN number supplied
VINLookup::IsValid(<vin>);

// create a new VINLookup with the specified VIN
$lookup = new VINLookup(<vin>);

// retrieve the _Country_ object (above), or FALSE if no country match was found.
$lookup->GetCountry();


问:
How to use multiple data frame inputs for Mapdeck add_scatterplot within R Shiny?
I'm finding Mapdeck to be a really cool alternative mapping method when working with large datasets in r shiny.  However I'm finding it difficult to pass in multiple datasets in order to expand the complexity of the resulting map.

For Example: I'm trying to populate the tooltip to create a popup with 'two' items by pulling in information from a second data frame (to illustrate a 1-to-many relationship).  But I can't get it to work.  Any thoughts?

Data sample

```<code>Map_DF <- data.frame("Point_ID" = 1:3, "Latitude" = c(38.05, 39.08, 40.05), "Longitude" = c(-107.00, -107.05, -108.00))
PointUse_DF <- data.frame("Point_ID" = c(1, 1, 2, 2, 3), "PointUse" = c("farm", "house", "farm", "house", "farm"))
</code>```

The Code.

```<code># ################################################################################################
# ################################################################################################
# # Sec 1a. Needed Libaries & Input Files

library(shiny)
library(shinydashboard)
library(mapdeck)
library(dplyr)

################################################################################################
################################################################################################
#UI
ui <- dashboardPage(
    dashboardHeader(),
    dashboardSidebar(),
    dashboardBody(
        mapdeckOutput(outputId = 'mapA')
    )
)

################################################################################################
################################################################################################
server <- function(input, output) {

    ##The MapDeck Token
    key <- '## put your own token here ##'
    set_token(key) ## set your access token

    ### The Map
    output$mapA <- renderMapdeck({
     mapdeck() %>%
            add_scatterplot(
                data = Map_DF,
                lat = "Latitude",
                lon = "Longitude",
                layer_id = 'Point_ID',
                tooltip = c("Point_ID",
                             PointUse_DF$PointUse[Map_DF$Point_ID]  # the idea of passing in a a key and returning multiple items
                            )
             )
    })

}

################################################################################################
################################################################################################
shinyApp(ui = ui, server = server)
</code>```

答:
The tooltip renders a column of the data object inside the popup.
So whatever you want displayed in the popup has to already exist on the data

with your example you need to create the tooltip column

```<code># Using data.table to rshape the data to give a comma-separated list of 'PointUse' values
library(data.table)

dt <- setDT( PointUse_DF )[, .(info = paste0(PointUse, collapse = ", ")), by = Point_ID]

## Now you can put this onto the map object

Map_DF <- merge(
  x = Map_DF
  , y = dt
  , by = "Point_ID"
  , all.x = T
)

mapdeck() %>%
  add_scatterplot(
    data = Map_DF,
    lat = "Latitude",
    lon = "Longitude",
    layer_id = 'Point_ID',
    radius_min_pixels = 3,
    tooltip = "info"
    )
  )
</code>```

Body:
I'm finding Mapdeck to be a really cool alternative mapping method when working with large datasets in r shiny.  However I'm finding it difficult to pass in multiple datasets in order to expand the complexity of the resulting map.

For Example: I'm trying to populate the tooltip to create a popup with 'two' items by pulling in information from a second data frame (to illustrate a 1-to-many relationship).  But I can't get it to work.  Any thoughts?

Data sample

Map_DF <- data.frame("Point_ID" = 1:3, "Latitude" = c(38.05, 39.08, 40.05), "Longitude" = c(-107.00, -107.05, -108.00))
PointUse_DF <- data.frame("Point_ID" = c(1, 1, 2, 2, 3), "PointUse" = c("farm", "house", "farm", "house", "farm"))

The Code.

# ################################################################################################
# ################################################################################################
# # Sec 1a. Needed Libaries & Input Files

library(shiny)
library(shinydashboard)
library(mapdeck)
library(dplyr)

################################################################################################
################################################################################################
#UI
ui <- dashboardPage(
    dashboardHeader(),
    dashboardSidebar(),
    dashboardBody(
        mapdeckOutput(outputId = 'mapA')
    )
)

################################################################################################
################################################################################################
server <- function(input, output) {

    ##The MapDeck Token
    key <- '## put your own token here ##'
    set_token(key) ## set your access token

    ### The Map
    output$mapA <- renderMapdeck({
     mapdeck() %>%
            add_scatterplot(
                data = Map_DF,
                lat = "Latitude",
                lon = "Longitude",
                layer_id = 'Point_ID',
                tooltip = c("Point_ID",
                             PointUse_DF$PointUse[Map_DF$Point_ID]  # the idea of passing in a a key and returning multiple items
                            )
             )
    })

}

################################################################################################
################################################################################################
shinyApp(ui = ui, server = server)

Body:
The tooltip renders a column of the data object inside the popup.
So whatever you want displayed in the popup has to already exist on the data

with your example you need to create the tooltip column

# Using data.table to rshape the data to give a comma-separated list of 'PointUse' values
library(data.table)

dt <- setDT( PointUse_DF )[, .(info = paste0(PointUse, collapse = ", ")), by = Point_ID]

## Now you can put this onto the map object

Map_DF <- merge(
  x = Map_DF
  , y = dt
  , by = "Point_ID"
  , all.x = T
)

mapdeck() %>%
  add_scatterplot(
    data = Map_DF,
    lat = "Latitude",
    lon = "Longitude",
    layer_id = 'Point_ID',
    radius_min_pixels = 3,
    tooltip = "info"
    )
  )


问:
How to setup protocols and delegates on a static table view?
I am trying to setup a static table view that has a segue to another table view with a list. The user then selects an item from the list, and it updates the main (static) table view. I have setup delegates but I think I am missing something. When selecting a item from the list, it throws an exception of "unexpectedly finding 'nil' when force unwrapping optional". It appears the optional is the protocol itself.

Error Screenshot

Storyboard Diagram

The main Table View file

```<code>//
//  AddAssetTableViewController.swift
//  ItemizePro
//
//  Created by Tyler Wasick on 5/27/20.
//  Copyright © 2020 Tyler Wasick. All rights reserved.
//

import UIKit

class AddAssetTableViewController: UITableViewController {

    // TODO: Add image IBOutlet

    @IBOutlet weak var nameTextField: UITextField!

    @IBOutlet weak var descriptionTextField: UITextField!

    @IBOutlet weak var datePurchasedTextField: UITextField!

    @IBOutlet weak var manufactureTextField: UITextField!

    @IBOutlet weak var modelTextField: UITextField!

    @IBOutlet weak var serialNumberTextField: UITextField!

    @IBOutlet weak var costTextField: UITextField!

    @IBOutlet weak var roomTextField: UITextField!

    @IBOutlet weak var notesTextView: UITextView!

    @IBOutlet weak var receiptTextField: UITextField!

    @IBOutlet weak var addUIButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem

    }

    // MARK: - Table view data source

    /*
     override func numberOfSections(in tableView: UITableView) -> Int {
     // #warning Incomplete implementation, return the number of sections
     return 0
     }

     override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
     // #warning Incomplete implementation, return the number of rows
     return 0
     }

     override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCell(withIdentifier: "imageCell", for: indexPath)

     // Configure the cell...

     return cell
     }
     */

    /*
     // Override to support conditional editing of the table view.
     override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
     // Return false if you do not want the specified item to be editable.
     return true
     }
     */

    /*
     // Override to support editing the table view.
     override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
     if editingStyle == .delete {
     // Delete the row from the data source
     tableView.deleteRows(at: [indexPath], with: .fade)
     } else if editingStyle == .insert {
     // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
     }
     }
     */

    /*
     // Override to support rearranging the table view.
     override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

     }
     */

    /*
     // Override to support conditional rearranging of the table view.
     override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
     // Return false if you do not want the item to be re-orderable.
     return true
     }
     */

    /*
     // MARK: - Navigation

     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destination.
     // Pass the selected object to the new view controller.
     }
     */

    // MARK: - Functions

    // MARK: - IBAction outlets

    @IBAction func addButtonTapped(_ sender: UIButton) {

    }

}

extension AddAssetTableViewController : RoomDelegate {
    func tappedOnRoom(room: String) {
        roomTextField.text = room
    }
}

</code>```

The Table View with a list of items (rooms) to select, which gets passed back to the first table view controller

```<code>//
//  RoomListViewController.swift
//  ItemizePro
//
//  Created by Tyler Wasick on 5/25/20.
//  Copyright © 2020 Tyler Wasick. All rights reserved.
//

import UIKit

protocol RoomDelegate {
    func tappedOnRoom(room: String)
}
class RoomListViewController : UIViewController {

    var selectionDelegate : RoomDelegate!

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        // Configure table view
        tableView.dataSource = self
        tableView.delegate = self

    }

    // When user taps on a room, it returns the room to the delagate and dismisses
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        // Assign the selection to 'selectedRoom'
        let selectedRoom = UserSettings.roomList[indexPath.row]

        // Return the room to the delegate
        selectionDelegate.tappedOnRoom(room: selectedRoom)
    }
}

extension RoomListViewController: UITableViewDataSource, UITableViewDelegate {

    // UITableViewDelegate
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return UserSettings.roomList.count
    }

    // UITableViewDataSource
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        // Setup cell
        let cell = tableView.dequeueReusableCell(withIdentifier: "RoomListCell", for: indexPath) as! RoomListView

        // Set the details for the cell
        let room = UserSettings.roomList[indexPath.row]
        cell.setRoomCell(room)

        // Return the cell
        return cell
    }

}
</code>```

答:
The crash is due to you using a force-unwrapped delegate which you have not provided a value for.

Make your Protocol class bound:
This will allow you to create a weak reference to your delegate

```<code>protocol RoomDelegate: class {
    func tappedOnRoom(room: String)
}
</code>```

Make your delegate weak and optional:

```<code>weak var selectionDelegate: RoomDelegate?
</code>```

Set the delegate in the prepareForSegue method of your AddAssetTableViewController.  This is the code that you are missing.

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let vc = segue.destination as? RoomListViewController {
        vc.selectionDelegate = self
    }
}
</code>```

Use optional chaining when calling the delegate

```<code>selectionDelegate?.tappedOnRoom(room: selectedRoom)
</code>```

Body:
I am trying to setup a static table view that has a segue to another table view with a list. The user then selects an item from the list, and it updates the main (static) table view. I have setup delegates but I think I am missing something. When selecting a item from the list, it throws an exception of "unexpectedly finding 'nil' when force unwrapping optional". It appears the optional is the protocol itself.

Error Screenshot

Storyboard Diagram

The main Table View file

//
//  AddAssetTableViewController.swift
//  ItemizePro
//
//  Created by Tyler Wasick on 5/27/20.
//  Copyright © 2020 Tyler Wasick. All rights reserved.
//

import UIKit

class AddAssetTableViewController: UITableViewController {

    // TODO: Add image IBOutlet

    @IBOutlet weak var nameTextField: UITextField!

    @IBOutlet weak var descriptionTextField: UITextField!

    @IBOutlet weak var datePurchasedTextField: UITextField!

    @IBOutlet weak var manufactureTextField: UITextField!

    @IBOutlet weak var modelTextField: UITextField!

    @IBOutlet weak var serialNumberTextField: UITextField!

    @IBOutlet weak var costTextField: UITextField!

    @IBOutlet weak var roomTextField: UITextField!

    @IBOutlet weak var notesTextView: UITextView!

    @IBOutlet weak var receiptTextField: UITextField!

    @IBOutlet weak var addUIButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem

    }

    // MARK: - Table view data source

    /*
     override func numberOfSections(in tableView: UITableView) -> Int {
     // #warning Incomplete implementation, return the number of sections
     return 0
     }

     override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
     // #warning Incomplete implementation, return the number of rows
     return 0
     }

     override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCell(withIdentifier: "imageCell", for: indexPath)

     // Configure the cell...

     return cell
     }
     */

    /*
     // Override to support conditional editing of the table view.
     override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
     // Return false if you do not want the specified item to be editable.
     return true
     }
     */

    /*
     // Override to support editing the table view.
     override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
     if editingStyle == .delete {
     // Delete the row from the data source
     tableView.deleteRows(at: [indexPath], with: .fade)
     } else if editingStyle == .insert {
     // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
     }
     }
     */

    /*
     // Override to support rearranging the table view.
     override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

     }
     */

    /*
     // Override to support conditional rearranging of the table view.
     override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
     // Return false if you do not want the item to be re-orderable.
     return true
     }
     */

    /*
     // MARK: - Navigation

     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destination.
     // Pass the selected object to the new view controller.
     }
     */

    // MARK: - Functions

    // MARK: - IBAction outlets

    @IBAction func addButtonTapped(_ sender: UIButton) {

    }

}

extension AddAssetTableViewController : RoomDelegate {
    func tappedOnRoom(room: String) {
        roomTextField.text = room
    }
}

The Table View with a list of items (rooms) to select, which gets passed back to the first table view controller

//
//  RoomListViewController.swift
//  ItemizePro
//
//  Created by Tyler Wasick on 5/25/20.
//  Copyright © 2020 Tyler Wasick. All rights reserved.
//

import UIKit

protocol RoomDelegate {
    func tappedOnRoom(room: String)
}
class RoomListViewController : UIViewController {

    var selectionDelegate : RoomDelegate!

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        // Configure table view
        tableView.dataSource = self
        tableView.delegate = self

    }

    // When user taps on a room, it returns the room to the delagate and dismisses
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        // Assign the selection to 'selectedRoom'
        let selectedRoom = UserSettings.roomList[indexPath.row]

        // Return the room to the delegate
        selectionDelegate.tappedOnRoom(room: selectedRoom)
    }
}

extension RoomListViewController: UITableViewDataSource, UITableViewDelegate {

    // UITableViewDelegate
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return UserSettings.roomList.count
    }

    // UITableViewDataSource
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        // Setup cell
        let cell = tableView.dequeueReusableCell(withIdentifier: "RoomListCell", for: indexPath) as! RoomListView

        // Set the details for the cell
        let room = UserSettings.roomList[indexPath.row]
        cell.setRoomCell(room)

        // Return the cell
        return cell
    }

}

Body:
The crash is due to you using a force-unwrapped delegate which you have not provided a value for.

Make your Protocol class bound:
This will allow you to create a weak reference to your delegate

protocol RoomDelegate: class {
    func tappedOnRoom(room: String)
}

Make your delegate weak and optional:

weak var selectionDelegate: RoomDelegate?

Set the delegate in the prepareForSegue method of your AddAssetTableViewController.  This is the code that you are missing.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let vc = segue.destination as? RoomListViewController {
        vc.selectionDelegate = self
    }
}

Use optional chaining when calling the delegate

selectionDelegate?.tappedOnRoom(room: selectedRoom)


问:
C ++ How to change the value of 4 bits in a 32 bit number
I have a 32-bit register that I need to manipulate. But I only need to change bits 12-15, and leave the rest of the bits unchanged.

I want to overwrite whatever is in bits 12-15 with 0x2 or 0b0010.

How can I do this in C++?

Here is an example code I have been trying.

```<code>#include <iostream>
#include <bitset>

using namespace std;

int main() {
    uint32_t x = 0x4D00D0F0;

    x |= 0x2 << 12; // shifting 0x2 12 bits to the left

    return 0;
}
</code>```

My solution only seems to shift a 1 to bit 13, why is that?

Can I shift an entire 4-bit hex number?

Bottom line, I want x = 0x4D0020F0

答:
First, mask the original bits out to make sure they are zeroed and won't interfere with the value, you are going to "or" there:

x & 0xffff0fff

Then "or" the new bits into place:

(x & 0xffff0fff) | (0x2 << 12)

Body:
I have a 32-bit register that I need to manipulate. But I only need to change bits 12-15, and leave the rest of the bits unchanged.

I want to overwrite whatever is in bits 12-15 with 0x2 or 0b0010.

How can I do this in C++?

Here is an example code I have been trying.

#include <iostream>
#include <bitset>

using namespace std;

int main() {
    uint32_t x = 0x4D00D0F0;

    x |= 0x2 << 12; // shifting 0x2 12 bits to the left

    return 0;
}

My solution only seems to shift a 1 to bit 13, why is that?

Can I shift an entire 4-bit hex number?

Bottom line, I want x = 0x4D0020F0


问:
Azure sql database subscription
I have a project for university and i have to use Azure Sql Database. I've made a student account which gave me 100 dollars to spend.
My problem is that in 2 or 3 days all my money were gone and now my subscription is disabled. I will make another account or something, but my question is: do you know why it cost me that much?

I think i've done something wrong when creating the database, because i don't think it costs that much usually. Can you help me understand?

答:
As a complement:

Please go to Azure SQL database configure page to check the current price tier of the database:

If your database is not very large(less than 2G), you could change to DTU based model price tier, you only need to pay for 4.99$/month.

Ref: Service tiers in the DTU-based purchase model.

Hope this helps.

Title: Azure sql database subscription


问:
WebView wrap-content
Is it possible to load a URL in a WebView and resize it to fit the screen? I mean I want to make the WebPage small so that the user doesn't need to scroll. Is this possible?</p>

答:
I was able to contain the entire page in my view by doing the following. First set the width and height to wrap_content. Then setting the initial scale to one like this:

```<code>WebView webview = (WebView) currentActivity.findView(R.layout.web_view, R.id.webview);
webview.setInitialScale(1);
</code>```

I found that I could get this to keep the width to the minimum necessary to display a readable font and then scroll along the y coordinate every time by doing the following.  First set both the height and width to wrap_content.  Then set the zoom density to far in your code like this:

```<code>WebView webview = (WebView) currentActivity.findView(R.layout.web_view, R.id.webview);
webview.getSettings().setDefaultZoom(ZoomDensity.FAR);
</code>```

This is probably the better solution most of the time.  Consider how small the font would be if you displayed the following web page in its entirety:

Title: WebView wrap-content

Body:
I was able to contain the entire page in my view by doing the following. First set the width and height to wrap_content. Then setting the initial scale to one like this:

WebView webview = (WebView) currentActivity.findView(R.layout.web_view, R.id.webview);
webview.setInitialScale(1);

I found that I could get this to keep the width to the minimum necessary to display a readable font and then scroll along the y coordinate every time by doing the following.  First set both the height and width to wrap_content.  Then set the zoom density to far in your code like this:

WebView webview = (WebView) currentActivity.findView(R.layout.web_view, R.id.webview);
webview.getSettings().setDefaultZoom(ZoomDensity.FAR);

This is probably the better solution most of the time.  Consider how small the font would be if you displayed the following web page in its entirety:


问:
Deploy internal asp.net project in IIS with ssl
I am creating an internal application which will be published on the IIS server of an ad ds domain, this will be internal and therefore not accessible from the internet so I cannot obtain a certificate from a certification authority. I manage to put the project online on IIS and access it from my SSL port 44313, but then google chrome sends the message that the site is not recognized and is therefore not secure. Is there a way to make all browsers in the domain ad ds recognize the certificate as secure? thank you in advance!</p>

答:
The link is useful,

https://learn.microsoft.com/en-us/windows-server/networking/core-network-guide/cncg/server-certs/install-the-certification-authority

If we want Google browser to recognize our server certificate(browser address bar will display a secure lock mark), we must install the server certificate on the client to the local certificate store(Trusted Root Certification Authorities or Trusted people) to indicate trust in the server certificate. In a simple case, we must install a single certificate one-to-one, if you want all machines in AD to trust the server, the best way is to install and establish a certificate authority in the domain, which will establish a certificate trust chain. Because every machine that joins the domain will contain the root certificate.

Feel free to let me know if there is anything I can help with.


问:
Can a domain service inject multiple repositories or operate with different aggregate roots?
Can a domain service inject multiple repositories or operate with different aggregate roots? If yes, would it be considered a violation of the SRP principle?

I am looking in depth and I have this question regarding domain services. If I have a business logic that involves working with several Aggregate Roots, what would be the best way to solve it with a Domain Service?

Thanks!

答:
Can a domain service inject multiple repositories or operate with different aggregate roots?

I see no problem with this as I find that working with multiple aggregates is usually where you need a domain service since the functionality doesn't seem to fit on a particular aggregate.  If the service does not fetch the relevant objects then they could be passed in from the integration/application concern.  In fact, you probably want to start there: a method that accepts the relevant aggregates.  You may find that it makes more sense to retrieve the objects in the caller before invoking the service method.

If yes, would it be considered a violation of the SRP principle?

The SRP is about what your class does and not what it uses so unless you are adding more functionality than is required I don't see how SRP is negatively affected.


问:
git fetch --unshallow gives :"fatal: --unshallow on a complete repository does not make sense" error
I am unable to git clone a remote repository using plain

```<code>git clone path
</code>```

I get the error "The remote end hung up unexpectedly".
The complete msg I get is :

```<code>Cloning into 'xyzabc'...
remote: Counting objects: 4328, done.
remote: Compressing objects: 100% (3861/3861), done.
select: Not enough memory2192/4328), 123.71 MiB | 164.00 KiB/s
ffatal: The remote end hung up unexpectedly
atal: early EOF
fatal: index-pack failed
</code>```

I search online for a solution and after trying every other solution landed on solution of doing :

```<code>git clone --depth=1 path
</code>```

followed by

```<code>git fetch --unshallow
</code>```

Now the clone is completing fully. But, when I try to run git fetch --unshallow to recieve the complete project, I get the error :

```<code>fatal: --unshallow on a complete repository does not make sense
</code>```

I dont know what to do please guide

答:
you are missing one step here,

after

```<code>git clone --depth=1 path
</code>```

after this cd into your project directory,

```<code>cd <intoPartiallyClonedProject>
</code>```

then,you need to perform
git fetch --depth=N, with increasing N
like

```<code>git fetch --depth=5
git fetch --depth=200
git fetch --depth=500
git fetch --depth=1000
</code>```

and then perform

this is best explained in detail in this answer,

answer by me i.e NikhilP

error: RPC failed; curl transfer closed with outstanding read data remaining

upvote if it helps you.

Body:
I am unable to git clone a remote repository using plain

git clone path

I get the error "The remote end hung up unexpectedly".
The complete msg I get is :

Cloning into 'xyzabc'...
remote: Counting objects: 4328, done.
remote: Compressing objects: 100% (3861/3861), done.
select: Not enough memory2192/4328), 123.71 MiB | 164.00 KiB/s
ffatal: The remote end hung up unexpectedly
atal: early EOF
fatal: index-pack failed

I search online for a solution and after trying every other solution landed on solution of doing :

git clone --depth=1 path

followed by

git fetch --unshallow

Now the clone is completing fully. But, when I try to run git fetch --unshallow to recieve the complete project, I get the error :

fatal: --unshallow on a complete repository does not make sense

I dont know what to do please guide

Body:
you are missing one step here,

after

git clone --depth=1 path

after this cd into your project directory,

cd <intoPartiallyClonedProject>

then,you need to perform
git fetch --depth=N, with increasing N
like

git fetch --depth=5
git fetch --depth=200
git fetch --depth=500
git fetch --depth=1000

and then perform

this is best explained in detail in this answer,

answer by me i.e NikhilP

error: RPC failed; curl transfer closed with outstanding read data remaining

upvote if it helps you.


问:
Generating binary entries array in python
I would like to generate an array as follows:

```<code>[[0,0,0],
 [0,0,1],
 [0,1,0],
 [0,1,1],
 [1,0,0],
 [1,0,1],
 [1,1,0]
 [1,1,1]]
</code>```

I tried to achieve this by setting 3 for loops, but I wish to go further to 4, 5, and higher bit-numbers, so the last method would not scale easly to these numbers.

Is there any simple way for doing this?

答:
You can use itertools.product to do this.

```<code>>>> import itertools
>>> list(itertools.product([0,1], repeat=3))
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
</code>```

https://docs.python.org/3/library/itertools.html#itertools.product

Body:
I would like to generate an array as follows:

[[0,0,0],
 [0,0,1],
 [0,1,0],
 [0,1,1],
 [1,0,0],
 [1,0,1],
 [1,1,0]
 [1,1,1]]

I tried to achieve this by setting 3 for loops, but I wish to go further to 4, 5, and higher bit-numbers, so the last method would not scale easly to these numbers.

Is there any simple way for doing this?

Body:
You can use itertools.product to do this.

>>> import itertools
>>> list(itertools.product([0,1], repeat=3))
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

https://docs.python.org/3/library/itertools.html#itertools.product


问:
Adding more commits to a Branch in Git
Apologies in advance. I'm sure this is a very simple question with a very simple answer but I'm a beginner at Git and I'm a bit lost. I have a master branch. I made some changes yesterday and performed git add ., git commit, made a new branch by doing git branch part-one, then I pushed the commits to that new branch by doing git push origin part-one. I see that my commits got pushed into that branch on github. Now, I did some more work on the same files. I added and staged the changes just as before. Now when I go to push the commits by doing git push origin part-one it says Everything up-to-date. I don't see the most recent commits in my history on github.

Why is it not pushing the most recent commit to my part-one branch?

Possible cause: If I wanted to push these commits to my branch. Was I supposed to be do git checkout part-one, then do git add and git commit? I did those commands while I was on the master.

答: You stopped after staging, you haven't committed, nothing to push (that's following your descruption). You said added and then staged.... that's the same thing. You meant added and committed?</p>

Title: Adding more commits to a Branch in Git


问:
Obtaining Sensor Data and motor control values?
I am currently using Webots and new to the software framework. I need to implement a robot at the moment and get the sensor data and motor control values from it. The robot is a self-made robot and is not one of them already implemented tutorials. Can someone elaborate on how to get those values? I am trying to implement it in C++ if someone could help me with the syntax of the code to obtain the values?

答:
You should start by following the Webots tutorials, there is one specific for controller which explains exactly what you are trying to do and is available in c++: https://cyberbotics.com/doc/guide/tutorial-4-more-about-controllers?tab-language=c++

There is one tutorial for building your own robot too: https://cyberbotics.com/doc/guide/tutorial-6-4-wheels-robot?tab-language=c++

In any case, I would recommend following at least tutorials 1 to 6 to get familiar with Webots.


问:
cannot implicitly convert type 'system.net.http.httpresponsemessage' to 'system.web.httpresponse'
I am creating a web service in visual studio 2015 using MySQL databases. I want implement only a GET method using HTTP. Now when I am doing it I cam accross and error. Which is

cannot implicitly convert type 'system.net.http.httpresponsemessage' to 'system.web.httpresponse'

The point where it comes is below

```<code>public HttpResponse Get()
    {
        try
        {
            return  Request.CreateResponse(HttpStatusCode.Found, mEntities.meters_info_dev.ToList());
        }
        catch (Exception)
        {
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No Data found");
        }
    }
</code>```

Below is the image

I couldn't find the solution for it. Any help would be highly appreciated

答:
Directly it will not take the implicit conversion as expected But we can use HttpResponseMessage/HttpWebResponse type function to avoid the above issue. I have mentioned some sample code, it may help you.</p>

```<code>[HttpPost]
        [Route("AddorUpdatePersonalInfo")]
        public async Task<HttpResponseMessage> AddorUpdatePersonalInfo([FromBody]PersonalInfo personalinfo)
        {
            try
            {
                var result = await this._Personalinforepository.AddorUpdatePersonalInfo(personalinfo);
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, result);
                return response;
            }
            catch(Exception ex)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
            }
        }
</code>```

Body:
I am creating a web service in visual studio 2015 using MySQL databases. I want implement only a GET method using HTTP. Now when I am doing it I cam accross and error. Which is

cannot implicitly convert type 'system.net.http.httpresponsemessage' to 'system.web.httpresponse'

The point where it comes is below

public HttpResponse Get()
    {
        try
        {
            return  Request.CreateResponse(HttpStatusCode.Found, mEntities.meters_info_dev.ToList());
        }
        catch (Exception)
        {
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No Data found");
        }
    }

Below is the image

I couldn't find the solution for it. Any help would be highly appreciated

Body:
Directly it will not take the implicit conversion as expected But we can use HttpResponseMessage/HttpWebResponse type function to avoid the above issue. I have mentioned some sample code, it may help you.

[HttpPost]
        [Route("AddorUpdatePersonalInfo")]
        public async Task<HttpResponseMessage> AddorUpdatePersonalInfo([FromBody]PersonalInfo personalinfo)
        {
            try
            {
                var result = await this._Personalinforepository.AddorUpdatePersonalInfo(personalinfo);
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, result);
                return response;
            }
            catch(Exception ex)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
            }
        }


问:
How to use a single variable which can have multiple data types in C++
How can a variable have 2 data types? If "month" is a variable and it should be take from input with std::cin. What should I do so that the user can enter a string like "January" or enter an integer like 1?</p>

答:
How can a variable have 2 data types?

It cannot. An object has one type. A single type can represent values of different types (unions,std::variant). However, you do not need it here. Whether the user enters 1 or "January" shouldn't matter, because it is both the same month.

What should I do so that the user can enter a string like "January" or enter an integer like 1?

When you read user input, read it as a std::string. Internally you can use an enum:

```<code>#include <iostream>
#include <string>

enum class month { January, February, Mazember};

std::istream& operator>>(std::istream& in, month& m){
    std::string temp;
    in >> temp;
    if (temp == "1" || temp == "January") {
        m = month::January;
    }
    //...
    return in;
}

std::ostream& operator<<(std::ostream& out,const month& m) {
    if (m == month::January) {
        out << "January";
    }
    //...
    return out;
}

int main()
{
    month m;
    std::cin >> m;
    std::cout << m;
}
</code>```

Body:
How can a variable have 2 data types?

It cannot. An object has one type. A single type can represent values of different types (unions,std::variant). However, you do not need it here. Whether the user enters 1 or "January" shouldn't matter, because it is both the same month.

What should I do so that the user can enter a string like "January" or enter an integer like 1?

When you read user input, read it as a std::string. Internally you can use an enum:

#include <iostream>
#include <string>

enum class month { January, February, Mazember};

std::istream& operator>>(std::istream& in, month& m){
    std::string temp;
    in >> temp;
    if (temp == "1" || temp == "January") {
        m = month::January;
    }
    //...
    return in;
}

std::ostream& operator<<(std::ostream& out,const month& m) {
    if (m == month::January) {
        out << "January";
    }
    //...
    return out;
}

int main()
{
    month m;
    std::cin >> m;
    std::cout << m;
}


问:
Singleton service visible from the classes
I have a singleton service class

```<code>    public class Globals
    {

        public string serverURL { get; set; } = "";
        public string hostURL { get; set; } = "";
    }
</code>```

and I have registered it in the Main function:

```<code>builder.Services.AddSingleton<Services.Globals>();
</code>```

anyway I would like to access it from the rest of the Classes in the project, not only the razor pages.
For instance I have a class inside a PCL library:

```<code>public class MyStuff
{

    public MyStuff()
    {
       - How do I access Globals in here?!
    }

    public void MyStuffMethod()
    {
       - How do I access Globals in here?!
    }
}
</code>```

How to access a Singleton object from the rest classes in the project ?

答:
Access like this, you just need to add a parameter in constructor of class.</p>

```<code>public class HomeController : Controller
    {
        private Globals _globals;
        public HomeController(Globals globals)
        {
            _globals = globals;
        }
}
</code>```

Body:
I have a singleton service class

    public class Globals
    {

        public string serverURL { get; set; } = "";
        public string hostURL { get; set; } = "";
    }

and I have registered it in the Main function:

builder.Services.AddSingleton<Services.Globals>();

anyway I would like to access it from the rest of the Classes in the project, not only the razor pages.
For instance I have a class inside a PCL library:

public class MyStuff
{

    public MyStuff()
    {
       - How do I access Globals in here?!
    }

    public void MyStuffMethod()
    {
       - How do I access Globals in here?!
    }
}

How to access a Singleton object from the rest classes in the project ?

Body:
Access like this, you just need to add a parameter in constructor of class.

public class HomeController : Controller
    {
        private Globals _globals;
        public HomeController(Globals globals)
        {
            _globals = globals;
        }
}


问:
Omxplayer cuts off roughly the last second of sound
I am using Omxplayer to play a sound file stored as .MP3

The issue I am facing is that on sound files with duration > 1 second, but < 10 appear to have the end (roughly a second) of the file cut off abruptly as if the track had finished.

I am unsure what could be causing this issue as Omxplayer throws no errors and just cuts out to its usual "Have a nice day"

This is on Raspbian on Pi.

答:
Workaround I ended up using was to convert my .mp3 files to .wav, and that stopped them from being cut off. The conversion was easy enough, and it might help down the line since .wav seems to be more acceptable for a variety of tools, e.g. aplay.

I looped through each of them and used the tool lame to convert

```<code>sudo apt-get install lame
lame --decode /path/to/file.mp3 /new/path/to/file.wav
</code>```

Since I happened to be having this problem in Node, I'll share that full solution to convert all .mp3 files in a directory to .wav in a loop. This assumes you have a folder full of only mp3 files, and doesn't check to enforce that:

```<code>const fs = require("fs");
const { exec } = require("child_process");

const files = fs.readdirSync("./audio_mp3/");

files.forEach((file) => {
  let newFile = file.replace('.mp3', '.wav')
  exec(`lame --decode ./audio_mp3/${file} ./audio_wav/${newFile}`);
  console.log(`Created ${newFile} in folder ./audio_wav/`);
})
</code>```

Body:
Workaround I ended up using was to convert my .mp3 files to .wav, and that stopped them from being cut off. The conversion was easy enough, and it might help down the line since .wav seems to be more acceptable for a variety of tools, e.g. aplay.

I looped through each of them and used the tool lame to convert

sudo apt-get install lame
lame --decode /path/to/file.mp3 /new/path/to/file.wav

Since I happened to be having this problem in Node, I'll share that full solution to convert all .mp3 files in a directory to .wav in a loop. This assumes you have a folder full of only mp3 files, and doesn't check to enforce that:

const fs = require("fs");
const { exec } = require("child_process");

const files = fs.readdirSync("./audio_mp3/");

files.forEach((file) => {
  let newFile = file.replace('.mp3', '.wav')
  exec(`lame --decode ./audio_mp3/${file} ./audio_wav/${newFile}`);
  console.log(`Created ${newFile} in folder ./audio_wav/`);
})


问:
How to "disable" CSS grid responsively?
On mobile screens, I'd like to have two buttons laid out in a 3-column grid like that:

.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-column-gap: 30px;
}

.long-grid-item {
  grid-column: 1/3;
}

.short-grid-item {
  grid-column: 3/4;
}

button {
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div class="long-grid-item">
    <button>Long</button>
  </div>
  <div class="short-grid-item">
    <button>Short</button>
  </div>
</div></code>```

However, on desktop screens, I'd like to "disable" the grid and have the buttons have a fixed width: 200px for the long button and 100px for the short one.

Is it possible to keep this HTML structure and just "disable" the grid functionality using media queries?

答:
Set fix width of 100px for the column for devices width above 992px (or your desire width) with media query. I hope I understand your problem.

.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-column-gap: 30px;
}

.long-grid-item {
  grid-column: 1/3;
}

.short-grid-item {
  grid-column: 3/4;
}

button {
  width: 100%;
}

@media screen and (min-width: 992px) {
  .grid {
    grid-template-columns: repeat(3, 100px);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div class="long-grid-item">
    <button>Long</button>
  </div>
  <div class="short-grid-item">
    <button>Short</button>
  </div>
</div></code>```

Title: How to "disable" CSS grid responsively?

Body:
On mobile screens, I'd like to have two buttons laid out in a 3-column grid like that:

.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-column-gap: 30px;
}

.long-grid-item {
  grid-column: 1/3;
}

.short-grid-item {
  grid-column: 3/4;
}

button {
  width: 100%;
}

    <button>Long</button>

    <button>Short</button>

However, on desktop screens, I'd like to "disable" the grid and have the buttons have a fixed width: 200px for the long button and 100px for the short one.

Is it possible to keep this HTML structure and just "disable" the grid functionality using media queries?

Body:
Set fix width of 100px for the column for devices width above 992px (or your desire width) with media query. I hope I understand your problem.

.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-column-gap: 30px;
}

.long-grid-item {
  grid-column: 1/3;
}

.short-grid-item {
  grid-column: 3/4;
}

button {
  width: 100%;
}

@media screen and (min-width: 992px) {
  .grid {
    grid-template-columns: repeat(3, 100px);
  }
}

<div class="grid">
  <div class="long-grid-item">
    <button>Long</button>
  </div>
  <div class="short-grid-item">
    <button>Short</button>
  </div>
</div>


问:
How can I get a list of all pull requests for a repo through the github API?
I want to obtain a list of all pull requests on a repo through the github API.

I've followed the instructions at http://developer.github.com/v3/pulls/ but when I query /repos/:owner/:repo/pulls it's consistently returning fewer pull requests than displayed on the website.

For example, when I query the torvalds/linux repo I get 9 open pull requests (there are 14 on the website). If I add ?state=closed I get a different set of 11 closed pull requests (the website shows around 20).

Does anyone know where this discrepancy arises, and if there's any way to get a complete list of pull requests for a repo through the API?

答:
With Github's new official CLI (command line interface):

```<code>gh pr list --repo OWNER/REPO
</code>```

which would produce something like:

```<code>Showing 2 of 2 pull requests in OWNER/REPO

#62  Doing something    that-weird-branch-name
#58  My PR title        wasnt-inspired-branch
</code>```

See additional details and options and installation instructions.

Body:
With Github's new official CLI (command line interface):

gh pr list --repo OWNER/REPO

which would produce something like:

Showing 2 of 2 pull requests in OWNER/REPO

#62  Doing something    that-weird-branch-name
#58  My PR title        wasnt-inspired-branch

See additional details and options and installation instructions.