问:
exiv2 UserComment metatag
What is the difference between the following statements for setting a comment string

```<code>exiv2 -c tera img.JPG
exiv2 -M"set Exif.Photo.UserComment adagio" img.JPG
</code>```

I can access them with

```<code>$ exiv2 -p c img.JPG
tera
$ exiv2 -p S img.JPG | grep adagio
         450 | 0x9286 UserComment                  | UNDEFINED |       14 |     38546 | ........adagio
</code>```

What would be the proper way to add simple ASCII characters that won't longer than a dozen of characters.

答:
The first command saves the text to the jpeg COM block (see Jpeg Syntax and structure).  This is a jpeg only piece of metadata.

The second command saves the text to the EXIF UserComment tag.  This is part of the EXIF standard of metadata.

The jpeg COM comment is a fairly fragile place to put metadata, as some programs will either not save it or overwrite it with their own text.  The UserComment is less likely to be lost or overwritten by most programs.

Title: exiv2 UserComment metatag

Body:
What is the difference between the following statements for setting a comment string

exiv2 -c tera img.JPG
exiv2 -M"set Exif.Photo.UserComment adagio" img.JPG

I can access them with

$ exiv2 -p c img.JPG
tera
$ exiv2 -p S img.JPG | grep adagio
         450 | 0x9286 UserComment                  | UNDEFINED |       14 |     38546 | ........adagio

What would be the proper way to add simple ASCII characters that won't longer than a dozen of characters.


来源: stackexchange

问:
sbt always recompiles full project in CI, even with caching?
I'm struggling to use SBT for a CI process with this basic workflow:

compile tests

cache ~/.sbt and ~/.ivy2/cache

cache all target directories in my project

In a subsequent step:

restore ~/.sbt and ~/.ivy2/cache

restore full project, including previously-generated target directories with contained .class files and identical source code (it should be the same checkout)

run tests via sbt test

100% of the time, sbt test recompiles the full project. I'd like to understand or debug why that's the case, given nothing has changed since the last compilation (well, nothing should have changed, so what's causing it to believe something has?)

I'm currently using circleci with a docker executor. This means there is a new docker instance, from the same image, running each step, though I would expect caching to address this.

Relevant sections of .circleci/config.yml (if you don't use circle, this should still be grok-able; I've annotated what I can):

---
version: 2

jobs:
  # compile and cache compilation
  test-compile:
    working_directory: /home/circleci/myteam/myproj
    docker:
      - image: myorg/myimage:sbt-1.2.8
    steps:
      # the directory to be persisted (cached/restored) to the next step
      - attach_workspace:
          at: /home/circleci/myteam
      # git pull to /home/circleci/myteam/myproj
      - checkout
      - restore_cache:
          # look for a pre-existing set of ~/.ivy2/cache, ~/.sbt dirs
          # from a prior build
          keys:
            - sbt-artifacts-{{ checksum "project/build.properties"}}-{{ checksum "build.sbt" }}-{{ checksum "project/Dependencies.scala" }}-{{ checksum "project/plugins.sbt" }}-{{ .Branch }}
      - restore_cache:
          # look for pre-existing set of 'target' dirs from a prior build
          keys:
            - build-{{ checksum "project/build.properties"}}-{{ checksum "build.sbt" }}-{{ checksum "project/Dependencies.scala" }}-{{ checksum "project/plugins.sbt" }}-{{ .Branch }}
      - run:
          # the compile step
          working_directory: /home/circleci/myteam/myproj
          command: sbt test:compile
      # per: https://www.scala-sbt.org/1.0/docs/Travis-CI-with-sbt.html
      # Cleanup the cached directories to avoid unnecessary cache updates
      - run:
          working_directory: /home/circleci
          command: |
            rm -rf /home/circleci/.ivy2/.sbt.ivy.lock
            find /home/circleci/.ivy2/cache -name "ivydata-*.properties" -print -delete
            find /home/circleci/.sbt -name "*.lock" -print -delete
      - save_cache:
          # cache ~/.ivy2/cache and ~/.sbt for subsequent builds
          key: sbt-artifacts-{{ checksum "project/build.properties"}}-{{ checksum "build.sbt" }}-{{ checksum "project/Dependencies.scala" }}-{{ checksum "project/plugins.sbt" }}-{{ .Branch }}-{{ .Revision }}
          paths:
            - /home/circleci/.ivy2/cache
            - /home/circleci/.sbt
      - save_cache:
          # cache the `target` dirs for subsequenet builds
          key: build-{{ checksum "project/build.properties"}}-{{ checksum "build.sbt" }}-{{ checksum "project/Dependencies.scala" }}-{{ checksum "project/plugins.sbt" }}-{{ .Branch }}-{{ .Revision }}
          paths:
            - /home/circleci/myteam/myproj/target
            - /home/circleci/myteam/myproj/project/target
            - /home/circleci/myteam/myproj/project/project/target
      # in circle, a 'workflow' undergoes several jobs, this first one
      # is 'compile', the next will run the tests (see next 'job' section
      # 'test-run' below).
      # 'persist to workspace' takes any files from this job and ensures
      # they 'come with' the workspace to the next job in the workflow
      - persist_to_workspace:
          root: /home/circleci/myteam
          # bring the git checkout, including all target dirs
          paths:
            - myproj
      - persist_to_workspace:
          root: /home/circleci
          # bring the big stuff
          paths:
            - .ivy2/cache
            - .sbt

  # actually runs the tests compiled in the previous job
  test-run:
    environment:
      SBT_OPTS: -XX:+UseConcMarkSweepGC -XX:+UnlockDiagnosticVMOptions  -XX:+UnlockExperimentalVMOptions -XX:+UseCGroupMemoryLimitForHeap -Duser.timezone=Etc/UTC -Duser.language=en -Duser.country=US
    docker:
      # run tests in the same image as before, but technically
      # a different instance
      - image: myorg/myimage:sbt-1.2.8
    steps:
      # bring over all files 'persist_to_workspace' in the last job
      - attach_workspace:
          at: /home/circleci/myteam
      # restore ~/.sbt and ~/.ivy2/cache via `mv` from the workspace
      # back to the home dir
      - run:
          working_directory: /home/circleci/myteam
          command: |
            [[ ! -d /home/circleci/.ivy2 ]] && mkdir /home/circleci/.ivy2

            for d in .ivy2/cache .sbt; do
              [[ -d "/home/circleci/$d" ]] && rm -rf "/home/circleci/$d"
              if [ -d "$d"  ]; then
                mv -v "$d" "/home/circleci/$d"
              else
                echo "$d does not exist" >&2
                ls -la . >&2
                exit 1
              fi
            done
      - run:
          # run the tests, already compiled
          # note: recompiles everything every time!
          working_directory: /home/circleci/myteam/myproj
          command: sbt test
          no_output_timeout: 3900s

workflows:
  version: 2
  build-and-test:
    jobs:
      - test-compile
      - test-run:
          requires:
            - test-compile
```

<p>Output from the second phase typically looks like:</p>

```#!/bin/bash -eo pipefail
sbt test

[info] Loading settings for project myproj-build from native-packager.sbt,plugins.sbt ...
[info] Loading project definition from /home/circleci/myorg/myproj/project
[info] Updating ProjectRef(uri("file:/home/circleci/myorg/myproj/project/"), "myproj-build")...
[info] Done updating.
[warn] There may be incompatibilities among your library dependencies; run 'evicted' to see detailed eviction warnings.
[info] Compiling 1 Scala source to /home/circleci/myorg/myproj/project/target/scala-2.12/sbt-1.0/classes ...
[info] Done compiling.
[info] Loading settings for project root from build.sbt ...
[info] Set current project to Piranha (in build file:/home/circleci/myorg/myproj/)
[info] Compiling 1026 Scala sources to /home/circleci/myorg/myproj/target/scala-2.12/classes ...
```

What can I do to determine why this is re-compiling all sources this second time and alleviate it?

I'm running sbt 1.2.8 with scala 2.12.8 in a linux container.

Update

I haven't solved the problem but I figured I'd share a workaround for the worst of my problem.

Primary problem: separate 'test compile' with 'test run'
Secondary problem: faster builds without having to recompile everything on every push

I have no solution to the secondary. For the primary:

I can run the scalatest runner from the CLI via scala -cp ... org.scalatest.tools.Runner rather than via sbt test to avoid any attempt at recompilation. The runner can operate against a directory of .class files.

Summary of changes:

Update the docker container to include a scala cli install. (Unfortunate as I now need to keep these versions in sync)

build phase: sbt test:compile 'inspect run' 'export test:fullClasspath' | tee >(grep -F '.jar' > ~test-classpath.txt)

compiles but also records a copy-patseable classpath string, suitable for passing into scala -cp VALUE_HERE to run tests

test phase: scala -cp "$(cat test-classpath.txt)" org.scalatest.tools.Runner -R target/scala-2.12/test-classes/ -u target/test-reports -oD

runs scalatest via the runner, using compiled .class files in target/scala-2.12/test-classes, using the classpath reported on in the compile phase, and printint to stdout as well as a reports directory

I don't love this and it has some problems, but figured I'd share this workaround.

答:
I have the same problem. I gave up trying to get all the timestamps to match up and eventually found that I could use:

```<code>sbt 'set  Compile / compile / skip := true' 'test'
</code>```

It still isn't perfect, sourceGenerators and probably some other things may still run but it is certainly a lot better than without it.

ContentLicense: CC BY-SA 4.0

Body:
I'm struggling to use SBT for a CI process with this basic workflow:

compile tests

cache ~/.sbt and ~/.ivy2/cache

cache all target directories in my project

In a subsequent step:

restore ~/.sbt and ~/.ivy2/cache

restore full project, including previously-generated target directories with contained .class files and identical source code (it should be the same checkout)

run tests via sbt test

100% of the time, sbt test recompiles the full project. I'd like to understand or debug why that's the case, given nothing has changed since the last compilation (well, nothing should have changed, so what's causing it to believe something has?)

I'm currently using circleci with a docker executor. This means there is a new docker instance, from the same image, running each step, though I would expect caching to address this.

Relevant sections of .circleci/config.yml (if you don't use circle, this should still be grok-able; I've annotated what I can):

---
version: 2

jobs:
  # compile and cache compilation
  test-compile:
    working_directory: /home/circleci/myteam/myproj
    docker:
      - image: myorg/myimage:sbt-1.2.8
    steps:
      # the directory to be persisted (cached/restored) to the next step
      - attach_workspace:
          at: /home/circleci/myteam
      # git pull to /home/circleci/myteam/myproj
      - checkout
      - restore_cache:
          # look for a pre-existing set of ~/.ivy2/cache, ~/.sbt dirs
          # from a prior build
          keys:
            - sbt-artifacts-{{ checksum "project/build.properties"}}-{{ checksum "build.sbt" }}-{{ checksum "project/Dependencies.scala" }}-{{ checksum "project/plugins.sbt" }}-{{ .Branch }}
      - restore_cache:
          # look for pre-existing set of 'target' dirs from a prior build
          keys:
            - build-{{ checksum "project/build.properties"}}-{{ checksum "build.sbt" }}-{{ checksum "project/Dependencies.scala" }}-{{ checksum "project/plugins.sbt" }}-{{ .Branch }}
      - run:
          # the compile step
          working_directory: /home/circleci/myteam/myproj
          command: sbt test:compile
      # per: https://www.scala-sbt.org/1.0/docs/Travis-CI-with-sbt.html
      # Cleanup the cached directories to avoid unnecessary cache updates
      - run:
          working_directory: /home/circleci
          command: |
            rm -rf /home/circleci/.ivy2/.sbt.ivy.lock
            find /home/circleci/.ivy2/cache -name "ivydata-*.properties" -print -delete
            find /home/circleci/.sbt -name "*.lock" -print -delete
      - save_cache:
          # cache ~/.ivy2/cache and ~/.sbt for subsequent builds
          key: sbt-artifacts-{{ checksum "project/build.properties"}}-{{ checksum "build.sbt" }}-{{ checksum "project/Dependencies.scala" }}-{{ checksum "project/plugins.sbt" }}-{{ .Branch }}-{{ .Revision }}
          paths:
            - /home/circleci/.ivy2/cache
            - /home/circleci/.sbt
      - save_cache:
          # cache the `target` dirs for subsequenet builds
          key: build-{{ checksum "project/build.properties"}}-{{ checksum "build.sbt" }}-{{ checksum "project/Dependencies.scala" }}-{{ checksum "project/plugins.sbt" }}-{{ .Branch }}-{{ .Revision }}
          paths:
            - /home/circleci/myteam/myproj/target
            - /home/circleci/myteam/myproj/project/target
            - /home/circleci/myteam/myproj/project/project/target
      # in circle, a 'workflow' undergoes several jobs, this first one
      # is 'compile', the next will run the tests (see next 'job' section
      # 'test-run' below).
      # 'persist to workspace' takes any files from this job and ensures
      # they 'come with' the workspace to the next job in the workflow
      - persist_to_workspace:
          root: /home/circleci/myteam
          # bring the git checkout, including all target dirs
          paths:
            - myproj
      - persist_to_workspace:
          root: /home/circleci
          # bring the big stuff
          paths:
            - .ivy2/cache
            - .sbt

  # actually runs the tests compiled in the previous job
  test-run:
    environment:
      SBT_OPTS: -XX:+UseConcMarkSweepGC -XX:+UnlockDiagnosticVMOptions  -XX:+UnlockExperimentalVMOptions -XX:+UseCGroupMemoryLimitForHeap -Duser.timezone=Etc/UTC -Duser.language=en -Duser.country=US
    docker:
      # run tests in the same image as before, but technically
      # a different instance
      - image: myorg/myimage:sbt-1.2.8
    steps:
      # bring over all files 'persist_to_workspace' in the last job
      - attach_workspace:
          at: /home/circleci/myteam
      # restore ~/.sbt and ~/.ivy2/cache via `mv` from the workspace
      # back to the home dir
      - run:
          working_directory: /home/circleci/myteam
          command: |
            [[ ! -d /home/circleci/.ivy2 ]] && mkdir /home/circleci/.ivy2

            for d in .ivy2/cache .sbt; do
              [[ -d "/home/circleci/$d" ]] && rm -rf "/home/circleci/$d"
              if [ -d "$d"  ]; then
                mv -v "$d" "/home/circleci/$d"
              else
                echo "$d does not exist" >&2
                ls -la . >&2
                exit 1
              fi
            done
      - run:
          # run the tests, already compiled
          # note: recompiles everything every time!
          working_directory: /home/circleci/myteam/myproj
          command: sbt test
          no_output_timeout: 3900s

workflows:
  version: 2
  build-and-test:
    jobs:
      - test-compile
      - test-run:
          requires:
            - test-compile

Output from the second phase typically looks like:

#!/bin/bash -eo pipefail
sbt test

[info] Loading settings for project myproj-build from native-packager.sbt,plugins.sbt ...
[info] Loading project definition from /home/circleci/myorg/myproj/project
[info] Updating ProjectRef(uri("file:/home/circleci/myorg/myproj/project/"), "myproj-build")...
[info] Done updating.
[warn] There may be incompatibilities among your library dependencies; run 'evicted' to see detailed eviction warnings.
[info] Compiling 1 Scala source to /home/circleci/myorg/myproj/project/target/scala-2.12/sbt-1.0/classes ...
[info] Done compiling.
[info] Loading settings for project root from build.sbt ...
[info] Set current project to Piranha (in build file:/home/circleci/myorg/myproj/)
[info] Compiling 1026 Scala sources to /home/circleci/myorg/myproj/target/scala-2.12/classes ...

What can I do to determine why this is re-compiling all sources this second time and alleviate it?

I'm running sbt 1.2.8 with scala 2.12.8 in a linux container.

Update

I haven't solved the problem but I figured I'd share a workaround for the worst of my problem.

Primary problem: separate 'test compile' with 'test run'
Secondary problem: faster builds without having to recompile everything on every push

I have no solution to the secondary. For the primary:

I can run the scalatest runner from the CLI via scala -cp ... org.scalatest.tools.Runner rather than via sbt test to avoid any attempt at recompilation. The runner can operate against a directory of .class files.

Summary of changes:

Update the docker container to include a scala cli install. (Unfortunate as I now need to keep these versions in sync)

build phase: sbt test:compile 'inspect run' 'export test:fullClasspath' | tee >(grep -F '.jar' > ~test-classpath.txt)

compiles but also records a copy-patseable classpath string, suitable for passing into scala -cp VALUE_HERE to run tests

test phase: scala -cp "$(cat test-classpath.txt)" org.scalatest.tools.Runner -R target/scala-2.12/test-classes/ -u target/test-reports -oD

runs scalatest via the runner, using compiled .class files in target/scala-2.12/test-classes, using the classpath reported on in the compile phase, and printint to stdout as well as a reports directory

I don't love this and it has some problems, but figured I'd share this workaround.

Body:
I have the same problem. I gave up trying to get all the timestamps to match up and eventually found that I could use:

sbt 'set  Compile / compile / skip := true' 'test'

It still isn't perfect, sourceGenerators and probably some other things may still run but it is certainly a lot better than without it.


问:
How to calculate a list of angles between two line vectors in a series of specimens in R?
I am doing work a geometric morphometric dataset of biological specimens with two dimensional Cartesian coordinates (i.e., landmarks). Part of my interest with this dataset is to produce a data frame of distances between important landmarks and angles between landmark vectors with homologous coordinates across all specimens for further comparison. Distances between points have not been a problem, but I have been running into problems when I have tried to calculate angles in each of my specimens.

I am trying to find a way to calculate the angle between line vectors representing the same angle on a series of specimens at once (the vectors describe a feature with biological significance that is present in all specimens across my dataset). The R package I use to manipulate the morphometric data outputs the landmarks as a three-dimensional object of class array() where rows are landmarks, columns are the dimensions of the coordinate, and the third dimension is the specimen. Here are the landmark coordinates for the three specimens in the sample data presented here.

```<code>, , Specimen1

         X         Y
1  -0.2411  0.060183
2  -0.0677 -0.029954
3   0.1147  0.012111
4   0.0085  0.000462

, , Specimen2

          X       Y
1  -0.22509  0.0764
2  -0.09437 -0.0202
3   0.09135 -0.0182
4   0.00367 -0.0045

, , Specimen3

         X        Y
1  -0.2223  0.06122
2  -0.1001 -0.02366
3   0.0553  0.00577
4  -0.0617 -0.01557
</code>```

Below is a readable array that replicates the data I get as output for the first three specimens.

```<code>data<-array(data=c(-0.2411,-0.0677,0.1147,0.0085,0.060183,-0.029954,0.012111,0.000462,-0.22509,-0.09437,0.09135,0.00367,0.0764,-0.0202,-0.0182,-0.0045,-0.2223,-0.1001,0.0553,-0.0617,0.06122,-0.02366,0.00577,-0.01557),c(4,2,3))
</code>```

I am interested in finding the angle formed by the lines between points 1 and 2 and points 3 and 4. To do this I calculate the vector of these two lines by subtracting the coordinates of one point from the other. When I do that I get a 2*N matrix for each vector where rows correspond to vectors in the X and Y axis and columns correspond to specimen.

I want to find the angle between these two vectors for specimen 1 (column 1 on both matrices), 2, 3, and so on. Ideally, I would like to get the output into a format where R reports the angle for each indivdual specimen, like so:

```<code>     Angle1
[,1] 146
[,2] 152
[,3] 135
</code>```

And then somehow add it into a data frame so it looks like this:

```<code>          Distance Angle1 Angle2
Specimen1 100      146    100
Specimen2 100      152    100
Specimen3 100      135    100
</code>```

The distances and values for Angle2 are just filler numbers to show the format I am trying to achieve.

I have tried using the angle() function in the mathlib package and the angle.calc() function in the Morpho package. Here is the code I used to calculate the angle using the angle() function.

```<code>vector1<-data[1,,]-data[2,,]
vector2<-data[3,,]-data[4,,]
angle(as.vector(vector1),as.vector(vector2),degree=TRUE)
</code>```

These functions will calculate what seems to be the accurate angle however they will only do it for the first specimen or a single specimen if otherwise specified, and do not produce a list of angles for all specimens. I have also checked previous questions on Stack Overflow but none of the answers given appear to be applicable to a dataset containing multiple specimens  with each column on both matrices representing a distinct specimen (and when I apply them at best they seem to have the same problem where they only return the angle for the first specimen). There are only three specimens here, I have a large number of specimens and multiple angles per specimen in the actual dataset and it is not possible to measure every angle individually for each specimen.

Is there any way to write a formula to produce a list containing the respective angle for each of these specimens?

答:
In general you may find it simpler to first get your data in a long/tidy format.  That allows for easier grouping and aggregation, which is where vectorized/mapped operations can really shine.

Here's one way to do that with the data you provided:

```<code>library(matlib)
library(tidyverse)

n_specimen <- ncol(vector1)

data.frame(t(vector1)) %>%
  rename_all(~str_replace(., "X", "v1_")) %>%
  bind_cols(
    data.frame(t(vector2)) %>%
      rename_all(~str_replace(., "X", "v2_"))
    ) %>%
  mutate(specimen = paste0("Specimen", 1:n_specimen)) %>%
  pivot_longer(-specimen, names_to = "vector", values_to = "value") %>%
  separate(vector, into = c("vector", "ix"), sep = "_", remove = TRUE) %>%
  group_by(specimen) %>%
  summarise(angle = angle(value[vector == "v1"], value[vector == "v2"]))

  specimen  angle
  <chr>     <dbl>
1 Specimen1  146.
2 Specimen2  152.
3 Specimen3  135.
</code>```

By way of explanation, here's how the data frame looks after the separate step:

```<code># A tibble: 12 x 4
   specimen  vector ix      value
   <chr>     <chr>  <chr>   <dbl>
 1 Specimen1 v1     1     -0.173
 2 Specimen1 v1     2      0.0901
 3 Specimen1 v2     1      0.106
 4 Specimen1 v2     2      0.0116
 5 Specimen2 v1     1     -0.131
 6 Specimen2 v1     2      0.0966
 7 Specimen2 v2     1      0.0877
 8 Specimen2 v2     2     -0.0137
 9 Specimen3 v1     1     -0.122
10 Specimen3 v1     2      0.0849
11 Specimen3 v2     1      0.117
12 Specimen3 v2     2      0.0213
</code>```

Each column has a unique level of information, and you can now group and summarise to the level of specificity required.

Body:
I am doing work a geometric morphometric dataset of biological specimens with two dimensional Cartesian coordinates (i.e., landmarks). Part of my interest with this dataset is to produce a data frame of distances between important landmarks and angles between landmark vectors with homologous coordinates across all specimens for further comparison. Distances between points have not been a problem, but I have been running into problems when I have tried to calculate angles in each of my specimens.

I am trying to find a way to calculate the angle between line vectors representing the same angle on a series of specimens at once (the vectors describe a feature with biological significance that is present in all specimens across my dataset). The R package I use to manipulate the morphometric data outputs the landmarks as a three-dimensional object of class array() where rows are landmarks, columns are the dimensions of the coordinate, and the third dimension is the specimen. Here are the landmark coordinates for the three specimens in the sample data presented here.

, , Specimen1

         X         Y
1  -0.2411  0.060183
2  -0.0677 -0.029954
3   0.1147  0.012111
4   0.0085  0.000462

, , Specimen2

          X       Y
1  -0.22509  0.0764
2  -0.09437 -0.0202
3   0.09135 -0.0182
4   0.00367 -0.0045

, , Specimen3

         X        Y
1  -0.2223  0.06122
2  -0.1001 -0.02366
3   0.0553  0.00577
4  -0.0617 -0.01557

Below is a readable array that replicates the data I get as output for the first three specimens.

data<-array(data=c(-0.2411,-0.0677,0.1147,0.0085,0.060183,-0.029954,0.012111,0.000462,-0.22509,-0.09437,0.09135,0.00367,0.0764,-0.0202,-0.0182,-0.0045,-0.2223,-0.1001,0.0553,-0.0617,0.06122,-0.02366,0.00577,-0.01557),c(4,2,3))

I am interested in finding the angle formed by the lines between points 1 and 2 and points 3 and 4. To do this I calculate the vector of these two lines by subtracting the coordinates of one point from the other. When I do that I get a 2*N matrix for each vector where rows correspond to vectors in the X and Y axis and columns correspond to specimen.

I want to find the angle between these two vectors for specimen 1 (column 1 on both matrices), 2, 3, and so on. Ideally, I would like to get the output into a format where R reports the angle for each indivdual specimen, like so:

     Angle1
[,1] 146
[,2] 152
[,3] 135

And then somehow add it into a data frame so it looks like this:

          Distance Angle1 Angle2
Specimen1 100      146    100
Specimen2 100      152    100
Specimen3 100      135    100

The distances and values for Angle2 are just filler numbers to show the format I am trying to achieve.

I have tried using the angle() function in the mathlib package and the angle.calc() function in the Morpho package. Here is the code I used to calculate the angle using the angle() function.

vector1<-data[1,,]-data[2,,]
vector2<-data[3,,]-data[4,,]
angle(as.vector(vector1),as.vector(vector2),degree=TRUE)

These functions will calculate what seems to be the accurate angle however they will only do it for the first specimen or a single specimen if otherwise specified, and do not produce a list of angles for all specimens. I have also checked previous questions on Stack Overflow but none of the answers given appear to be applicable to a dataset containing multiple specimens  with each column on both matrices representing a distinct specimen (and when I apply them at best they seem to have the same problem where they only return the angle for the first specimen). There are only three specimens here, I have a large number of specimens and multiple angles per specimen in the actual dataset and it is not possible to measure every angle individually for each specimen.

Is there any way to write a formula to produce a list containing the respective angle for each of these specimens?

Body:
In general you may find it simpler to first get your data in a long/tidy format.  That allows for easier grouping and aggregation, which is where vectorized/mapped operations can really shine.

Here's one way to do that with the data you provided:

library(matlib)
library(tidyverse)

n_specimen <- ncol(vector1)

data.frame(t(vector1)) %>%
  rename_all(~str_replace(., "X", "v1_")) %>%
  bind_cols(
    data.frame(t(vector2)) %>%
      rename_all(~str_replace(., "X", "v2_"))
    ) %>%
  mutate(specimen = paste0("Specimen", 1:n_specimen)) %>%
  pivot_longer(-specimen, names_to = "vector", values_to = "value") %>%
  separate(vector, into = c("vector", "ix"), sep = "_", remove = TRUE) %>%
  group_by(specimen) %>%
  summarise(angle = angle(value[vector == "v1"], value[vector == "v2"]))

  specimen  angle
  <chr>     <dbl>
1 Specimen1  146.
2 Specimen2  152.
3 Specimen3  135.

By way of explanation, here's how the data frame looks after the separate step:

# A tibble: 12 x 4
   specimen  vector ix      value
   <chr>     <chr>  <chr>   <dbl>
 1 Specimen1 v1     1     -0.173
 2 Specimen1 v1     2      0.0901
 3 Specimen1 v2     1      0.106
 4 Specimen1 v2     2      0.0116
 5 Specimen2 v1     1     -0.131
 6 Specimen2 v1     2      0.0966
 7 Specimen2 v2     1      0.0877
 8 Specimen2 v2     2     -0.0137
 9 Specimen3 v1     1     -0.122
10 Specimen3 v1     2      0.0849
11 Specimen3 v2     1      0.117
12 Specimen3 v2     2      0.0213

Each column has a unique level of information, and you can now group and summarise to the level of specificity required.


问:
How to login as root user to Oracle's rman
I am trying to login rman as the root user:

rman target /

Recovery Manager: Release 19.0.0.0.0 - Production on Wed Jan 8 21:40:47 2020
Version 19.3.0.0.0

Copyright (c) 1982, 2019, Oracle and/or its affiliates.  All rights reserved.

RMAN-00571: ===========================================================
RMAN-00569: =============== ERROR MESSAGE STACK FOLLOWS ===============
RMAN-00571: ===========================================================
RMAN-00554: initialization of internal recovery manager package failed
RMAN-04005: error from target database:
ORA-01017: invalid username/password; logon denied
```

<p>But I get this error.</p>

<p>I can login using the following</p>

<pre class="lang-none prettyprint-override"><code>rman target sys/oracle@orcl
</code>```

But I want to login as a root user. How can I do this?

答:
Step 01: Findout which OS group currently having SYSDBA privilege (This depends on your installation Oracle Software, but usually it is dba OS group).

Step 02: Modify supplementary Group of root to that group (dba in this example).
Optional: modify PATH having $ORACLE_HOME/bin, setting appropriate ORACLE_SID & ORACLE_HOME.

:) good luck

Body:
I am trying to login rman as the root user:

rman target /

Recovery Manager: Release 19.0.0.0.0 - Production on Wed Jan 8 21:40:47 2020
Version 19.3.0.0.0

Copyright (c) 1982, 2019, Oracle and/or its affiliates.  All rights reserved.

RMAN-00571: ===========================================================
RMAN-00569: =============== ERROR MESSAGE STACK FOLLOWS ===============
RMAN-00571: ===========================================================
RMAN-00554: initialization of internal recovery manager package failed
RMAN-04005: error from target database:
ORA-01017: invalid username/password; logon denied

But I get this error.

I can login using the following

rman target sys/oracle@orcl

But I want to login as a root user. How can I do this?


问:
Firebase CLI error in Google Cloud Build step
When I am running the "firebase use" command from the Firebase CLI in a cloudbuild step I get the following error:

```<code>Starting Step #5 - "SetFirebaseEnvironment"
Step #5 - "SetFirebaseEnvironment": Already have image (with digest): eu.gcr.io/BUCKET_NAME/firebase:7.12-0
Step #5 - "SetFirebaseEnvironment": [2020-02-17T13:09:50.806Z] ----------------------------------------------------------------------
Step #5 - "SetFirebaseEnvironment": [2020-02-17T13:09:50.808Z] Command:       /usr/local/bin/node /usr/local/bin/firebase use dev --debug
Step #5 - "SetFirebaseEnvironment": [2020-02-17T13:09:50.808Z] CLI Version:   7.12.1
Step #5 - "SetFirebaseEnvironment": [2020-02-17T13:09:50.808Z] Platform:      linux
Step #5 - "SetFirebaseEnvironment": [2020-02-17T13:09:50.808Z] Node Version:  v13.6.0
Step #5 - "SetFirebaseEnvironment": [2020-02-17T13:09:50.813Z] Time:          Mon Feb 17 2020 13:09:50 GMT+0000 (Coordinated Universal Time)
Step #5 - "SetFirebaseEnvironment": [2020-02-17T13:09:50.813Z] ----------------------------------------------------------------------
Step #5 - "SetFirebaseEnvironment": [2020-02-17T13:09:50.813Z]
Step #5 - "SetFirebaseEnvironment": [2020-02-17T13:09:50.820Z] > command requires scopes: ["email","openid","https://www.googleapis.com/auth/cloudplatformprojects.readonly","https://www.googleapis.com/auth/firebase","https://www.googleapis.com/auth/cloud-platform"]
Step #5 - "SetFirebaseEnvironment": [2020-02-17T13:09:50.820Z] > attempting to authenticate via app default credentials
Step #5 - "SetFirebaseEnvironment": [2020-02-17T13:09:50.854Z] TypeError: Cannot create property 'refresh_token' on string 'Not Found
Step #5 - "SetFirebaseEnvironment": '
Step #5 - "SetFirebaseEnvironment":     at /usr/local/lib/node_modules/firebase-tools/node_modules/google-auto-auth/node_modules/google-auth-library/lib/auth/oauth2client.js:208:28
Step #5 - "SetFirebaseEnvironment":     at /usr/local/lib/node_modules/firebase-tools/node_modules/google-auto-auth/node_modules/google-auth-library/lib/auth/computeclient.js:85:7
Step #5 - "SetFirebaseEnvironment":     at Request._callback (/usr/local/lib/node_modules/firebase-tools/node_modules/google-auto-auth/node_modules/google-auth-library/lib/transporters.js:106:7)
Step #5 - "SetFirebaseEnvironment":     at Request.self.callback (/usr/local/lib/node_modules/firebase-tools/node_modules/request/request.js:185:22)
Step #5 - "SetFirebaseEnvironment":     at Request.emit (events.js:321:20)
Step #5 - "SetFirebaseEnvironment":     at Request.EventEmitter.emit (domain.js:485:12)
Step #5 - "SetFirebaseEnvironment":     at Request.<anonymous> (/usr/local/lib/node_modules/firebase-tools/node_modules/request/request.js:1154:10)
Step #5 - "SetFirebaseEnvironment":     at Request.emit (events.js:321:20)
Step #5 - "SetFirebaseEnvironment":     at Request.EventEmitter.emit (domain.js:485:12)
Step #5 - "SetFirebaseEnvironment":     at IncomingMessage.<anonymous> (/usr/local/lib/node_modules/firebase-tools/node_modules/request/request.js:1076:12)
Step #5 - "SetFirebaseEnvironment":     at Object.onceWrapper (events.js:427:28)
Step #5 - "SetFirebaseEnvironment":     at IncomingMessage.emit (events.js:333:22)
Step #5 - "SetFirebaseEnvironment":     at IncomingMessage.EventEmitter.emit (domain.js:485:12)
Step #5 - "SetFirebaseEnvironment":     at endReadableNT (_stream_readable.js:1220:12)
Step #5 - "SetFirebaseEnvironment":     at processTicksAndRejections (internal/process/task_queues.js:84:21)
Step #5 - "SetFirebaseEnvironment":
Step #5 - "SetFirebaseEnvironment": Error: An unexpected error has occurred.
Finished Step #5 - "SetFirebaseEnvironment"
2020/02/17 14:09:51 Step Step #5 - "SetFirebaseEnvironment" finished
2020/02/17 14:09:51 status changed to "ERROR"
ERROR
ERROR: build step 5 "eu.gcr.io/BUCKET_NAME/firebase:7.12-0" failed: exit status 2
2020/02/17 14:09:54 Build finished with ERROR status
</code>```

When I run the same command on my local machine with exactly the same Firebase CLI version and Node version I dont get this error. Why do I get this error and how do a solve it?

答: It seems as it's fixed now (see comments to original question with links), but generally, the logic to fix such an issue is to try rebuilding firebase docker image used in cloud builder step.</p>

Body:
When I am running the "firebase use" command from the Firebase CLI in a cloudbuild step I get the following error:

Starting Step #5 - "SetFirebaseEnvironment"
Step #5 - "SetFirebaseEnvironment": Already have image (with digest): eu.gcr.io/BUCKET_NAME/firebase:7.12-0
Step #5 - "SetFirebaseEnvironment": [2020-02-17T13:09:50.806Z] ----------------------------------------------------------------------
Step #5 - "SetFirebaseEnvironment": [2020-02-17T13:09:50.808Z] Command:       /usr/local/bin/node /usr/local/bin/firebase use dev --debug
Step #5 - "SetFirebaseEnvironment": [2020-02-17T13:09:50.808Z] CLI Version:   7.12.1
Step #5 - "SetFirebaseEnvironment": [2020-02-17T13:09:50.808Z] Platform:      linux
Step #5 - "SetFirebaseEnvironment": [2020-02-17T13:09:50.808Z] Node Version:  v13.6.0
Step #5 - "SetFirebaseEnvironment": [2020-02-17T13:09:50.813Z] Time:          Mon Feb 17 2020 13:09:50 GMT+0000 (Coordinated Universal Time)
Step #5 - "SetFirebaseEnvironment": [2020-02-17T13:09:50.813Z] ----------------------------------------------------------------------
Step #5 - "SetFirebaseEnvironment": [2020-02-17T13:09:50.813Z]
Step #5 - "SetFirebaseEnvironment": [2020-02-17T13:09:50.820Z] > command requires scopes: ["email","openid","https://www.googleapis.com/auth/cloudplatformprojects.readonly","https://www.googleapis.com/auth/firebase","https://www.googleapis.com/auth/cloud-platform"]
Step #5 - "SetFirebaseEnvironment": [2020-02-17T13:09:50.820Z] > attempting to authenticate via app default credentials
Step #5 - "SetFirebaseEnvironment": [2020-02-17T13:09:50.854Z] TypeError: Cannot create property 'refresh_token' on string 'Not Found
Step #5 - "SetFirebaseEnvironment": '
Step #5 - "SetFirebaseEnvironment":     at /usr/local/lib/node_modules/firebase-tools/node_modules/google-auto-auth/node_modules/google-auth-library/lib/auth/oauth2client.js:208:28
Step #5 - "SetFirebaseEnvironment":     at /usr/local/lib/node_modules/firebase-tools/node_modules/google-auto-auth/node_modules/google-auth-library/lib/auth/computeclient.js:85:7
Step #5 - "SetFirebaseEnvironment":     at Request._callback (/usr/local/lib/node_modules/firebase-tools/node_modules/google-auto-auth/node_modules/google-auth-library/lib/transporters.js:106:7)
Step #5 - "SetFirebaseEnvironment":     at Request.self.callback (/usr/local/lib/node_modules/firebase-tools/node_modules/request/request.js:185:22)
Step #5 - "SetFirebaseEnvironment":     at Request.emit (events.js:321:20)
Step #5 - "SetFirebaseEnvironment":     at Request.EventEmitter.emit (domain.js:485:12)
Step #5 - "SetFirebaseEnvironment":     at Request.<anonymous> (/usr/local/lib/node_modules/firebase-tools/node_modules/request/request.js:1154:10)
Step #5 - "SetFirebaseEnvironment":     at Request.emit (events.js:321:20)
Step #5 - "SetFirebaseEnvironment":     at Request.EventEmitter.emit (domain.js:485:12)
Step #5 - "SetFirebaseEnvironment":     at IncomingMessage.<anonymous> (/usr/local/lib/node_modules/firebase-tools/node_modules/request/request.js:1076:12)
Step #5 - "SetFirebaseEnvironment":     at Object.onceWrapper (events.js:427:28)
Step #5 - "SetFirebaseEnvironment":     at IncomingMessage.emit (events.js:333:22)
Step #5 - "SetFirebaseEnvironment":     at IncomingMessage.EventEmitter.emit (domain.js:485:12)
Step #5 - "SetFirebaseEnvironment":     at endReadableNT (_stream_readable.js:1220:12)
Step #5 - "SetFirebaseEnvironment":     at processTicksAndRejections (internal/process/task_queues.js:84:21)
Step #5 - "SetFirebaseEnvironment":
Step #5 - "SetFirebaseEnvironment": Error: An unexpected error has occurred.
Finished Step #5 - "SetFirebaseEnvironment"
2020/02/17 14:09:51 Step Step #5 - "SetFirebaseEnvironment" finished
2020/02/17 14:09:51 status changed to "ERROR"
ERROR
ERROR: build step 5 "eu.gcr.io/BUCKET_NAME/firebase:7.12-0" failed: exit status 2
2020/02/17 14:09:54 Build finished with ERROR status

When I run the same command on my local machine with exactly the same Firebase CLI version and Node version I dont get this error. Why do I get this error and how do a solve it?


问:
How to build object hierarchy for serialization with json.net?
I'm trying to properly write code to build a data structure to serialize into json.

I'm using json.net.

I don't want to create a bunch of classes to hold this data, as I thought there should be some classes that will already do this in json.net

I've already got all the data I need in a series of nested loops, and now I just want to add them to an object hierarchy before I run JsonConvert.SerializeObject on it.

I've already tried code like this, but it doesn't seem to work

```<code>JArray container = new JArray();

        container.Add(new JObject(new JProperty("name", "Client1"), new JProperty("projects", new JArray())));

        container[0].AddAfterSelf(new JObject(new JProperty("projects", new JArray())));
        container[1].AddAfterSelf(new JObject(new JProperty("projects", "Project2")));
        container[1].AddAfterSelf(new JObject(new JProperty("projects", "Project3")));
        container.Add(new JProperty("name", "Client2"));

        var test = JsonConvert.SerializeObject(container);
</code>```

The problem is that when I use [i]. or ElementAt(i) to access somewhere in the structure, either .Add() is missing or .ElementAt isn't there.
How do I step through the data structure to make this nicely output the below, or do I have to create my own container class for all of this?

This is the data format I am trying to make.

```<code>[
    {
    "name": "student1",
    "projects":
    [
        {
        "name": "Project1",
        "tasks":
                [
                    {
                    "name": "task1",
                    "id": 2
                    }
                ],
        "id": 6
        }
    ]
},
    {
    "name": "Student2",
    "projects": [
                {
                "name": "Project1",
                "tasks": [
                         {
                         "name": "Task2",
                         "id": 1
                         },
                         {
                         "name": "Task3",
                         "id": 3
                         },
                         {
                         "name": "Task4",
                         "id": 4
                         }
                         ],
                "id": 2
</code>```

etc...

答:
I think what you're asking is how to serialize complex business objects in json, but only expose certain properties.

In other words you already have a list of students, but you only want to send very specific data via json. If I'm wrong this answer won't suit your needs.

So assuming you have a list of students, with a projects property that has an inner property of tasks, this is how I do it without having to create loads of new classes, I use anonymous objects.

Once I've created my list of anonymous objects, I simply turn them into a json string.

As pointed out in the comments you don't need to use json.net, this functionality is available in the framework, add a reference to System.Web.Extensions.dll then

using System.Web.Script.Serialization;

```<code>var jsonStudents = new List<object>();

foreach (var student in students)
{
    jsonStudents.Add(new
    {
        student.Id,         //anonymous properties automatically pick up the name of the property you pass them, this will be called Id
        FullName = student.FirstName + " " + student.LastName, //if you want to name a property yourself use this notation
        Projects = student.Projects.Select(p => new //this will be an enumerable of nested anonymous objects, we're partially selecting project properties
        {
            p.Id,
            p.Name,
            Tasks = p.Tasks.Select(t => new //nesting another level
            {
                t.Id,
                t.Name
            })
        })
    });
}

var serializer = new JavaScriptSerializer();

var jsonString = serializer.Serialize(jsonStudents);
</code>```

If you really want to use loops you can do this to allow you to do more complicated things in the creating of the projects and tasks:

```<code>var jsonStudents = new List<object>();

foreach (var student in students)
{
    var tempStudent = new
    {
        student.Id,         //anonymous properties automatically pick up the name of the property you pass them, this will be called Id
        FullName = student.FirstName + " " + student.LastName, //if you want to name a property yourself use this notation
        Projects = new List<object>()
    };

    foreach (var project in student.Projects)
    {
        var tempProject = new {
            project.Id,
            project.Name,
            Tasks = new List<object>()
        };

        foreach (var task in project.Tasks)
        {
            tempProject.Tasks.Add(new {
                task.Id,
                task.Name
            });
        }

        tempStudent.Projects.Add(tempProject);
    }

    jsonStudents.Add(tempStudent);
}

var serializer = new JavaScriptSerializer();

var jsonString = serializer.Serialize(jsonStudents);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to properly write code to build a data structure to serialize into json.

I'm using json.net.

I don't want to create a bunch of classes to hold this data, as I thought there should be some classes that will already do this in json.net

I've already got all the data I need in a series of nested loops, and now I just want to add them to an object hierarchy before I run JsonConvert.SerializeObject on it.

I've already tried code like this, but it doesn't seem to work

JArray container = new JArray();

        container.Add(new JObject(new JProperty("name", "Client1"), new JProperty("projects", new JArray())));

        container[0].AddAfterSelf(new JObject(new JProperty("projects", new JArray())));
        container[1].AddAfterSelf(new JObject(new JProperty("projects", "Project2")));
        container[1].AddAfterSelf(new JObject(new JProperty("projects", "Project3")));
        container.Add(new JProperty("name", "Client2"));

        var test = JsonConvert.SerializeObject(container);

The problem is that when I use [i]. or ElementAt(i) to access somewhere in the structure, either .Add() is missing or .ElementAt isn't there.
How do I step through the data structure to make this nicely output the below, or do I have to create my own container class for all of this?

This is the data format I am trying to make.

[
    {
    "name": "student1",
    "projects":
    [
        {
        "name": "Project1",
        "tasks":
                [
                    {
                    "name": "task1",
                    "id": 2
                    }
                ],
        "id": 6
        }
    ]
},
    {
    "name": "Student2",
    "projects": [
                {
                "name": "Project1",
                "tasks": [
                         {
                         "name": "Task2",
                         "id": 1
                         },
                         {
                         "name": "Task3",
                         "id": 3
                         },
                         {
                         "name": "Task4",
                         "id": 4
                         }
                         ],
                "id": 2

etc...

Body:
I think what you're asking is how to serialize complex business objects in json, but only expose certain properties.

In other words you already have a list of students, but you only want to send very specific data via json. If I'm wrong this answer won't suit your needs.

So assuming you have a list of students, with a projects property that has an inner property of tasks, this is how I do it without having to create loads of new classes, I use anonymous objects.

Once I've created my list of anonymous objects, I simply turn them into a json string.

As pointed out in the comments you don't need to use json.net, this functionality is available in the framework, add a reference to System.Web.Extensions.dll then

using System.Web.Script.Serialization;

var jsonStudents = new List<object>();

foreach (var student in students)
{
    jsonStudents.Add(new
    {
        student.Id,         //anonymous properties automatically pick up the name of the property you pass them, this will be called Id
        FullName = student.FirstName + " " + student.LastName, //if you want to name a property yourself use this notation
        Projects = student.Projects.Select(p => new //this will be an enumerable of nested anonymous objects, we're partially selecting project properties
        {
            p.Id,
            p.Name,
            Tasks = p.Tasks.Select(t => new //nesting another level
            {
                t.Id,
                t.Name
            })
        })
    });
}

var serializer = new JavaScriptSerializer();

var jsonString = serializer.Serialize(jsonStudents);

If you really want to use loops you can do this to allow you to do more complicated things in the creating of the projects and tasks:

var jsonStudents = new List<object>();

foreach (var student in students)
{
    var tempStudent = new
    {
        student.Id,         //anonymous properties automatically pick up the name of the property you pass them, this will be called Id
        FullName = student.FirstName + " " + student.LastName, //if you want to name a property yourself use this notation
        Projects = new List<object>()
    };

    foreach (var project in student.Projects)
    {
        var tempProject = new {
            project.Id,
            project.Name,
            Tasks = new List<object>()
        };

        foreach (var task in project.Tasks)
        {
            tempProject.Tasks.Add(new {
                task.Id,
                task.Name
            });
        }

        tempStudent.Projects.Add(tempProject);
    }

    jsonStudents.Add(tempStudent);
}

var serializer = new JavaScriptSerializer();

var jsonString = serializer.Serialize(jsonStudents);


问:
Javascript count same array of object values based on two values
Let's say we have an array of object like this

```<code>const studentRecord = [
 {
   name: 'John Doe',
   gender: 'Male',
   grade: '85'
 },{
   name: 'Steve Doe',
   gender: 'Male',
   grade: '85'
 },{
   name: 'Jane Doe',
   gender: 'Male',
   grade: '90'
 },{
   name: 'Mary Jane',
   gender: 'Female',
   grade: '85'
 },
]
</code>```

I would like to count all students that are male that have the same grade and female students with the same grade something like this would be the output...

```<code> 85: {
       Male: 2,
       Female: 1,
     }
 90: {
       Female:1
     }

</code>```

I only have this code so far

```<code>    const foo = {};
    studentRecord.reduce((prevVal, currentVal) => {
      foo[currentVal['gender']] = (foo[currentVal['gender']] || 0) + 1;
    });
</code>```

Which only outputs
 {Male: 2, Female: 2}

答:
try this

const studentRecord = [
 {
   name: 'John Doe',
   gender: 'Male',
   grade: '85'
 },{
   name: 'Steve Doe',
   gender: 'Male',
   grade: '85'
 },{
   name: 'Jane Doe',
   gender: 'Male',
   grade: '90'
 },{
   name: 'Mary Jane',
   gender: 'Female',
   grade: '85'
 },
]

const grades = {};

studentRecord.map(e => { if(!grades[e.grade]) grades[e.grade] = {Male:0,Female:0}; });

studentRecord.map(e => grades[e.grade][e.gender]++ );

document.getElementById("result").innerHTML = JSON.stringify(grades)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="result"></div></code>```

Body:
Let's say we have an array of object like this

const studentRecord = [
 {
   name: 'John Doe',
   gender: 'Male',
   grade: '85'
 },{
   name: 'Steve Doe',
   gender: 'Male',
   grade: '85'
 },{
   name: 'Jane Doe',
   gender: 'Male',
   grade: '90'
 },{
   name: 'Mary Jane',
   gender: 'Female',
   grade: '85'
 },
]

I would like to count all students that are male that have the same grade and female students with the same grade something like this would be the output...

 85: {
       Male: 2,
       Female: 1,
     }
 90: {
       Female:1
     }

I only have this code so far

    const foo = {};
    studentRecord.reduce((prevVal, currentVal) => {
      foo[currentVal['gender']] = (foo[currentVal['gender']] || 0) + 1;
    });

Which only outputs
 {Male: 2, Female: 2}

Body:
try this

const studentRecord = [
 {
   name: 'John Doe',
   gender: 'Male',
   grade: '85'
 },{
   name: 'Steve Doe',
   gender: 'Male',
   grade: '85'
 },{
   name: 'Jane Doe',
   gender: 'Male',
   grade: '90'
 },{
   name: 'Mary Jane',
   gender: 'Female',
   grade: '85'
 },
]

const grades = {};

studentRecord.map(e => { if(!grades[e.grade]) grades[e.grade] = {Male:0,Female:0}; });

studentRecord.map(e => grades[e.grade][e.gender]++ );

document.getElementById("result").innerHTML = JSON.stringify(grades)

<div id="result"></div>


问:
How do I sum 2 specific column rows in a DataFrame if some of the values are NaN?
I'd like to create a new column, Inches_z. If there are values in both Inches_x and Inches_y, I want to sum the values in those 2 specific columns and return it as the result for Inches_z in the same row. If one NaN value exists, I'd like to return the row value that's not the NaN value. If both values are NaN, I'd like the resulting value to also be NaN. How do I do this?

I have:

```<code>Name    | Inches_x | Feet | Inches_y
------------------------------------
'Silvers'|    7    |   1   |     2
'Jones'  |    7    |   2   |     7
'Jackson'|    4    |  NaN  |    NaN
'Merole' |   NaN   |   2   |     8
'Kanoff' |   NaN   |   5   |    NaN
'Walker' |   NaN   |   8   |     0
'Smith'  |    8    |   0   |     3
</code>```

I want:

```<code>Name    | Inches_x | Feet | Inches_y | Inches_z
-----------------------------------------------
'Silvers'|    7    |   1   |     2   |    9
'Jones'  |    7    |   2   |     7   |    14
'Jackson'|    4    |  NaN  |    NaN  |    4
'Merole' |   NaN   |   2   |     8   |    8
'Kanoff' |   NaN   |   5   |    NaN  |   NaN
'Walker' |   NaN   |   8   |     0   |    0
'Smith'  |    8    |   0   |     3   |    11
</code>```

答:
You can simply use sum on axis=1 with min_count:

```<code>df["Inches_z"] = df.filter(like="Inches_").sum(1, min_count=1)
print (df)

        Name  Inches_x  Feet  Inches_y  Inches_z
0  'Silvers'       7.0   1.0       2.0       9.0
1    'Jones'       7.0   2.0       7.0      14.0
2  'Jackson'       4.0   NaN       NaN       4.0
3   'Merole'       NaN   2.0       8.0       8.0
4   'Kanoff'       NaN   5.0       NaN       NaN
5   'Walker'       NaN   8.0       0.0       0.0
6    'Smith'       8.0   0.0       3.0      11.0
</code>```

Body:
I'd like to create a new column, Inches_z. If there are values in both Inches_x and Inches_y, I want to sum the values in those 2 specific columns and return it as the result for Inches_z in the same row. If one NaN value exists, I'd like to return the row value that's not the NaN value. If both values are NaN, I'd like the resulting value to also be NaN. How do I do this?

I have:

Name    | Inches_x | Feet | Inches_y
------------------------------------
'Silvers'|    7    |   1   |     2
'Jones'  |    7    |   2   |     7
'Jackson'|    4    |  NaN  |    NaN
'Merole' |   NaN   |   2   |     8
'Kanoff' |   NaN   |   5   |    NaN
'Walker' |   NaN   |   8   |     0
'Smith'  |    8    |   0   |     3

I want:

Name    | Inches_x | Feet | Inches_y | Inches_z
-----------------------------------------------
'Silvers'|    7    |   1   |     2   |    9
'Jones'  |    7    |   2   |     7   |    14
'Jackson'|    4    |  NaN  |    NaN  |    4
'Merole' |   NaN   |   2   |     8   |    8
'Kanoff' |   NaN   |   5   |    NaN  |   NaN
'Walker' |   NaN   |   8   |     0   |    0
'Smith'  |    8    |   0   |     3   |    11

Body:
You can simply use sum on axis=1 with min_count:

df["Inches_z"] = df.filter(like="Inches_").sum(1, min_count=1)
print (df)

        Name  Inches_x  Feet  Inches_y  Inches_z
0  'Silvers'       7.0   1.0       2.0       9.0
1    'Jones'       7.0   2.0       7.0      14.0
2  'Jackson'       4.0   NaN       NaN       4.0
3   'Merole'       NaN   2.0       8.0       8.0
4   'Kanoff'       NaN   5.0       NaN       NaN
5   'Walker'       NaN   8.0       0.0       0.0
6    'Smith'       8.0   0.0       3.0      11.0


问:
Java generic Integer data vs primitive int data
I know that in Java we can use generic data types for various reasons. However, in terms of data storage. If a primitive int in Java can store up to 2,147,483,647 signed values, does this same storage capacity apply for the Integer generic type? Also, does the data type chosen in a program affect the runtime in any way? Or does it more so affect the space-time complexity of a program? My main question is that if I stick with a data type that is rather small but appropriate for my programs needs, than will it by any means help my program run faster?

答:
Yes, the same limitations apply.

You can see the source of the Integer class here:

http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/lang/Integer.java

Line 840 shows that an Integer is backed by a simple int:

```<code>private final int value;
</code>```

So whatever restrictions an int has, an Integer also has.

Body:
Yes, the same limitations apply.

You can see the source of the Integer class here:

http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/lang/Integer.java

Line 840 shows that an Integer is backed by a simple int:

private final int value;

So whatever restrictions an int has, an Integer also has.


问:
R session abort when I use assignTaxonomy
I have been having this problem for more than a week now and I am running out of time and patience.This problem occurs when I run my script on a Mac and when I run it on a PC (no difference of results from more RAM, it just aborts faster). When I try to run this line of my dataset, the session aborts.

```<code>  set.seed(119)
  tax_PR2 <- assignTaxonomy(seqtab,
                      "~/Desktop/Documents/Bruts/aeDNA_data_shared/pr2_version_4.11.1_dada2.fasta",
                      multithread=TRUE)
</code>```

Does anyone have any idea of what the problem is? I verified my dataset (seqtab is currently considered by R as a large matrix of 3930724 elements of 20.2Mb), I verified the space I have on my computer, I have all the needed packages to run this line of code and I tried different sources of genome database for PR2 (PR2 version 4.11.1 or 4.12.0 etc...) and it always has the same result.

If you have any ideas I would appreciate them. I hope the information I gave is sufficient.

Packages installed:

```<code>   library(BiocManager)
   library(Rcpp)
   library(dada2)
   library(ff)
   library(ggplot)
   library(gridExtra)
   library(phyloseq)
   library(vegan)
</code>```

答:
This is probably caused by a bug that was introduced in 1.14, see the Github issue here for more information: https://github.com/benjjneb/dada2/issues/916

We've just identified the cause, and a fix should be out soon. For immediate use, the workaround is to turn off multithreading, or to revert to the previous release 1.12.

Body:
I have been having this problem for more than a week now and I am running out of time and patience.This problem occurs when I run my script on a Mac and when I run it on a PC (no difference of results from more RAM, it just aborts faster). When I try to run this line of my dataset, the session aborts.

  set.seed(119)
  tax_PR2 <- assignTaxonomy(seqtab,
                      "~/Desktop/Documents/Bruts/aeDNA_data_shared/pr2_version_4.11.1_dada2.fasta",
                      multithread=TRUE)

Does anyone have any idea of what the problem is? I verified my dataset (seqtab is currently considered by R as a large matrix of 3930724 elements of 20.2Mb), I verified the space I have on my computer, I have all the needed packages to run this line of code and I tried different sources of genome database for PR2 (PR2 version 4.11.1 or 4.12.0 etc...) and it always has the same result.

If you have any ideas I would appreciate them. I hope the information I gave is sufficient.

Packages installed:

   library(BiocManager)
   library(Rcpp)
   library(dada2)
   library(ff)
   library(ggplot)
   library(gridExtra)
   library(phyloseq)
   library(vegan)


问:
Hibernate: Identifier
When using Hibernate:

Must I identify an id or composite id for each entity,
What about if I want to use table without any primary key and without composite key ...

Thanx in advance

答: I you are working with a legacy schema then you need to have a look at composite-id.</p>

OwnerDisplayName: Moro

ContentLicense: CC BY-SA 2.5

Title: Hibernate: Identifier

LastEditorDisplayName: Fabian Steeg

OwnerDisplayName: cherouvim


问:
Reading a formatted text file + Extracting certain information + Loading it into a JList
So here I got my code that would read a text file:

```<code>import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ReadTextFile {
    public static void main(String[] args) {
        File file = new File("Test.txt");
        StringBuffer contents = new StringBuffer();
        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new FileReader(file));
            String text = null;

            // repeat until all lines is read
            while ((text = reader.readLine()) != null) {
                contents.append(text).append(System.getProperty("line.separator"));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // show file contents here
        System.out.println(contents.toString());
    }
}
</code>```

Ok, now I need my text file (Test.txt) to have the following structure (Example):

```<code>topic:- <climate>subtopic1, <atmosphere_type>subtopic2

subtopic1:- <temperatures>sentence1, <gases>sentence2, <winds>sentence3
subtopic2:- <gas_composition>sentence4, <gravitational_weight>sentence5

sentence1:- temperatures are around 34ºC but they can reach -42ºC in winter
sentence2:- there are significant proportions of nitrogen (13%) and butane (24%)
sentence3:- there are permanent winds with gusts of 118 km/h
sentence4:- methane (48%), nitrogen (13%), butane (24%) and oxygen (12%)
sentence5:- gravity in ecuador is 7.95 atmospheres
</code>```

What I really need is to have 2 JList, where in the first JList I could choose a topic (Like "climate" or "atmosphere type") and then on my second JList I'd select a subtopic (If I choose "climate", then I could choose "temperatures", "gases" or "winds"), so when I hit a JButton, the program would show me the corresponding sentence. Is it hard to do something like that? Thanks for your help! :)

答:
Try to build the following data structures from the file.

```<code>// map of a topic (or subtopic) name to a list of subtopic (or sentence) names
Map<String, List<String>> subtopics = new HashMap<String, List<String>>();

// The above will contain the entries:
// topic -> [subtopic1, subtopic2]
// subtopic1 -> [sentence1, sentence2, sentence3]
// subtopic2 -> [sentence4, sentence5]

// map of topic/sentence name to heading
Map<String, String> headings = new HashMap<String, String>();

// This will contain:
// subtopic1 -> climate
// subtopic2 -> atmosphere type
// sentence1 -> temperatures
// sentence2 -> gases
// sentence3 -> winds
// sentence4 -> gas composition
// sentence5 -> gravitational weight

// dictionary for looking up a sentence name and retrieving its corresponding text
Map<String, String> dict = new HashMap<String, String>();

// sentence1 -> temperatures are around 34ºC but they can reach -42ºC in winter
// sentence2 -> there are significant proportions of nitrogen (13%) and butane (24%)
// sentence3 -> there are permanent winds with gusts of 118 km/h
// sentence4 -> methane (48%), nitrogen (13%), butane (24%) and oxygen (12%)
// sentence5 -> gravity in ecuador is 7.95 atmospheres
</code>```

This should get you going in a good direction. One bit to watch for is when adding a topic to the 'subtopics' map for the first time, you have to remember to first create the List (e.g. an ArrayList), add the subtopic name to the list and and the list as the value for the topic name. If the topic name is found in the list, just add the subtopic name to the existing List.

Body:
So here I got my code that would read a text file:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ReadTextFile {
    public static void main(String[] args) {
        File file = new File("Test.txt");
        StringBuffer contents = new StringBuffer();
        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new FileReader(file));
            String text = null;

            // repeat until all lines is read
            while ((text = reader.readLine()) != null) {
                contents.append(text).append(System.getProperty("line.separator"));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // show file contents here
        System.out.println(contents.toString());
    }
}

Ok, now I need my text file (Test.txt) to have the following structure (Example):

topic:- <climate>subtopic1, <atmosphere_type>subtopic2

subtopic1:- <temperatures>sentence1, <gases>sentence2, <winds>sentence3
subtopic2:- <gas_composition>sentence4, <gravitational_weight>sentence5

sentence1:- temperatures are around 34ºC but they can reach -42ºC in winter
sentence2:- there are significant proportions of nitrogen (13%) and butane (24%)
sentence3:- there are permanent winds with gusts of 118 km/h
sentence4:- methane (48%), nitrogen (13%), butane (24%) and oxygen (12%)
sentence5:- gravity in ecuador is 7.95 atmospheres

What I really need is to have 2 JList, where in the first JList I could choose a topic (Like "climate" or "atmosphere type") and then on my second JList I'd select a subtopic (If I choose "climate", then I could choose "temperatures", "gases" or "winds"), so when I hit a JButton, the program would show me the corresponding sentence. Is it hard to do something like that? Thanks for your help! :)

Body:
Try to build the following data structures from the file.

// map of a topic (or subtopic) name to a list of subtopic (or sentence) names
Map<String, List<String>> subtopics = new HashMap<String, List<String>>();

// The above will contain the entries:
// topic -> [subtopic1, subtopic2]
// subtopic1 -> [sentence1, sentence2, sentence3]
// subtopic2 -> [sentence4, sentence5]

// map of topic/sentence name to heading
Map<String, String> headings = new HashMap<String, String>();

// This will contain:
// subtopic1 -> climate
// subtopic2 -> atmosphere type
// sentence1 -> temperatures
// sentence2 -> gases
// sentence3 -> winds
// sentence4 -> gas composition
// sentence5 -> gravitational weight

// dictionary for looking up a sentence name and retrieving its corresponding text
Map<String, String> dict = new HashMap<String, String>();

// sentence1 -> temperatures are around 34ºC but they can reach -42ºC in winter
// sentence2 -> there are significant proportions of nitrogen (13%) and butane (24%)
// sentence3 -> there are permanent winds with gusts of 118 km/h
// sentence4 -> methane (48%), nitrogen (13%), butane (24%) and oxygen (12%)
// sentence5 -> gravity in ecuador is 7.95 atmospheres

This should get you going in a good direction. One bit to watch for is when adding a topic to the 'subtopics' map for the first time, you have to remember to first create the List (e.g. an ArrayList), add the subtopic name to the list and and the list as the value for the topic name. If the topic name is found in the list, just add the subtopic name to the existing List.


问:
Trouble importing multiple modules in Pythonanywhere fiels
Trying to run this code on pythonanywhere to send out automatic reminders in the morning to people with upcoming interviews. It works the first time I run the pythonanywhere.py file but breaks every subsequent time. This error does not happen on .ipynb files.

```<code>#Import pandas for dataframes
#Import datetime to check day
import numpy as np
import pandas as pd
import datetime
import requests
from twilio.rest import Client

#datetime_object = datetime.datetime.now() #Get current time
today = datetime.date.today() #Get current day
today = pd.Timestamp(today) #Convert current day into usable formate
interviewees = pd.ExcelFile('/home/drblessing/InterviewCandidates.xlsx') #Load in list of interview candidates
interviews_df = interviewees.parse() #Parse interview candidates into dataframe
Reminders = (interviews_df['Date'] - datetime.timedelta(days=1)) #Take their interview day and subtract one to send out reminder
Reminders_df = interviews_df[Reminders == today] #Checking which candidates have reminders today
Reminder_phones = pd.Series.tolist(Reminders_df['Phone'])
Reminder_emails = pd.Series.tolist(Reminders_df['Email'])
account_sid = '****************************'
auth_token = '5**************************'
client = Client(account_sid, auth_token)

for i in Reminder_phones:
    message = client.messages.create(
                              body='Hi there! This is an automated message to remind you about your interview on 2/20 at 1:00 pm. ',
                              from_='**********',
                              to=['******************']
                          )
    print(message.sid)

def send_simple_message():
    return requests.post(
        "https://api.mailgun.net/v3/dbless.net/messages",
        auth=("api", "*********************************"),
        data={"from": "urmom <mailgun@dbless.net>",
            "to": Reminder_emails,
            "subject": "Test",
            "text": "I had to show python who's BOSS "})

send_simple_message()
</code>```

However, after the first run I get this error:

RuntimeError: implement_array_function method already has a docstring

答:
Twilio developer evangelist here.

It appears that this is a problem with numpy. There is suggestion that downgrading numpy to version 1.15.4 might help.

As an aside, I know that pandas tutorials normally import numpy, but they tend to go on and use it later in the script. In this case you don't seem to be using numpy anywhere, so could you remove that import and see if your script still works?

Body:
Trying to run this code on pythonanywhere to send out automatic reminders in the morning to people with upcoming interviews. It works the first time I run the pythonanywhere.py file but breaks every subsequent time. This error does not happen on .ipynb files.

#Import pandas for dataframes
#Import datetime to check day
import numpy as np
import pandas as pd
import datetime
import requests
from twilio.rest import Client

#datetime_object = datetime.datetime.now() #Get current time
today = datetime.date.today() #Get current day
today = pd.Timestamp(today) #Convert current day into usable formate
interviewees = pd.ExcelFile('/home/drblessing/InterviewCandidates.xlsx') #Load in list of interview candidates
interviews_df = interviewees.parse() #Parse interview candidates into dataframe
Reminders = (interviews_df['Date'] - datetime.timedelta(days=1)) #Take their interview day and subtract one to send out reminder
Reminders_df = interviews_df[Reminders == today] #Checking which candidates have reminders today
Reminder_phones = pd.Series.tolist(Reminders_df['Phone'])
Reminder_emails = pd.Series.tolist(Reminders_df['Email'])
account_sid = '****************************'
auth_token = '5**************************'
client = Client(account_sid, auth_token)

for i in Reminder_phones:
    message = client.messages.create(
                              body='Hi there! This is an automated message to remind you about your interview on 2/20 at 1:00 pm. ',
                              from_='**********',
                              to=['******************']
                          )
    print(message.sid)

def send_simple_message():
    return requests.post(
        "https://api.mailgun.net/v3/dbless.net/messages",
        auth=("api", "*********************************"),
        data={"from": "urmom <mailgun@dbless.net>",
            "to": Reminder_emails,
            "subject": "Test",
            "text": "I had to show python who's BOSS "})

send_simple_message()

However, after the first run I get this error:

RuntimeError: implement_array_function method already has a docstring


问:
Why is C# List<T> Add method very slow?
I have an ASP.NET MVC project using Dapper to read data from a database and I need to export to Excel.

Dapper is fast! ExecuteReader takes only 35 seconds.

But list.Add(InStock); spends too much time!  Over 1020 seconds!

Do you have any idea why this is?

public List<InStock> GetList(string stSeId, string edSeId, string stSeDay, string edSeDay, string qDate)
{
    List<InStock> list = new List<InStock>();
    InStock InStock = null;

    IDataReader reader;

    using (var conn = _connection.GetConnection())
    {
        try
        {
            conn.Open();
            //******************Only 35 seconds*****
            reader = conn.ExecuteReader(fileHelper.GetScriptFromFile("GetInStock"),
                 new { STSeId = stSeId, EDSeId = edSeId, STSeDay = stSeDay, EDSeDay = edSeDay, qDate = qDate });
            //*************************************

            //******************Over 1020 seconds**********
            while (reader.Read())
            {
                InStock = new InStock();

                InStock.ColA = reader.GetString(reader.GetOrdinal("ColA"));
                InStock.ColB = reader.GetString(reader.GetOrdinal("ColB"));
                InStock.ColC = reader.GetString(reader.GetOrdinal("ColC"));

                list.Add(InStock);
            }
            //*********************************************
            return list;
        }
        catch (Exception err)
        {
            throw err;
        }
    }
}
```

答:
It's the database.

From Retrieve data using a DataReader,

The DataReader is a good choice when you're retrieving large amounts of data because the data is not cached in memory.

The key clue for your performance concern regards "because the data is not cached in memory". While strictly an implementation detail, each call to Read() gets new data from the database, while the List<InStock>.Add() call is just adding the new InStock to the list.

There are orders of magnitude of difference in processing times between disk access (even SSDs) compared to RAM. And theres orders of magnitude of difference between network requests and disk access. There's not really a conceivable way that anything other than the database access is the cause of most of your run time.

--

As a side note, you're going to exceed the maximum number of rows in an Excel worksheet.

Title: Why is C# List<T> Add method very slow?


问:
How to create JavaDoc using Android Studio without R and BuildConfig?
I want to generate the JavaDoc for my library excluding R and BuildConfig. The Generate JavaDoc... functionality from the Tools menu does not have the option to exclude files.

How to create JavaDoc using Android Studio without R and and BuildConfig?

答:
Another way to do it is to
1- go Tools --> Generate JavaDoc...
2- select Custom scope
3- from the drop down menu select Open Files. </p>

<p>this method will generate documentation for only the opened files in ur window </p>

Body:
Another way to do it is to
1- go Tools --> Generate JavaDoc...
2- select Custom scope
3- from the drop down menu select Open Files.

this method will generate documentation for only the opened files in ur window


问:
Sending values from one form to another without returning to form 1
I've been trying to figure out how to have a user input a string into a text box in Form1 and then hit a "Done" button and display Form2 with a Label containing the text from the text box in Form1.

I had come across this question which almost solved my problem (Send values from one form to another form) but the answer to the above question showed you how to hit a button, display Form2, then input a string, and hit another button returning to form 1 where the label displayed the text inputted in Form2.

I want to be able to input the string into a text box in Form 1 and when you hit a button display Form 2 with the label containing the string from the text box in Form 1.

I've spent a good hour or so trying to deconstruct the tiny bit of code from the linked question and get it to work how I want, but I just can't seem to understand it. If theres anyone who could either explain how to get a label in Form2 to contain a string from a text box in Form1 or show me the code necessary so I may look over it and understand it, it'd be greatly appreciated. As I currently cannot seem to get a grasp of how the code works in the previous question I linked.

This is the bit of code I used from the above linked question

```<code>// Form 1
// inside the button click event
using(Form2 form2 = new Form2())
{
    if(form2.ShowDialog() == DialogResult.OK)
    {
        someControlOnForm1.Text = form2.TheValue;
    }
}
</code>```

And...

```<code>// Inside Form2
// Create a public property to serve the value
public string TheValue
{
    get { return someTextBoxOnForm2.Text; }
}
</code>```

答:
In m understanding you want to get around with the data across forms?

If you want to get the data and retrieve it forms
you can try this

Create a class name called Globals

```<code>public class Globals
{
private static string _myData;
public static string MyData
{
    get
    {
        // Reads are usually simple
        return _myData;
    }
    set
    {
        _myData = value;
    }
 }

}
</code>```

in your Form1 set a value in a global variable

```<code>Globals.myData = "someText"; //set the value
</code>```

in your Form2 get the value

```<code>//example we have a lable
label1.Text = Globals.myData //this returns the value "someText"
</code>```

Body:
I've been trying to figure out how to have a user input a string into a text box in Form1 and then hit a "Done" button and display Form2 with a Label containing the text from the text box in Form1.

I had come across this question which almost solved my problem (Send values from one form to another form) but the answer to the above question showed you how to hit a button, display Form2, then input a string, and hit another button returning to form 1 where the label displayed the text inputted in Form2.

I want to be able to input the string into a text box in Form 1 and when you hit a button display Form 2 with the label containing the string from the text box in Form 1.

I've spent a good hour or so trying to deconstruct the tiny bit of code from the linked question and get it to work how I want, but I just can't seem to understand it. If theres anyone who could either explain how to get a label in Form2 to contain a string from a text box in Form1 or show me the code necessary so I may look over it and understand it, it'd be greatly appreciated. As I currently cannot seem to get a grasp of how the code works in the previous question I linked.

This is the bit of code I used from the above linked question

// Form 1
// inside the button click event
using(Form2 form2 = new Form2())
{
    if(form2.ShowDialog() == DialogResult.OK)
    {
        someControlOnForm1.Text = form2.TheValue;
    }
}

And...

// Inside Form2
// Create a public property to serve the value
public string TheValue
{
    get { return someTextBoxOnForm2.Text; }
}

Body:
In m understanding you want to get around with the data across forms?

If you want to get the data and retrieve it forms
you can try this

Create a class name called Globals

public class Globals
{
private static string _myData;
public static string MyData
{
    get
    {
        // Reads are usually simple
        return _myData;
    }
    set
    {
        _myData = value;
    }
 }

}

in your Form1 set a value in a global variable

Globals.myData = "someText"; //set the value

in your Form2 get the value

//example we have a lable
label1.Text = Globals.myData //this returns the value "someText"


问:
REST API DELETE LIST ITEM - USE THIS CODE
Delete Items:

This Code will help to delete the item in list using REST API for SharePoint.

var SiteUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('ListName')/items('" + courtids + "')";

```<code>        $.ajax({
              url: SiteUrl
                         method: 'DELETE',
                         headers: {
                             'X-RequestDigest': $('#__REQUESTDIGEST').val()
                         },

            async: false,
            success: function (data) {
                alert("Delete success");

            },
            error: function (data) {

            }
        });
</code>```

答:
To delete item using REST API, the following example code for your reference.</p>

```<code><script src="http://code.jquery.com/jquery-1.12.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
    var listName="listName";
    var itemId=1;
    $("#deleteItem").click(function(){
        deleteItem(listName,itemId);
    });
});
function deleteItem(listName,itemId){
    var siteUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('"+listName+"')/items(" + itemId + ")";
    $.ajax({
        url: siteUrl,
        type: "POST",
        headers: {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "IF-MATCH": "*",
            "X-HTTP-Method": "DELETE"
        },
        async: false,
        success: function (data) {
            alert("Delete success");
        },
        error: function (data) {
        }
    });
}
</script>
<input id="deleteItem" type="button" value="Delete Item"/>
</code>```

Body:
Delete Items:

This Code will help to delete the item in list using REST API for SharePoint.

var SiteUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('ListName')/items('" + courtids + "')";

        $.ajax({
              url: SiteUrl
                         method: 'DELETE',
                         headers: {
                             'X-RequestDigest': $('#__REQUESTDIGEST').val()
                         },

            async: false,
            success: function (data) {
                alert("Delete success");

            },
            error: function (data) {

            }
        });

Body:
To delete item using REST API, the following example code for your reference.

<script src="http://code.jquery.com/jquery-1.12.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
    var listName="listName";
    var itemId=1;
    $("#deleteItem").click(function(){
        deleteItem(listName,itemId);
    });
});
function deleteItem(listName,itemId){
    var siteUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('"+listName+"')/items(" + itemId + ")";
    $.ajax({
        url: siteUrl,
        type: "POST",
        headers: {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "IF-MATCH": "*",
            "X-HTTP-Method": "DELETE"
        },
        async: false,
        success: function (data) {
            alert("Delete success");
        },
        error: function (data) {
        }
    });
}
</script>
<input id="deleteItem" type="button" value="Delete Item"/>


问:
Generic Action Link in MVC 3 / Razor
Just started a new MVC 3 project and I can't get the strongly-type generic action link and url helpers I am used to in MVC 2 futures.

Which nuget packages and namespaces do I need to get hold off?

Example

```<code>Html.ActionLink<HomeController>(c => c.Index(), "Home")
</code>```

ANSWER:

Just needed to reference Microsoft.Web.Mvc via NuGet MvcContrib - and make the namespace available in the views.

答: Grab the T4MVC package in NuGet.</p>

Title: Generic Action Link in MVC 3 / Razor

Body:
Just started a new MVC 3 project and I can't get the strongly-type generic action link and url helpers I am used to in MVC 2 futures.

Which nuget packages and namespaces do I need to get hold off?

Example

Html.ActionLink<HomeController>(c => c.Index(), "Home")

ANSWER:

Just needed to reference Microsoft.Web.Mvc via NuGet MvcContrib - and make the namespace available in the views.

Body: Grab the T4MVC package in NuGet.


问:
Why is the Selenium driver.find command returning a list twice as large as it should be?
I'm using Selenium to do some web scraping of urls. However, I've noticed that Python is inserting blanks in between urls.

This is being returned to me:

['uk.linkedin.com › pauljgarner',

'',

'uk.linkedin.com › namakarskiy',

'',

'uk.linkedin.com › danny-butler-62834777',

'',

'uk.linkedin.com › ksrameshkanth'

When it should be:

['uk.linkedin.com › pauljgarner',

'uk.linkedin.com › namakarskiy',

'uk.linkedin.com › danny-butler-62834777',

'uk.linkedin.com › ksrameshkanth'

My Relevant Code:

```<code>from selenium import webdriver
driver = webdriver.Chrome('/Users/yu/Downloads/chromedriver')
driver.get('https:www.google.com')

##inputting google search##
search_query = driver.find_element_by_name('q')
search_query.send_keys(parameters.search_query)
search_query.send_keys(Keys.RETURN)

##compiling list of linkedin urls##
linkedin_urls = driver.find_elements_by_class_name('iUh30')
linkedin_urls = [url.text for url in linkedin_urls]

linkedin_urls
len(linkedin_urls)
##the above command returns length of 20, when it should be 10##
</code>```

Why is this happening and how do I fix it? Haven't seen anything similar on the web

答:
I tried your code and I get as many spaces as the data elements (exactly as you've indicated). When I looked at the elements at the webpage, I found that elements are duplicated when you use the class iUh30.

I fixed the issue by searching for a parent div element that has the class TbwUpd NJjxre (using an XPath query), as follows:

Instead of:

```<code>linkedin_urls = driver.find_elements_by_class_name('iUh30')
</code>```

Use this:

```<code>linkedin_urls = driver.find_elements_by_xpath(".//div[@class='TbwUpd NJjxre']")
</code>```

Hope it helps.

Body:
I'm using Selenium to do some web scraping of urls. However, I've noticed that Python is inserting blanks in between urls.

This is being returned to me:

['uk.linkedin.com › pauljgarner',

'',

'uk.linkedin.com › namakarskiy',

'',

'uk.linkedin.com › danny-butler-62834777',

'',

'uk.linkedin.com › ksrameshkanth'

When it should be:

['uk.linkedin.com › pauljgarner',

'uk.linkedin.com › namakarskiy',

'uk.linkedin.com › danny-butler-62834777',

'uk.linkedin.com › ksrameshkanth'

My Relevant Code:

from selenium import webdriver
driver = webdriver.Chrome('/Users/yu/Downloads/chromedriver')
driver.get('https:www.google.com')

##inputting google search##
search_query = driver.find_element_by_name('q')
search_query.send_keys(parameters.search_query)
search_query.send_keys(Keys.RETURN)

##compiling list of linkedin urls##
linkedin_urls = driver.find_elements_by_class_name('iUh30')
linkedin_urls = [url.text for url in linkedin_urls]

linkedin_urls
len(linkedin_urls)
##the above command returns length of 20, when it should be 10##

Why is this happening and how do I fix it? Haven't seen anything similar on the web

Body:
I tried your code and I get as many spaces as the data elements (exactly as you've indicated). When I looked at the elements at the webpage, I found that elements are duplicated when you use the class iUh30.

I fixed the issue by searching for a parent div element that has the class TbwUpd NJjxre (using an XPath query), as follows:

Instead of:

linkedin_urls = driver.find_elements_by_class_name('iUh30')

Use this:

linkedin_urls = driver.find_elements_by_xpath(".//div[@class='TbwUpd NJjxre']")

Hope it helps.


问:
How do I make my model's depdent fields appear in my JSON using Django serializers?
I'm using Django 2.0 and Python 3.7.  I have the following models ...

```<code>from django.db import models

from address.models import AddressField
from phonenumber_field.modelfields import PhoneNumberField
from address.models import State
from address.models import Country

class CoopTypeManager(models.Manager):

    def get_by_natural_key(self, name):
        return self.get_or_create(name=name)[0]

class CoopType(models.Model):
    name = models.CharField(max_length=200, null=False)

    objects = CoopTypeManager()

    class Meta:
        unique_together = ("name",)

class Coop(models.Model):
    name = models.CharField(max_length=250, null=False)
    type = models.ForeignKey(CoopType, on_delete=None)
    address = AddressField(on_delete=models.CASCADE)
    enabled = models.BooleanField(default=True, null=False)
    phone = PhoneNumberField(null=True)
    email = models.EmailField(null=True)
    web_site = models.TextField()
</code>```

And then I created the following serializers ...

```<code>from rest_framework import serializers
from maps.models import Coop, CoopType

class CoopSerializer(serializers.ModelSerializer):
    class Meta:
        model = Coop
        fields = ['id', 'name', 'type', 'address', 'enabled', 'phone', 'email', 'web_site']

    def create(self, validated_data):
        """
        Create and return a new `Snippet` instance, given the validated data.
        """
        return Coop.objects.create(**validated_data)

    def update(self, instance, validated_data):
        """
        Update and return an existing `Coop` instance, given the validated data.
        """
        instance.name = validated_data.get('name', instance.name)
        instance.type = validated_data.get('type', instance.type)
        instance.address = validated_data.get('address', instance.address)
        instance.enabled = validated_data.get('enabled', instance.enabled)
        instance.phone = validated_data.get('phone', instance.phone)
        instance.email = validated_data.get('email', instance.email)
        instance.web_site = validated_data.get('web_site', instance.web_site)
        instance.save()
        return instance

class CoopTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = CoopType
        fields = ['id', 'name']

    def create(self, validated_data):
        """
        Create and return a new `CoopType` instance, given the validated data.
        """
        return CoopType.objects.create(**validated_data)

    def update(self, instance, validated_data):
        """
        Update and return an existing `Snippet` instance, given the validated data.
        """
        instance.name = validated_data.get('name', instance.name)
        instance.save()
        return instance
</code>```

I'm trying to create an API to display my models as JSON.  I created this views file

```<code>from maps.models import Coop
from maps.serializers import CoopSerializer
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

class CoopList(APIView):
    """
    List all coops, or create a new coop.
    """
    def get(self, request, format=None):
        coops = Coop.objects.all()
        serializer = CoopSerializer(coops, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = CoopSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class CoopDetail(APIView):
    """
    Retrieve, update or delete a coop instance.
    """
    def get_object(self, pk):
        try:
            return Coop.objects.get(pk=pk)
        except Coop.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        coop = self.get_object(pk)
        serializer = CoopSerializer(coop)
        return Response(serializer.data)

    def put(self, request, pk, format=None):
        coop = self.get_object(pk)
        serializer = CoopSerializer(coop, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        coop = self.get_object(pk)
        coop.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
</code>```

However, my dependent model, CoopType, is not getting displayed as JSON.  Only its primary key is getting displayed, e.g. ...

```<code>{
    "id": 915,
    "name": "Young Men's Educational Network",
    "type": 10,
    "address": 790,
    "enabled": true,
    "phone": null,
    "email": null,
    "web_site": "www.ymenchi.com/"
},
</code>```

How do I get my dependent model to appear in my JSON?

答:
Override the to_representation(...) method of the Serializer

```<code>class CoopSerializer(serializers.ModelSerializer):
    # other code snippets
    <b>def to_representation(self, instance):
        rep = super().to_representation(instance)
        rep['type'] = CoopTypeSerializer(instance.type).data
        return rep</b></code>```

Reference: DRF: Simple foreign key assignment with nested serializers?

Body:
I'm using Django 2.0 and Python 3.7.  I have the following models ...

from django.db import models

from address.models import AddressField
from phonenumber_field.modelfields import PhoneNumberField
from address.models import State
from address.models import Country

class CoopTypeManager(models.Manager):

    def get_by_natural_key(self, name):
        return self.get_or_create(name=name)[0]

class CoopType(models.Model):
    name = models.CharField(max_length=200, null=False)

    objects = CoopTypeManager()

    class Meta:
        unique_together = ("name",)

class Coop(models.Model):
    name = models.CharField(max_length=250, null=False)
    type = models.ForeignKey(CoopType, on_delete=None)
    address = AddressField(on_delete=models.CASCADE)
    enabled = models.BooleanField(default=True, null=False)
    phone = PhoneNumberField(null=True)
    email = models.EmailField(null=True)
    web_site = models.TextField()

And then I created the following serializers ...

from rest_framework import serializers
from maps.models import Coop, CoopType

class CoopSerializer(serializers.ModelSerializer):
    class Meta:
        model = Coop
        fields = ['id', 'name', 'type', 'address', 'enabled', 'phone', 'email', 'web_site']

    def create(self, validated_data):
        """
        Create and return a new `Snippet` instance, given the validated data.
        """
        return Coop.objects.create(**validated_data)

    def update(self, instance, validated_data):
        """
        Update and return an existing `Coop` instance, given the validated data.
        """
        instance.name = validated_data.get('name', instance.name)
        instance.type = validated_data.get('type', instance.type)
        instance.address = validated_data.get('address', instance.address)
        instance.enabled = validated_data.get('enabled', instance.enabled)
        instance.phone = validated_data.get('phone', instance.phone)
        instance.email = validated_data.get('email', instance.email)
        instance.web_site = validated_data.get('web_site', instance.web_site)
        instance.save()
        return instance

class CoopTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = CoopType
        fields = ['id', 'name']

    def create(self, validated_data):
        """
        Create and return a new `CoopType` instance, given the validated data.
        """
        return CoopType.objects.create(**validated_data)

    def update(self, instance, validated_data):
        """
        Update and return an existing `Snippet` instance, given the validated data.
        """
        instance.name = validated_data.get('name', instance.name)
        instance.save()
        return instance

I'm trying to create an API to display my models as JSON.  I created this views file

from maps.models import Coop
from maps.serializers import CoopSerializer
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

class CoopList(APIView):
    """
    List all coops, or create a new coop.
    """
    def get(self, request, format=None):
        coops = Coop.objects.all()
        serializer = CoopSerializer(coops, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = CoopSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class CoopDetail(APIView):
    """
    Retrieve, update or delete a coop instance.
    """
    def get_object(self, pk):
        try:
            return Coop.objects.get(pk=pk)
        except Coop.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        coop = self.get_object(pk)
        serializer = CoopSerializer(coop)
        return Response(serializer.data)

    def put(self, request, pk, format=None):
        coop = self.get_object(pk)
        serializer = CoopSerializer(coop, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        coop = self.get_object(pk)
        coop.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

However, my dependent model, CoopType, is not getting displayed as JSON.  Only its primary key is getting displayed, e.g. ...

{
    "id": 915,
    "name": "Young Men's Educational Network",
    "type": 10,
    "address": 790,
    "enabled": true,
    "phone": null,
    "email": null,
    "web_site": "www.ymenchi.com/"
},

How do I get my dependent model to appear in my JSON?

Body:
Override the to_representation(...) method of the Serializer

class CoopSerializer(serializers.ModelSerializer):
    # other code snippets
    def to_representation(self, instance):
        rep = super().to_representation(instance)
        rep['type'] = CoopTypeSerializer(instance.type).data
        return rep

Reference: DRF: Simple foreign key assignment with nested serializers?