问:
ZooKeeperClientTimeoutException when using @EmbeddedKafka
Once I add @EmbeddedKafka to an integration test I see the following error:</p>

```<code>Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'embeddedKafka': Invocation of init method failed; nested exception is kafka.zookeeper.ZooKeeperClientTimeoutException: Timed out waiting for connection while in state: CONNECTING
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1796)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:407)
    at org.springframework.kafka.test.context.EmbeddedKafkaContextCustomizer.customizeContext(EmbeddedKafkaContextCustomizer.java:119)
    at org.springframework.boot.test.context.SpringBootContextLoader$ContextCustomizerAdapter.initialize(SpringBootContextLoader.java:315)
    at org.springframework.boot.SpringApplication.applyInitializers(SpringApplication.java:626)
    at org.springframework.boot.SpringApplication.prepareContext(SpringApplication.java:370)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:126)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    ... 64 more
Caused by: kafka.zookeeper.ZooKeeperClientTimeoutException: Timed out waiting for connection while in state: CONNECTING
    at kafka.zookeeper.ZooKeeperClient.$anonfun$waitUntilConnected$3(ZooKeeperClient.scala:258)
    at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
    at kafka.utils.CoreUtils$.inLock(CoreUtils.scala:253)
    at kafka.zookeeper.ZooKeeperClient.waitUntilConnected(ZooKeeperClient.scala:254)
    at kafka.zookeeper.ZooKeeperClient.<init>(ZooKeeperClient.scala:112)
    at kafka.zk.KafkaZkClient$.apply(KafkaZkClient.scala:1826)
    at kafka.server.KafkaServer.createZkClient$1(KafkaServer.scala:364)
    at kafka.server.KafkaServer.initZkClient(KafkaServer.scala:387)
    at kafka.server.KafkaServer.startup(KafkaServer.scala:207)
    at kafka.utils.TestUtils$.createServer(TestUtils.scala:142)
    at kafka.utils.TestUtils.createServer(TestUtils.scala)
    at org.springframework.kafka.test.EmbeddedKafkaBroker.afterPropertiesSet(EmbeddedKafkaBroker.java:305)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1855)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1792)
</code>```

答:
If you are using Spring boot 2.2.x
you have to explicitly use spring kafka 2.4.6 (at least in test)

```<code>testImplementation 'org.springframework.kafka:spring-kafka:2.4.6.RELEASE'
testImplementation 'org.springframework.kafka:spring-kafka-test:2.4.6.RELEASE'
</code>```

and also explicitly set your kafka client version to 2.3.1 (in gradle.properties file):

```<code>kafka.version=2.4.1
</code>```

Body:
Once I add @EmbeddedKafka to an integration test I see the following error:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'embeddedKafka': Invocation of init method failed; nested exception is kafka.zookeeper.ZooKeeperClientTimeoutException: Timed out waiting for connection while in state: CONNECTING
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1796)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:407)
    at org.springframework.kafka.test.context.EmbeddedKafkaContextCustomizer.customizeContext(EmbeddedKafkaContextCustomizer.java:119)
    at org.springframework.boot.test.context.SpringBootContextLoader$ContextCustomizerAdapter.initialize(SpringBootContextLoader.java:315)
    at org.springframework.boot.SpringApplication.applyInitializers(SpringApplication.java:626)
    at org.springframework.boot.SpringApplication.prepareContext(SpringApplication.java:370)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:126)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    ... 64 more
Caused by: kafka.zookeeper.ZooKeeperClientTimeoutException: Timed out waiting for connection while in state: CONNECTING
    at kafka.zookeeper.ZooKeeperClient.$anonfun$waitUntilConnected$3(ZooKeeperClient.scala:258)
    at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
    at kafka.utils.CoreUtils$.inLock(CoreUtils.scala:253)
    at kafka.zookeeper.ZooKeeperClient.waitUntilConnected(ZooKeeperClient.scala:254)
    at kafka.zookeeper.ZooKeeperClient.<init>(ZooKeeperClient.scala:112)
    at kafka.zk.KafkaZkClient$.apply(KafkaZkClient.scala:1826)
    at kafka.server.KafkaServer.createZkClient$1(KafkaServer.scala:364)
    at kafka.server.KafkaServer.initZkClient(KafkaServer.scala:387)
    at kafka.server.KafkaServer.startup(KafkaServer.scala:207)
    at kafka.utils.TestUtils$.createServer(TestUtils.scala:142)
    at kafka.utils.TestUtils.createServer(TestUtils.scala)
    at org.springframework.kafka.test.EmbeddedKafkaBroker.afterPropertiesSet(EmbeddedKafkaBroker.java:305)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1855)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1792)

Body:
If you are using Spring boot 2.2.x
you have to explicitly use spring kafka 2.4.6 (at least in test)

testImplementation 'org.springframework.kafka:spring-kafka:2.4.6.RELEASE'
testImplementation 'org.springframework.kafka:spring-kafka-test:2.4.6.RELEASE'

and also explicitly set your kafka client version to 2.3.1 (in gradle.properties file):

kafka.version=2.4.1


来源: stackexchange

问:
Video to webp converter software
I need to convert several videos to animated webp format, but I found no software to handle it.
There are some online tools, but they are either paid or work with restrictions like low resolution and fps.</p>

答:
Though didn't find a software with GUI that can to the converting, I tried the ffmpeg CLI method and it works for me.

1. Install ffmpeg CLI through homebrew

In terminal.app, install ffmpeg through homebrew

```<code>brew install ffmpeg
</code>```

Validate the installation:

```<code>which ffmpeg
</code>```

Expect to see terminal returns the directory path of ffmpeg such as /usr/local/bin/ffmpeg

2. Run and convert

Example command which would convert an mp4 file to a lossless loop playing webp file in 20FPS with resolution 800px(width) * h600px(height):

```<code>ffmpeg -i input_filename.mp4 -vcodec libwebp -filter:v fps=fps=20 -lossless 1 -loop 0 -preset default -an -vsync 0 -s 800:600 output_filename.webp
</code>```

primary options:

set frame per second as 20: -filter:v fps=fps=20

set output file lossless: -lossless 1

set output webp file loop play: -loop 0. For non-loop, use -loop 1

set rendering mode -preset default , can set as picture, photo, text, icon, drawing and none as needed. It would effect output file size. http://ffmpeg.org/ffmpeg-all.html#Options-28

set output webp resolution as w800px * h600px -s 800:600

For more option details, please visit the the ffmpeg libwebp documentation

This method should applicable for majority video formats including .mov, .avi, .flv, etc. as input files as well as .gif format as output file.

Noted this on my gist: https://gist.github.com/witmin/1edf926c2886d5c8d9b264d70baf7379

ContentLicense: CC BY-SA 4.0

Title: Video to webp converter software

Body:
Though didn't find a software with GUI that can to the converting, I tried the ffmpeg CLI method and it works for me.

1. Install ffmpeg CLI through homebrew

In terminal.app, install ffmpeg through homebrew

brew install ffmpeg

Validate the installation:

which ffmpeg

Expect to see terminal returns the directory path of ffmpeg such as /usr/local/bin/ffmpeg

2. Run and convert

Example command which would convert an mp4 file to a lossless loop playing webp file in 20FPS with resolution 800px(width) * h600px(height):

ffmpeg -i input_filename.mp4 -vcodec libwebp -filter:v fps=fps=20 -lossless 1 -loop 0 -preset default -an -vsync 0 -s 800:600 output_filename.webp

primary options:

set frame per second as 20: -filter:v fps=fps=20

set output file lossless: -lossless 1

set output webp file loop play: -loop 0. For non-loop, use -loop 1

set rendering mode -preset default , can set as picture, photo, text, icon, drawing and none as needed. It would effect output file size. http://ffmpeg.org/ffmpeg-all.html#Options-28

set output webp resolution as w800px * h600px -s 800:600

For more option details, please visit the the ffmpeg libwebp documentation

This method should applicable for majority video formats including .mov, .avi, .flv, etc. as input files as well as .gif format as output file.

Noted this on my gist: https://gist.github.com/witmin/1edf926c2886d5c8d9b264d70baf7379


问:
Can not install Phpmyadmin
Cant install phpmyadmin on kali linux rolling on virtualbox after following a 2019 tutorial on youtube,

Tried

```<code>sudo apt-get install phpmyadmin
</code>```

(which was all the tutor done)

Package phpmyadmin is not available, but is referred to by another package.

apt-cache policy phpmyadmin says there is no candidate.

Unless phpmyadmin has a repository i have not added then i am confused as the tutorial i watched and followed was to the letter.

/etc/apt/sources.list

deb http://http.kali.org/kali kali-rolling main non-free contrib
deb-src http://http.kali.org/kali kali-rolling main non-free contrib

答:
Repository which should be in your "/etc/apt/sources.list":

```<code>deb http://http.kali.org/kali kali-rolling main non-free contrib
</code>```

Next, run the following commands:

```<code>$ sudo apt-get update
$ sudo apt-get install phpmyadmin -y
$ sudo ln -s /usr/share/phpmyadmin  /var/www/html
$ sudo service mysql start
$ sudo service apache2 start
</code>```

Finally, start your favorite browser and type:

```<code>http://localhost/phpmyadmin
</code>```

Title: Can not install Phpmyadmin

Body:
Cant install phpmyadmin on kali linux rolling on virtualbox after following a 2019 tutorial on youtube,

Tried

sudo apt-get install phpmyadmin

(which was all the tutor done)

Package phpmyadmin is not available, but is referred to by another package.

apt-cache policy phpmyadmin says there is no candidate.

Unless phpmyadmin has a repository i have not added then i am confused as the tutorial i watched and followed was to the letter.

/etc/apt/sources.list

deb http://http.kali.org/kali kali-rolling main non-free contrib
deb-src http://http.kali.org/kali kali-rolling main non-free contrib

Body:
Repository which should be in your "/etc/apt/sources.list":

deb http://http.kali.org/kali kali-rolling main non-free contrib

Next, run the following commands:

$ sudo apt-get update
$ sudo apt-get install phpmyadmin -y
$ sudo ln -s /usr/share/phpmyadmin  /var/www/html
$ sudo service mysql start
$ sudo service apache2 start

Finally, start your favorite browser and type:

http://localhost/phpmyadmin


问:
Zipcodes are missing in kibana 7.2.1 map visualization
I am drawing some data on US zip code map in kibana, whenever I open the visualization there is an error popup which says:

Unable to show 43 results on map: Ensure that each of these term matches a shape on that shape's join field: 00605, 00613, 00681, 00970, 00977, 15134, 18501, 29151, 29802, 29861, 30031, 31131, 73070, 74018, 75033, 77225, 77305, 77399, 77512, 78599, 84091, 84129, 85001, 85117, 85274, 85311, 85372, 85378, 85732, 92088, 92112, 92263, 92329, 92340, 92375, 92393, 92402, 92415, 92423, 92502, 92513, 92546, 97078

I think these are the zipcodes present in my data but not in kibana.
if this is the case, how can i add these zip codes or complete zip code boundaries to kibana?
if not, what can i do to make it work?

Also searched for some resources and found that these zip codes are not available https://maps.elastic.co/v7.2/index.html?locale=en#file/usa_zip_codes

答:
After searching I got to know that zip codes listed above do not represent an area instead they represent a particular Post Office Box which is a point, not area.
I have confirmed this from here: https://www.zip-codes.com/zip-code/00605/zip-code-00605.asp</p>


问:
Using Java Stream API, finding highest value of variable, with the stream of the changes made to the variable

Context/Scenario

Let's say we have an immutable object called Transaction, where transaction.getAction() would return a TransactionAction enum which can be DEPOSIT or WITHDRAW, and transaction.getAmount() would return an Integer which specify the amount of money being deposit or withdrawn.

```<code>enum TransactionAction {
    WITHDRAW,
    DEPOSIT
}

public class Transaction {

    private final TransactionAction action;
    private final int amount;

    public Transaction(TransactionAction action, int amount) {
        this.action = action;
        this.amount = amount;
    }

    public TransactionAction getAction() {
        return action;
    }

    public int getAmount() {
        return amount;
    }

}
</code>```

Question

We now have a Stream<Transaction> which is a stream filled with Transaction that can either be DEPOSIT or WITHDRAW. We can imagine this Stream<Transaction> as a history of transactions of one particular bank account.

What I am trying to achieve is to get the highest balance the account has ever achieved in most efficient manner (thus using Stream API).

Example

Bob transaction history is:

```<code>// balance start at 0
[DEPOSIT]   1200        // balance: 1200
[DEPOSIT]   500         // balance: 1700
[WITHDRAW]  700         // balance: 1000
[DEPOSIT]   300         // balance: 1300
[WITHDRAW]  800         // balance: 500
[WITHDRAW]  500         // balance: 0
</code>```

Bob's highest balance is 1700.

答:
A wrong solution

    // Deposit is positive, withdrawal is negative.
    final Stream<Integer> theOriginalDepositWithdrawals = Stream.of(1200, 500, -700, 300, -800, -500);
    final Stream<Integer> sequentialDepositWithdrawals = theOriginalDepositWithdrawals.sequential();

    final CurrentBalanceMaximumBalance currentMaximumBalance = sequentialDepositWithdrawals.<CurrentBalanceMaximumBalance>reduce(

      // Identity.
      new CurrentBalanceMaximumBalance(0, Integer.MIN_VALUE),

      // Accumulator.
      (currentAccumulation, elementDepositWithdrawal) -> {

        final int newCurrentBalance =
          currentAccumulation.currentBalance +
          elementDepositWithdrawal;

        final int newMaximumBalance = Math.max(
          currentAccumulation.maximumBalance,
          newCurrentBalance
        );

        return new CurrentBalanceMaximumBalance(
          newCurrentBalance,
          newMaximumBalance
        );
      },

      // Combiner.
      (res1, res2) -> {

        final int newCurrentBalance =
          res1.currentBalance +
          res2.currentBalance;

        final int newMaximumBalance = Math.max(
          res1.maximumBalance,
          res2.maximumBalance
        );

        return new CurrentBalanceMaximumBalance(
          newCurrentBalance, newMaximumBalance
        );
      }

    );

    System.out.println("Maximum is: " + currentMaximumBalance.maximumBalance);
```

<p>Helper class:</p>

<pre class="lang-java prettyprint-override"><code>class CurrentBalanceMaximumBalance {

  public final int currentBalance;
  public final int maximumBalance;

  public CurrentBalanceMaximumBalance(
    int currentBalance,
    int maximumBalance
  ) {

    this.currentBalance = currentBalance;
    this.maximumBalance = maximumBalance;
  }
}
</code>```

This is a wrong solution. It might arbitrarily work, but there is no guarantee that it will.

It breaks the interface of reduce. The properties that are broken are associativity for both the accumulator function and the combiner function. It also doesn't require that the stream respects the order of the original transactions.

This makes it possibly dangerous to use, and might well give wrong results depending on what the implementation of reduce happens to be as well as whether the stream respects the original order of the deposits and withdrawals or not.

Using sequential() here is not sufficient, since sequential() is about sequential/parallel execution. An example of a stream that executes sequentially but does not have ordering is a stream created from a HashSet and then have sequential() called on it.

A correct solution

The problem uses the concept of a "current balance", and that is only meaningful when computed from the first transaction and then in order to the end. For instance, if you have the list [-1000, 10, 10, -1000], you cannot start in the middle and then say that the "current balance" was 20 at some point. You must apply the operations reg. "current balance" in the order of the original transactions.

So, one straight-forward solution is to:

Require that the stream respects the original order of transactions, with a defined "encounter order".

Apply forEachOrdered().

Body:
Context/Scenario

Let's say we have an immutable object called Transaction, where transaction.getAction() would return a TransactionAction enum which can be DEPOSIT or WITHDRAW, and transaction.getAmount() would return an Integer which specify the amount of money being deposit or withdrawn.

enum TransactionAction {
    WITHDRAW,
    DEPOSIT
}

public class Transaction {

    private final TransactionAction action;
    private final int amount;

    public Transaction(TransactionAction action, int amount) {
        this.action = action;
        this.amount = amount;
    }

    public TransactionAction getAction() {
        return action;
    }

    public int getAmount() {
        return amount;
    }

}

Question

We now have a Stream<Transaction> which is a stream filled with Transaction that can either be DEPOSIT or WITHDRAW. We can imagine this Stream<Transaction> as a history of transactions of one particular bank account.

What I am trying to achieve is to get the highest balance the account has ever achieved in most efficient manner (thus using Stream API).

Example

Bob transaction history is:

// balance start at 0
[DEPOSIT]   1200        // balance: 1200
[DEPOSIT]   500         // balance: 1700
[WITHDRAW]  700         // balance: 1000
[DEPOSIT]   300         // balance: 1300
[WITHDRAW]  800         // balance: 500
[WITHDRAW]  500         // balance: 0

Bob's highest balance is 1700.

Body:
A wrong solution

    // Deposit is positive, withdrawal is negative.
    final Stream<Integer> theOriginalDepositWithdrawals = Stream.of(1200, 500, -700, 300, -800, -500);
    final Stream<Integer> sequentialDepositWithdrawals = theOriginalDepositWithdrawals.sequential();

    final CurrentBalanceMaximumBalance currentMaximumBalance = sequentialDepositWithdrawals.<CurrentBalanceMaximumBalance>reduce(

      // Identity.
      new CurrentBalanceMaximumBalance(0, Integer.MIN_VALUE),

      // Accumulator.
      (currentAccumulation, elementDepositWithdrawal) -> {

        final int newCurrentBalance =
          currentAccumulation.currentBalance +
          elementDepositWithdrawal;

        final int newMaximumBalance = Math.max(
          currentAccumulation.maximumBalance,
          newCurrentBalance
        );

        return new CurrentBalanceMaximumBalance(
          newCurrentBalance,
          newMaximumBalance
        );
      },

      // Combiner.
      (res1, res2) -> {

        final int newCurrentBalance =
          res1.currentBalance +
          res2.currentBalance;

        final int newMaximumBalance = Math.max(
          res1.maximumBalance,
          res2.maximumBalance
        );

        return new CurrentBalanceMaximumBalance(
          newCurrentBalance, newMaximumBalance
        );
      }

    );

    System.out.println("Maximum is: " + currentMaximumBalance.maximumBalance);

Helper class:

class CurrentBalanceMaximumBalance {

  public final int currentBalance;
  public final int maximumBalance;

  public CurrentBalanceMaximumBalance(
    int currentBalance,
    int maximumBalance
  ) {

    this.currentBalance = currentBalance;
    this.maximumBalance = maximumBalance;
  }
}

This is a wrong solution. It might arbitrarily work, but there is no guarantee that it will.

It breaks the interface of reduce. The properties that are broken are associativity for both the accumulator function and the combiner function. It also doesn't require that the stream respects the order of the original transactions.

This makes it possibly dangerous to use, and might well give wrong results depending on what the implementation of reduce happens to be as well as whether the stream respects the original order of the deposits and withdrawals or not.

Using sequential() here is not sufficient, since sequential() is about sequential/parallel execution. An example of a stream that executes sequentially but does not have ordering is a stream created from a HashSet and then have sequential() called on it.

A correct solution

The problem uses the concept of a "current balance", and that is only meaningful when computed from the first transaction and then in order to the end. For instance, if you have the list [-1000, 10, 10, -1000], you cannot start in the middle and then say that the "current balance" was 20 at some point. You must apply the operations reg. "current balance" in the order of the original transactions.

So, one straight-forward solution is to:

Require that the stream respects the original order of transactions, with a defined "encounter order".

Apply forEachOrdered().


问:
How to make one circle inside of another using CSS
I am trying to make one circle inside of another circle using css, but I am having an issue making it completely centered. I am close, but still not there. Any ideas?

```<code><div id="content">
    <h1>Test Circle</h1>
    <div id="outer-circle">
        <div id="inner-circle">
            <span id="inside-content"></span>
        </div>
    </div>
</div>
</code>```

Here is my CSS:

```<code>#outer-circle {
    background: #385a94;
    border-radius: 50%;
    height:500px;
    width:500px;
}
#inner-circle {
    position: relative;
    background: #a9aaab;
    border-radius: 50%;
    height:300px;
    width:300px;
    margin: 0px 0px 0px 100px;
}
</code>```

Also, here is a fiddle:
http://jsfiddle.net/972SF/

答:
If you want to use only one div to add circle inside circle, then use box-shadow.

div {
  border-radius: 50%;
  box-shadow: 0px 0px 0px 10px red, 0px 0px 0px 20px green, 0px 0px 0px 30px yellow, 0px 0px 0px 40px pink;
  width: 100px;
  height:100px;
  margin: 3em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to make one circle inside of another circle using css, but I am having an issue making it completely centered. I am close, but still not there. Any ideas?

Test Circle

Here is my CSS:

#outer-circle {
    background: #385a94;
    border-radius: 50%;
    height:500px;
    width:500px;
}
#inner-circle {
    position: relative;
    background: #a9aaab;
    border-radius: 50%;
    height:300px;
    width:300px;
    margin: 0px 0px 0px 100px;
}

Also, here is a fiddle:
http://jsfiddle.net/972SF/

Body:
If you want to use only one div to add circle inside circle, then use box-shadow.

div {
  border-radius: 50%;
  box-shadow: 0px 0px 0px 10px red, 0px 0px 0px 20px green, 0px 0px 0px 30px yellow, 0px 0px 0px 40px pink;
  width: 100px;
  height:100px;
  margin: 3em;
}

<div></div>


问:
Angular get object from array by id from input
Hello,

I have:

imei.ts

```<code>export default class imei {
    product: String;
    type: String;
    system: String;
    capacity: String;
    serial: String;
    imei: String;
}
</code>```

and array in test.component.ts:

```<code> iphones: imei[] = [
    {product: "iPhone",
    type: "11 Pro Max",
    system: "iOS 13",
    capacity: "128 GB",
    serial: "DNQVXUJWJCLH",
    imei: "35 304509 499369 6"},

    {product: "iPhone",
    type: "6s",
    system: "iOS 12",
    capacity: "32 GB",
    serial: "ANXVSCVWWCBH",
    imei: "41 102109 494369 9"},

    {product: "iPhone",
    type: "5",
    system: "iOS 11",
    capacity: "8 GB",
    serial: "OXQVXWAHJCLH",
    imei: "63 302354 499369 6"}
 ]
</code>```

I want to after input imei in this section:

```<code><div class="container" id="imei" style="height:100vh;" >
    <div class="row justify-content-center">
        <div class="col-12 text-center">
            <img src="assets/warranty.png" alt="">
            <h1>
                Check your warranty for service and support
            </h1>
            <h2>Please tell us your IMEI or Serial number
            </h2>
            <input type="text" placeholder="IMEI or Serial number">
            <a><p>Where I can find my IMEI or Serial number?</p></a>
            <div class="row justify-content-center">
                <button type="submit" class="btn btn-primary btn-lg btn-confirm" [ngxScrollToDuration]=1200
                [ngxScrollTo]="'#specification'" (click)="toggle1()" >Check</button>
            </div>
            <a><img class="mx-auto d-block spec-arrow" src="assets\arrow.png"></a>
        </div>
    </div>
</div>
</code>```

Display data from array with this imei here:

```<code>    <div class="col-12 text-center" *ngFor="let iphone of iphones">
        <img src="assets/iphone.png" alt="">
        <h2>Is that your phone?</h2>
        <h2>Your iPhone Specification:</h2>
        <div class="row justify-content-center">
            <div class="col-xl-2 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: rgb(156, 156, 156);">
                <p>Product:</p>
            </div>
            <div class="col-xl-3 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: #14569d; font-size: 120%;">
                <p>{{iphone.product}}</p>
            </div>
        </div>
        <div class="row justify-content-center">
            <div class="col-xl-2 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: rgb(156, 156, 156);">
                <p>Type:</p>
            </div>
            <div class="col-xl-3 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: #14569d; font-size: 120%;">
                <p>11 Pro Max</p>
            </div>
        </div>
        <div class="row justify-content-center">
            <div class="col-xl-2 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: rgb(156, 156, 156);">
                <p>Operating system:</p>
            </div>
            <div class="col-xl-3 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: #14569d; font-size: 120%;">
                <p>iOS 13</p>
            </div>
        </div>
        <div class="row justify-content-center">
            <div class="col-xl-2 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: rgb(156, 156, 156);">
                <p>Capacity:</p>
            </div>
            <div class="col-xl-3 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: #14569d; font-size: 120%;">
                <p>128 GB</p>
            </div>
        </div>
        <div class="row justify-content-center">
            <div class="col-xl-2 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: rgb(156, 156, 156);">
                <p>Serial number:</p>
            </div>
            <div class="col-xl-3 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: #14569d; font-size: 120%;">
                <p>DNQVXUJWJCLH</p>
            </div>
        </div>
        <div class="row justify-content-center">
            <div class="col-xl-2 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: rgb(156, 156, 156);">
                <p>IMEI:</p>
            </div>
            <div class="col-xl-3 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: #14569d; font-size: 120%;">
                <p>35 304509 499369 6</p>
            </div>
        </div>
        <div class="row justify-content-center">
            <div class="col-12 text-center">
                <button class="btn btn-primary btn-lg btn-confirm " [ngxScrollToDuration]=1200
                    [ngxScrollTo]="'#repair'" (click)="toggle2()">Confirm</button>
            </div>
        </div>
    </div>
</div>
</code>```

Is there a way to do it in simple way? I where looking for an answer but I didn't find right solution.

I don't excepted ready solution - I prefer showing the way or things which I should use

答:
Bind your input IMEI or Serial number with (ngModel).

On Submit, in your .ts file, check IMEI with given array using Array.find().

Store the found array element in a variable.

Display elements of the stored variable.

Body:
Hello,

I have:

imei.ts

export default class imei {
    product: String;
    type: String;
    system: String;
    capacity: String;
    serial: String;
    imei: String;
}

and array in test.component.ts:

 iphones: imei[] = [
    {product: "iPhone",
    type: "11 Pro Max",
    system: "iOS 13",
    capacity: "128 GB",
    serial: "DNQVXUJWJCLH",
    imei: "35 304509 499369 6"},

    {product: "iPhone",
    type: "6s",
    system: "iOS 12",
    capacity: "32 GB",
    serial: "ANXVSCVWWCBH",
    imei: "41 102109 494369 9"},

    {product: "iPhone",
    type: "5",
    system: "iOS 11",
    capacity: "8 GB",
    serial: "OXQVXWAHJCLH",
    imei: "63 302354 499369 6"}
 ]

I want to after input imei in this section:

                Check your warranty for service and support

Please tell us your IMEI or Serial number

            <input type="text" placeholder="IMEI or Serial number">

Where I can find my IMEI or Serial number?

                <button type="submit" class="btn btn-primary btn-lg btn-confirm" [ngxScrollToDuration]=1200
                [ngxScrollTo]="'#specification'" (click)="toggle1()" >Check</button>

Display data from array with this imei here:

Is that your phone?

Your iPhone Specification:

Product:

{{iphone.product}}

Type:

11 Pro Max

Operating system:

iOS 13

Capacity:

128 GB

Serial number:

DNQVXUJWJCLH

IMEI:

35 304509 499369 6

                <button class="btn btn-primary btn-lg btn-confirm " [ngxScrollToDuration]=1200
                    [ngxScrollTo]="'#repair'" (click)="toggle2()">Confirm</button>

Is there a way to do it in simple way? I where looking for an answer but I didn't find right solution.

I don't excepted ready solution - I prefer showing the way or things which I should use


问:
Database in MongoDB connection string
In the MongoDB Nodejs driver, I see some confusion in what the connection URI can be.

On one hand, in the page describing the URI (https://docs.mongodb.com/manual/reference/connection-string/) it says the the path parameter is the "authentication database".

On the other hand, in many of the official examples (http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html#mongoclient-connect) it seems they are using the path parameter as the active database to use (they call db.collection() straight away, without calling .database().

Am I missing something?

答:
TL;DR:

Calling db.collection() immediately after connection only works in versions of the driver less than 3.0.

Details:

Firstly, the official examples you sighted were from MongoDB driver at version 1.4.9, the driver is now at version 3.5.8, I would suggest you check out the latest documentation and examples here.

To clarify the confusion, the database path specified in the connection URI is the authentication database i.e the database used to log in, this is true even for the 1.4.9 version of the driver - reference.

However, the reason for the difference you mentioned, i.e being able to call db.collection() immediately after a connection in some cases is a result of the change in the MongoClient class in version 3 of the driver - reference.

Before version 3, MongoClient.connect would return a DB instance to its call back function and this instance would be referencing the database specified in the path of the connection URI, so you could call db.collection() straight away:

```<code>MongoClient.connect("<connection_URI>", function(err, db) {
  // db is a DB instance, so I can access my collections straight away:
   db.collection('sample_collection').find();
});
</code>```

However, an update was made at version 3 such that, MongoClient.connect now returns a MongoClient instance not a DB instance anymore - reference:

```<code>MongoClient.connect("<connection_URI>", function(err, client) {
  // client is a MongoClient instance, you would have to call
  // the Client.db() method to access your database
  const db = client.db('sample_database');
  // Now you can access your collections
  db.collection('sample_collection').find();
});
</code>```

Title: Database in MongoDB connection string

Body:
TL;DR:

Calling db.collection() immediately after connection only works in versions of the driver less than 3.0.

Details:

Firstly, the official examples you sighted were from MongoDB driver at version 1.4.9, the driver is now at version 3.5.8, I would suggest you check out the latest documentation and examples here.

To clarify the confusion, the database path specified in the connection URI is the authentication database i.e the database used to log in, this is true even for the 1.4.9 version of the driver - reference.

However, the reason for the difference you mentioned, i.e being able to call db.collection() immediately after a connection in some cases is a result of the change in the MongoClient class in version 3 of the driver - reference.

Before version 3, MongoClient.connect would return a DB instance to its call back function and this instance would be referencing the database specified in the path of the connection URI, so you could call db.collection() straight away:

MongoClient.connect("<connection_URI>", function(err, db) {
  // db is a DB instance, so I can access my collections straight away:
   db.collection('sample_collection').find();
});

However, an update was made at version 3 such that, MongoClient.connect now returns a MongoClient instance not a DB instance anymore - reference:

MongoClient.connect("<connection_URI>", function(err, client) {
  // client is a MongoClient instance, you would have to call
  // the Client.db() method to access your database
  const db = client.db('sample_database');
  // Now you can access your collections
  db.collection('sample_collection').find();
});


问:
Super class method and submethods for subclasses in runtime
I have method with super class as argument in main class.

```<code>public class MainClass() {
...
    public void myMethod(MyClass class)
...
</code>```

In runtime this object can be any of its subclasses and it should call different method depending on subclasses in same main class

```<code>public class MainClass() {
...
    public void mySubMethod(MySubClass1 class)

    public void mySubMethod(MuySubClass2 class)
...
</code>```

Of course, I can use instanceOf or Static Factory Pattern with Enum but still it will be (pseudo code)

```<code>public void myMethod(MyClass class) {
if (instanceOf == MySubclass1) mySubMethod((MySubClass1)subClass1Object)
if (instanceOf == MySubclass2) mySubMethod((MySubClass2)subClass2Object)
}
</code>```

In runtime jvm knows which subclass exactly object is and knows for each sub-method argument should be. I don't have control over MyClass, MySubclass1 and MySubclass2,...

But is there any elegant way to achive this?

答:
You could use "double-dispatch" by moving those methods to the various target subclasses themselves.</p>

```<code>interface MyClass {
   void mySubMethod(Something context);
}

public void myMethod(MyClass target){
   target.mySubMethod(this);
}
</code>```

Body:
I have method with super class as argument in main class.

public class MainClass() {
...
    public void myMethod(MyClass class)
...

In runtime this object can be any of its subclasses and it should call different method depending on subclasses in same main class

public class MainClass() {
...
    public void mySubMethod(MySubClass1 class)

    public void mySubMethod(MuySubClass2 class)
...

Of course, I can use instanceOf or Static Factory Pattern with Enum but still it will be (pseudo code)

public void myMethod(MyClass class) {
if (instanceOf == MySubclass1) mySubMethod((MySubClass1)subClass1Object)
if (instanceOf == MySubclass2) mySubMethod((MySubClass2)subClass2Object)
}

In runtime jvm knows which subclass exactly object is and knows for each sub-method argument should be. I don't have control over MyClass, MySubclass1 and MySubclass2,...

But is there any elegant way to achive this?

Body:
You could use "double-dispatch" by moving those methods to the various target subclasses themselves.

interface MyClass {
   void mySubMethod(Something context);
}

public void myMethod(MyClass target){
   target.mySubMethod(this);
}


问:
How to output and format PsObject to multine text box in GUI
Im playing around with a GUI for WMI in powershell script. How do i format a PsObject to output in a multiline textbox so that each property of the PsObject is on its own line?

This is for my own learning purposes - I know there are tools out there for WMI collection :)

答:
You can loop through the properties in your PSObject with ForEach-Object or use inline Format-List as suggested by @Theo

here's the sample code snippet to suite your requirement

```<code>$Form = New-Object System.Windows.Forms.Form
$Form.Size = New-Object System.Drawing.Size(400,400)
$Form.StartPosition = "CenterScreen"

$objTextBox1 = New-Object System.Windows.Forms.TextBox
$objTextBox1.Multiline = $True;
$objTextBox1.Location = New-Object System.Drawing.Size(10,10)
$objTextBox1.Size = New-Object System.Drawing.Size(300,400)
$objTextBox1.Scrollbars = "Vertical"

$Form.Controls.Add($objTextBox1)

$output = Get-ComputerInfo -Property "os*"

$output.PSObject.Properties | ForEach-Object {
    $objTextBox1.Text = $objTextBox1.Text + "$($_.Name): $($_.Value)`r`n";
    #Write-Host "$($_.Name): $($_.Value)`r`n"
}

$form.ShowDialog()| Out-Null
</code>```

Body:
You can loop through the properties in your PSObject with ForEach-Object or use inline Format-List as suggested by @Theo

here's the sample code snippet to suite your requirement

$Form = New-Object System.Windows.Forms.Form
$Form.Size = New-Object System.Drawing.Size(400,400)
$Form.StartPosition = "CenterScreen"

$objTextBox1 = New-Object System.Windows.Forms.TextBox
$objTextBox1.Multiline = $True;
$objTextBox1.Location = New-Object System.Drawing.Size(10,10)
$objTextBox1.Size = New-Object System.Drawing.Size(300,400)
$objTextBox1.Scrollbars = "Vertical"

$Form.Controls.Add($objTextBox1)

$output = Get-ComputerInfo -Property "os*"

$output.PSObject.Properties | ForEach-Object {
    $objTextBox1.Text = $objTextBox1.Text + "$($_.Name): $($_.Value)`r`n";
    #Write-Host "$($_.Name): $($_.Value)`r`n"
}

$form.ShowDialog()| Out-Null


问:
Is there a solution to plot 3D multiple time line series in web application using highcharts or any other libraries
I am trying to plot 3D .NET web charts to show time vs temperature lines with the Z Axis showing the curve for each months. I am looking for a solution which is Similar to the one shown on the images below.

答:
You should be able to achieve it by using the scatter3d series in Highcharts. Because I am not a .NET developer I prepared a basic demo in Highcharts JS how to achieve similar chart.

Demo: https://jsfiddle.net/BlackLabel/r1Lant7p/

```<code>  chart: {
    renderTo: 'container',
    type: 'scatter3d',
    options3d: {
      enabled: true,
      alpha: 10,
      beta: 30,
      depth: 250,
      viewDistance: 5,
      fitToPlot: false,
    }
  },
</code>```

And here is a basic demo of the scatter3d chart in the Highcharts.NET wrapper: https://dotnet.highcharts.com/Highcharts/Demo/Gallery?demo=Scatter3d&theme=default

API: https://dotnet.highcharts.com/Help/Highcharts/html/index.html

Body:
You should be able to achieve it by using the scatter3d series in Highcharts. Because I am not a .NET developer I prepared a basic demo in Highcharts JS how to achieve similar chart.

Demo: https://jsfiddle.net/BlackLabel/r1Lant7p/

  chart: {
    renderTo: 'container',
    type: 'scatter3d',
    options3d: {
      enabled: true,
      alpha: 10,
      beta: 30,
      depth: 250,
      viewDistance: 5,
      fitToPlot: false,
    }
  },

And here is a basic demo of the scatter3d chart in the Highcharts.NET wrapper: https://dotnet.highcharts.com/Highcharts/Demo/Gallery?demo=Scatter3d&theme=default

API: https://dotnet.highcharts.com/Help/Highcharts/html/index.html


问:
Implementing SCD 2 in Informatica without PK defined on the target
How can we implement SCD 2 in informatica when no PK is defined on target table(oracle)?

Implementing SCD type 2 using Dynamic lkp concept which will tag the incoming row as 0,1,2.
Ive associated the SRC ports to the lookup ports and given the conditioning by specifying the "Update Dynamic Cache Condition" ie MD5(SRC Columns)<>MD5(LKP columns) and enabling the "Output Old Value On Update" with "Insert Else Update" property SET and overriding the LKP sql.

Then in the EXP am flagging the incoming record whether to insert/update using which in Router we will define the grps.

From Router INSERT GRP(FLAG = 'INSERT' or FLAG = 'UPDATE') , 1 target instance for new insert.
UPDATE GRP(FLAG = 'UPDATE') connecting to EXP where i tag the old record status as 'N' and doing the Update Override at the second Target instance since no PK defined am doing this.

Every thing is working fine while i check in debugger mode to check the flow , But when there is an updated record old record gets tagged with status 'N' and new record gets inserted in the first pipeline (first target instance) while old record when it flows from UPDATE grp of router its getting updated with the Status as N and end date am making SYSDATE-1 its working in the Expression but its again getting INSERTED in the second target instance which should get updated with status as N and end date(sysdate-1).But its getting inserted with Status Y and end date with defaukt date Can any one help me to figure whats going wrong here?

Note : in the Session level , for TARGET instance 1 its INSERT and for second instance where update should happen its "UPDATE as UPDATE"

Also tried by keeping the Update Strategy in the second pipe keeping DD_UPDATE and treat source as DATA DRIVEN at the session by specifying the PK at the target designer (Infa level not the db level) but No luck

答:
Steps

While performing SCD, you first have to identity the history records and you have to
first update the history records and then insert the new records

You have to use target load plan and set, first your update flow should apply and then insert operation should happen. You will have target load plan in mapping tab

In session task, in properties tab, change Treat source row as to Data driven


问:
What is the cURL command request to generate an mp3 text-to-speech file?
I am not a dev. I'm looking to generate synthetic voices for digital books which I am creating. I would really appreciate some help with the following. After inputting the curl command, what is the next step to generate a sound file? I would greatly appreciate any advice on how to proceed. Thank you.</p>

答:
You can generate audio files from text on your own desktop, depending on which OS your are running:

MacOs: MAC's "say" command to MP3

Ubuntu: https://askubuntu.com/questions/178736/generate-mp3-file-from-espeak

Windows: https://www.microsoft.com/en-us/search?q=text+to+audio (warning: store downloads on your own risk)

If you have a server running, you may use the server to generate the audio:

php: eSpeak to mp3 in php on both windows and linux (online text-to-speech)

nodejs: text to audio file on node.js

python: How can I convert text to speech (mp3 file) in python?


问:
SortedAscending/Descending Styles not working
I'm having trouble with the Sorted Styles in my gridview, they are simply not being applied, be it cellstyle, headerstyle, color etc...

Maybe it's because of the way i'm sorting my dataview? It's like the framework isn't seeing the column as being sorted...

```<code>protected void dgvOpps_Sorting(object sender, GridViewSortEventArgs e)
{
    string sortDirection = "ASC";
    string lastDirection = ViewState["SortDirection"] as string;

    if ((lastDirection != null) && (lastDirection == "ASC"))
        sortDirection = "DESC";

    ViewState["SortDirection"] = sortDirection;
    ViewState["SortExpression"] = e.SortExpression;

    string orderByCol = e.SortExpression;

    DataTable dt;

    if (Session["dgvOppsFilter"] != null)
        dt = ldcrmClient.RetrieveOpportunitiesOfReseller(loggedUser.account_id, (string[])Session["dgvOppsFilter"], new string[0]);
    else dt = ldcrmClient.RetrieveOpportunitiesOfReseller(loggedUser.account_id, new string[0], new string[0]);

    DataView dv = new DataView(dt);
    dv.Sort = e.SortExpression + " " + sortDirection;

    Session.Add("dgvOppsSort", e.SortExpression + " " + sortDirection);

    dgvOpps.DataSource = dv;
    dgvOpps.DataBind();
}
</code>```

答:
Try This:

```<code> protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                if (ViewState["sortDirection"] == null)
                    ViewState["sortDirection"] = "asc";

                if (ViewState["sortExpression"] == null)
                    ViewState["sortExpression"] = "your-column-name";
               // Fill the Grid
            }
        }
        catch (Exception ex)
        {
            //Response.Write(ex.Message);
        }
    }
</code>```

Sorting:

```<code>protected void dgvOpps_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (Convert.ToString(ViewState["sortDirection"]) == "asc")
            ViewState["sortDirection"] = "desc";
        else
            ViewState["sortDirection"] = "asc";

        ViewState["sortExpression"] = e.SortExpression;
// Feetch dt here according to your code
          if (dt.Rows.Count > 0)
            {
                dt.DefaultView.Sort = Convert.ToString(ViewState["sortExpression"]) + " " + Convert.ToString(ViewState["sortDirection"]);
                dgvOpps.DataSource =dt;
                dgvOpps.DataBind();
            }
            else
            {
                dgvOpps.DataSource = null;
                dgvOpps.DataBind();

            }
    }
</code>```

Body:
I'm having trouble with the Sorted Styles in my gridview, they are simply not being applied, be it cellstyle, headerstyle, color etc...

Maybe it's because of the way i'm sorting my dataview? It's like the framework isn't seeing the column as being sorted...

protected void dgvOpps_Sorting(object sender, GridViewSortEventArgs e)
{
    string sortDirection = "ASC";
    string lastDirection = ViewState["SortDirection"] as string;

    if ((lastDirection != null) && (lastDirection == "ASC"))
        sortDirection = "DESC";

    ViewState["SortDirection"] = sortDirection;
    ViewState["SortExpression"] = e.SortExpression;

    string orderByCol = e.SortExpression;

    DataTable dt;

    if (Session["dgvOppsFilter"] != null)
        dt = ldcrmClient.RetrieveOpportunitiesOfReseller(loggedUser.account_id, (string[])Session["dgvOppsFilter"], new string[0]);
    else dt = ldcrmClient.RetrieveOpportunitiesOfReseller(loggedUser.account_id, new string[0], new string[0]);

    DataView dv = new DataView(dt);
    dv.Sort = e.SortExpression + " " + sortDirection;

    Session.Add("dgvOppsSort", e.SortExpression + " " + sortDirection);

    dgvOpps.DataSource = dv;
    dgvOpps.DataBind();
}

Body:
Try This:

 protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                if (ViewState["sortDirection"] == null)
                    ViewState["sortDirection"] = "asc";

                if (ViewState["sortExpression"] == null)
                    ViewState["sortExpression"] = "your-column-name";
               // Fill the Grid
            }
        }
        catch (Exception ex)
        {
            //Response.Write(ex.Message);
        }
    }

Sorting:

protected void dgvOpps_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (Convert.ToString(ViewState["sortDirection"]) == "asc")
            ViewState["sortDirection"] = "desc";
        else
            ViewState["sortDirection"] = "asc";

        ViewState["sortExpression"] = e.SortExpression;
// Feetch dt here according to your code
          if (dt.Rows.Count > 0)
            {
                dt.DefaultView.Sort = Convert.ToString(ViewState["sortExpression"]) + " " + Convert.ToString(ViewState["sortDirection"]);
                dgvOpps.DataSource =dt;
                dgvOpps.DataBind();
            }
            else
            {
                dgvOpps.DataSource = null;
                dgvOpps.DataBind();

            }
    }


答:
Change

To

```<code><input type="text" placeholder="IMEI or Serial number" #imeiInput>
</code>```

then change submit button to :-

```<code><button type="submit" class="btn btn-primary btn-lg btn-confirm" [ngxScrollToDuration]=1200
                [ngxScrollTo]="'#specification'" (click)="toggle1(imeiInput.value)" >Check</button>
</code>```

In Typescript

```<code>public selectedImei;
toggle1(imei) {
  this.selectedImei = this.iphones.find((iphone)=>iphone.imei === imei);
}
</code>```

Use this selected Imei in template below like :-

```<code> <div class="col-12 text-center">
        <img src="assets/iphone.png" alt="">
        <h2>Is that your phone?</h2>
        <h2>Your iPhone Specification:</h2>
        <div class="row justify-content-center">
            <div class="col-xl-2 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: rgb(156, 156, 156);">
                <p>Product:</p>
            </div>
            <div class="col-xl-3 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: #14569d; font-size: 120%;">
                <p>{{selectedImei?.product}}</p>
            </div>
        </div>
        <div class="row justify-content-center">
            <div class="col-xl-2 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: rgb(156, 156, 156);">
                <p>Type:</p>
            </div>
            <div class="col-xl-3 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: #14569d; font-size: 120%;">
                <p>{{selectedImei?.type}}</p>
            </div>
        </div>
        <div class="row justify-content-center">
            <div class="col-xl-2 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: rgb(156, 156, 156);">
                <p>Operating system:</p>
            </div>
            <div class="col-xl-3 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: #14569d; font-size: 120%;">
                <p>{{selectedImei?.system}}</p>
            </div>
        </div>
        <div class="row justify-content-center">
            <div class="col-xl-2 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: rgb(156, 156, 156);">
                <p>Capacity:</p>
            </div>
            <div class="col-xl-3 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: #14569d; font-size: 120%;">
                <p>{{selectedImei?.capacity}}</p>
            </div>
        </div>
        <div class="row justify-content-center">
            <div class="col-xl-2 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: rgb(156, 156, 156);">
                <p>Serial number:</p>
            </div>
            <div class="col-xl-3 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: #14569d; font-size: 120%;">
                <p>{{selectedImei?.serial}}</p>
            </div>
        </div>
        <div class="row justify-content-center">
            <div class="col-xl-2 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: rgb(156, 156, 156);">
                <p>IMEI:</p>
            </div>
            <div class="col-xl-3 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: #14569d; font-size: 120%;">
                <p>{{selectedImei?.imei}}</p>
            </div>
        </div>
        <div class="row justify-content-center">
            <div class="col-12 text-center">
                <button class="btn btn-primary btn-lg btn-confirm " [ngxScrollToDuration]=1200
                    [ngxScrollTo]="'#repair'" (click)="toggle2()">Confirm</button>
            </div>
        </div>
    </div>
</div>
</code>```

Title: Angular get object from array by id from input

Body:
Change

To

<input type="text" placeholder="IMEI or Serial number" #imeiInput>

then change submit button to :-

<button type="submit" class="btn btn-primary btn-lg btn-confirm" [ngxScrollToDuration]=1200
                [ngxScrollTo]="'#specification'" (click)="toggle1(imeiInput.value)" >Check</button>

In Typescript

public selectedImei;
toggle1(imei) {
  this.selectedImei = this.iphones.find((iphone)=>iphone.imei === imei);
}

Use this selected Imei in template below like :-

 <div class="col-12 text-center">
        <img src="assets/iphone.png" alt="">
        <h2>Is that your phone?</h2>
        <h2>Your iPhone Specification:</h2>
        <div class="row justify-content-center">
            <div class="col-xl-2 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: rgb(156, 156, 156);">
                <p>Product:</p>
            </div>
            <div class="col-xl-3 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: #14569d; font-size: 120%;">
                <p>{{selectedImei?.product}}</p>
            </div>
        </div>
        <div class="row justify-content-center">
            <div class="col-xl-2 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: rgb(156, 156, 156);">
                <p>Type:</p>
            </div>
            <div class="col-xl-3 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: #14569d; font-size: 120%;">
                <p>{{selectedImei?.type}}</p>
            </div>
        </div>
        <div class="row justify-content-center">
            <div class="col-xl-2 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: rgb(156, 156, 156);">
                <p>Operating system:</p>
            </div>
            <div class="col-xl-3 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: #14569d; font-size: 120%;">
                <p>{{selectedImei?.system}}</p>
            </div>
        </div>
        <div class="row justify-content-center">
            <div class="col-xl-2 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: rgb(156, 156, 156);">
                <p>Capacity:</p>
            </div>
            <div class="col-xl-3 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: #14569d; font-size: 120%;">
                <p>{{selectedImei?.capacity}}</p>
            </div>
        </div>
        <div class="row justify-content-center">
            <div class="col-xl-2 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: rgb(156, 156, 156);">
                <p>Serial number:</p>
            </div>
            <div class="col-xl-3 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: #14569d; font-size: 120%;">
                <p>{{selectedImei?.serial}}</p>
            </div>
        </div>
        <div class="row justify-content-center">
            <div class="col-xl-2 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: rgb(156, 156, 156);">
                <p>IMEI:</p>
            </div>
            <div class="col-xl-3 col-sm-5 text-xl-left text-md-left text-sm-center"
                style="color: #14569d; font-size: 120%;">
                <p>{{selectedImei?.imei}}</p>
            </div>
        </div>
        <div class="row justify-content-center">
            <div class="col-12 text-center">
                <button class="btn btn-primary btn-lg btn-confirm " [ngxScrollToDuration]=1200
                    [ngxScrollTo]="'#repair'" (click)="toggle2()">Confirm</button>
            </div>
        </div>
    </div>
</div>


问:
Working on a Dynamic table to add and delete rows in Vuejs framework, Below is my table
```<code><div class="card-headerfrm" style="margin:0 0px 15px -20px; overflow: auto">
<form method="post" id="form2" class="form-horizontal" v-on:submit.prevent="submitForm">
<table class="table-hover tbl datatables" style="width:100%;">
  <head>
    <tr class="text-primary table-bordered">
    <td class="text-center tableheader"><b>Name</b></td>
    <td class="text-center tableheader"><b>Email</b></td>
    <td class="text-center tableheader"><b>Contact No</b></td>
    <td class="text-center tableheader"><b>Type</b></td>
    <td class="text-center tableheader"><b>Person Type</b></td>
    <td class="text-center tableheader"><b>Remove</b></td>
  </tr>
</thead>
<tbody v-for="(input,index) in inputs" :key="index">
  {{input}}
  <tr>
    <td>
      <b-form-fieldset>
        <b-input-group>
          <b-form-input
             type="text"
             placeholder="Enter Registered Name"
             v-model="input.name"
             :name="'name'+index"
             v-validate="{required:true, max: 30, regex: /^[a-z\d\-_\s]+$/i}"
             v-bind:class="{'form-control': true, 'error': errors.has('name'+index) }">
          </b-form-input>
        </b-input-group>
        <span v-show="errors.has('name'+index)" class="text-danger">{{ errors.first('name'+index) }}</span>
      </b-form-fieldset>
  </td>
    <td>
      <b-form-fieldset>
        <b-input-group>
          <b-form-input
             type="text"
             placeholder="Enter Email"
             v-model="input.email"
             :name="'email'+index"
           v-validate="{required:true, max: 30, regex: /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/}"
             v-bind:class="{'form-control': true, 'error': errors.has('email'+index) }">
            </b-form-input>
        </b-input-group>
        <span v-show="errors.has('email'+index)" class="text-danger">{{ errors.first('email'+index) }}</span>
      </b-form-fieldset>
  </td>
    <td>
      <b-form-fieldset>
        <b-input-group>
          <b-form-input
             type="text"
             placeholder="Enter Contact No"
             v-model="input.contactno"
             :name="'contactno'+index"
             v-validate="{required:true, regex: /^(0|[+91]{3})?[7-9][0-9]{9}$/}"
             v-bind:class="{'form-control': true, 'error': errors.has('contactno'+index) }">
           </b-form-input>
        </b-input-group>
        <span v-show="errors.has('contactno'+index)" class="text-danger">{{ errors.first('contactno'+index) }}</span>
      </b-form-fieldset>
  </td>
  <td>
    <b-form-fieldset>
      <b-input-group>
        <basic-select
             :options="typeOption"
             :selected-option="selectedType.objectArray[index]"
             v-model="input.type"
             :name="'type'+index"
             placeholder="Select Type"
             @select="typeFunc"
             v-validate="{required:true}"
             v-bind:class="{'form-control': true, 'error': errors.has('type'+index)}">
        </basic-select>
      </b-input-group>
    </b-form-fieldset>
  </td>
  <td>
    <b-form-fieldset>
      <b-input-group>
        <basic-select
             :options="personTypeOption"
             :selected-option="selectedPersonType.objectArray[index]"
             v-model="input.persontype"
             :name="'persontype'+index"
             placeholder="Person Type"
             @select="personTypeFunc"
             v-validate="{required: true}"
             v-bind:class="{'form-control': true, 'error': errors.has('persontype'+index)}">
         </basic-select>
      </b-input-group>
    </b-form-fieldset>
  </td>
  <td class="text-center"><h4><i class="fa fa-minus-circle" @click="removeRow(index)"></i></h4></td>
</tr>
</tbody>
</code>```

Submit

```<code>    export default {
    name:'',
    components:{VueElementLoading, BasicSelect},
    data(){
    return {
    selectedType:{ objectArray:[] },
    selectedPersonType:{ objectArray:[] },
    typeOption:[{
    value:1,
    text: "Operation"
    },
    {
    value:2,
    text: "Technology"
    },
    {
    value:3,
    text: "Finance And Legal"
    }],
    personTypeOption:[{
    value: 1,
    text: "Xpressbees"
    },
    {
    value: 2,
    text: "Client"
    }],
    inputs:[],
    }
    },
    created: function(){

    },
   mounted(){

   },
   methods:{
     typeFunc(cls){
       this.selectedType.objectArray.push(cls)
     },
     personTypeFunc(cls){
       this.selectedPersonType.object.push(cls)
     },
     openList(){
       if(this.inputs.length === 0){
         this.showList = true
         this.inputs.push({
           name:'',
           email:'',
           contactno:'',
           type:'',
           persontype:''
         });
       }else {
           this.addInput()
       }
     },
     addInput() {
       this.inputs.push({
         name:'',
         email:'',
         contactno:'',
         type:'',
         persontype:''
       });
       },
     AddNewFunction() {
       this.showList = true
       this.inputs = [];
       if (this.inputs.length == 0) {
         this.addInput();
       }
     },
     onSubmit: function(event){
       this.$validator.validateAll()
       .then(res =>{
         if (res) {
         this.showList = true
         this.getAllClientsDetails()
       }else {
         return false
       }
       }).catch(err =>{
         console.log("Error Details", err);
       })
     },
     submitForm: function(event){
       this.$validator.validateAll()
       .then(res =>{

         if (res) {
           this.SaveSpockDetails()
         }else {
           return false
         }
       }).catch(err =>{
         console.log("Error Details", err);
       })
     }
        }
      }
</code>```

So I am writing a code in javascript framework (Vuejs) for dynamically add and delete rows from a table. And I want the user to first fill the first opened row(line) and then click on the Add button, then that row goes for a validation check. And if the validation results are true then open second-row otherwise show an error. And to validate field I am using this.$validator.validateAll() function which validates all fields on the submit button.
I have 3 text fields and 2 select fields in the table,
1) Name
2) Email
3) Contact Number
4) Type (select)
5) Person Type (select)

in which 3 input-text fields are working fine but in the select field I am getting a validation error
It shows validation error, even after selected any of the values from the dropdown box.

答:
At least you've got 2 keys with the same name in data() function. Remove first
Or juts edit your data func to:

```<code> data(){
    return {
     selectedTypes:[]
    }
 }
</code>```

And change all callings to this

Body:
<form method="post" id="form2" class="form-horizontal" v-on:submit.prevent="submitForm">

    Name
    Email
    Contact No
    Type
    Person Type
    Remove

  {{input}}

        {{ errors.first('name'+index) }}

        {{ errors.first('email'+index) }}

        {{ errors.first('contactno'+index) }}

        <basic-select
             :options="typeOption"
             :selected-option="selectedType.objectArray[index]"
             v-model="input.type"
             :name="'type'+index"
             placeholder="Select Type"
             @select="typeFunc"
             v-validate="{required:true}"
             v-bind:class="{'form-control': true, 'error': errors.has('type'+index)}">
        </basic-select>

        <basic-select
             :options="personTypeOption"
             :selected-option="selectedPersonType.objectArray[index]"
             v-model="input.persontype"
             :name="'persontype'+index"
             placeholder="Person Type"
             @select="personTypeFunc"
             v-validate="{required: true}"
             v-bind:class="{'form-control': true, 'error': errors.has('persontype'+index)}">
         </basic-select>

Submit

    export default {
    name:'',
    components:{VueElementLoading, BasicSelect},
    data(){
    return {
    selectedType:{ objectArray:[] },
    selectedPersonType:{ objectArray:[] },
    typeOption:[{
    value:1,
    text: "Operation"
    },
    {
    value:2,
    text: "Technology"
    },
    {
    value:3,
    text: "Finance And Legal"
    }],
    personTypeOption:[{
    value: 1,
    text: "Xpressbees"
    },
    {
    value: 2,
    text: "Client"
    }],
    inputs:[],
    }
    },
    created: function(){

    },
   mounted(){

   },
   methods:{
     typeFunc(cls){
       this.selectedType.objectArray.push(cls)
     },
     personTypeFunc(cls){
       this.selectedPersonType.object.push(cls)
     },
     openList(){
       if(this.inputs.length === 0){
         this.showList = true
         this.inputs.push({
           name:'',
           email:'',
           contactno:'',
           type:'',
           persontype:''
         });
       }else {
           this.addInput()
       }
     },
     addInput() {
       this.inputs.push({
         name:'',
         email:'',
         contactno:'',
         type:'',
         persontype:''
       });
       },
     AddNewFunction() {
       this.showList = true
       this.inputs = [];
       if (this.inputs.length == 0) {
         this.addInput();
       }
     },
     onSubmit: function(event){
       this.$validator.validateAll()
       .then(res =>{
         if (res) {
         this.showList = true
         this.getAllClientsDetails()
       }else {
         return false
       }
       }).catch(err =>{
         console.log("Error Details", err);
       })
     },
     submitForm: function(event){
       this.$validator.validateAll()
       .then(res =>{

         if (res) {
           this.SaveSpockDetails()
         }else {
           return false
         }
       }).catch(err =>{
         console.log("Error Details", err);
       })
     }
        }
      }

So I am writing a code in javascript framework (Vuejs) for dynamically add and delete rows from a table. And I want the user to first fill the first opened row(line) and then click on the Add button, then that row goes for a validation check. And if the validation results are true then open second-row otherwise show an error. And to validate field I am using this.$validator.validateAll() function which validates all fields on the submit button.
I have 3 text fields and 2 select fields in the table,
1) Name
2) Email
3) Contact Number
4) Type (select)
5) Person Type (select)

in which 3 input-text fields are working fine but in the select field I am getting a validation error
It shows validation error, even after selected any of the values from the dropdown box.

Body:
At least you've got 2 keys with the same name in data() function. Remove first
Or juts edit your data func to:

 data(){
    return {
     selectedTypes:[]
    }
 }

And change all callings to this


问:
Codility "PermMissingElem" Solution in Javascript
A codility problem asks to find the missing number in zero-indexed array A consisting of N different integers.

E.g.

```<code>  Arr[0] = 2
  Arr[1] = 3
  Arr[2] = 1
  Arr[3] = 4
  Arr[4] = 6
</code>```

I previously submitted a solution that first sorts the array and then performs a forEach function returning the value +1 where the array difference between elements is more than 1, however this doesn't get the 100 points.

Is there a way to improve this?

答:
This got me 100%

```<code>function solution(A) {
if (A.length === 0 || !A) {
    return 1;
}

A.sort((a, b) => a - b);
let count = A[0];
if (count !== 1) { return 1 }
for (let i = 0; i <= A.length; i++) {
    if (A[i + 1] === count + 1) {
        count ++;
        continue
    }
    return count + 1;
}
</code>```

}

Body:
A codility problem asks to find the missing number in zero-indexed array A consisting of N different integers.

E.g.

  Arr[0] = 2
  Arr[1] = 3
  Arr[2] = 1
  Arr[3] = 4
  Arr[4] = 6

I previously submitted a solution that first sorts the array and then performs a forEach function returning the value +1 where the array difference between elements is more than 1, however this doesn't get the 100 points.

Is there a way to improve this?

Body:
This got me 100%

function solution(A) {
if (A.length === 0 || !A) {
    return 1;
}

A.sort((a, b) => a - b);
let count = A[0];
if (count !== 1) { return 1 }
for (let i = 0; i <= A.length; i++) {
    if (A[i + 1] === count + 1) {
        count ++;
        continue
    }
    return count + 1;
}

}


问:
Unable to build Maven project due to Javadoc error?
Has anyone come across a similar Maven error as below?

I am unable to build my project due to the error below. All was working previously fine before I started working on the code.

I did not even work on the below defined interfaces and it seems to be related to Javadoc?

```<code>[ERROR] Failed to execute goal org.apache.maven.plugins:maven-javadoc-plugin:2.9.1:jar (attach-javadocs) on project jonney-project: MavenReportException: Error while creating archive:

[ERROR] Exit code: 1 - /Users/me/Work/myProject/library/src/main/java/com/me/someInterface.java:45: warning: no @return
[ERROR] public abstract boolean searchForDevce();
[ERROR] ^
[ERROR] /Users/me/Work/myProject/src/main/java/com/me/someInterfaceAgain.java:52: warning: no @return
[ERROR] public abstract boolean selectDevice(int pos);
[ERROR] ^
</code>```

答:
As mentioned by @turbanoff since version 3.0.0 the maven-javadoc-plugin config setting <additionalparam> has been replaced by <additionalOptions>

So the plugin defintion in your pom.xml can look like this:

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-javadoc-plugin</artifactId>
    <version>3.2.0</version>
    <configuration>
        <additionalOptions>-Xdoclint:none</additionalOptions>
    </configuration>
</plugin>
</code>```

This configuration will still generate the warnings. So you can and should fix them in your code. But it will now no longer break the maven build.

Body:
Has anyone come across a similar Maven error as below?

I am unable to build my project due to the error below. All was working previously fine before I started working on the code.

I did not even work on the below defined interfaces and it seems to be related to Javadoc?

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-javadoc-plugin:2.9.1:jar (attach-javadocs) on project jonney-project: MavenReportException: Error while creating archive:

[ERROR] Exit code: 1 - /Users/me/Work/myProject/library/src/main/java/com/me/someInterface.java:45: warning: no @return
[ERROR] public abstract boolean searchForDevce();
[ERROR] ^
[ERROR] /Users/me/Work/myProject/src/main/java/com/me/someInterfaceAgain.java:52: warning: no @return
[ERROR] public abstract boolean selectDevice(int pos);
[ERROR] ^

Body:
As mentioned by @turbanoff since version 3.0.0 the maven-javadoc-plugin config setting <additionalparam> has been replaced by <additionalOptions>

So the plugin defintion in your pom.xml can look like this:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-javadoc-plugin</artifactId>
    <version>3.2.0</version>
    <configuration>
        <additionalOptions>-Xdoclint:none</additionalOptions>
    </configuration>
</plugin>

This configuration will still generate the warnings. So you can and should fix them in your code. But it will now no longer break the maven build.


问:
Loops in R, Looping a specific ISIN for multiple operations
For my bachelor project I conduct a performance analysis in R. Unfortunately I have no experience with loops and could not find any suitable solutions.

I got a dataframe with daily data which is divided into 3 different volumes/ sizes. For one stock I need about 2000 lines of code to analyze it on a weekly basis. In my dataframe there are about 99 shares in 3 different sizes, so I would have to copy/paste the ISIN number every time.

To get an impression here the code:

```<code>w01.2016_DE0005089031 <- df_DE0005089031 %>%
  dplyr::select(Date, ClosingPrice ) %>%
  dplyr::filter(Date >= as.Date("2016-01-04") & Date <= as.Date("2016-01-10"))

w01.2016_DE0005089031 <- log((w01.2016_DE0005089031[ nrow(w01.2016_DE0005089031),2]) / w01.2016_DE0005089031[1,2])
.
.up to
.
w18.2020_DE0005089031 <- df_DE0005089031 %>%
  dplyr::select(Date, ClosingPrice ) %>%
  dplyr::filter(Date >= as.Date("2020-04-27") & Date <= as.Date("2020-04-30"))

w18.2020_DE0005089031 <- log((w18.2020_DE0005089031[ nrow(w18.2020_DE0005089031),2]) / w18.2020_DE0005089031[1,2])
</code>```

and

```<code>df01_w01_2016_SmallCap <- df %>%
  dplyr::select(Underlying, Date, Size, ClosingPrice, NumberOfBuyers, NumberOfSellers) %>%
  dplyr::filter(Underlying == "DE0005089031", Size == "SmallCap", Date >= as.Date("2016-01-04") & Date <= as.Date("2016-01-10"))
.
.up to
.
df01_w18_2020_SmallCap <- df %>%
  dplyr::select(Underlying, Date, Size, ClosingPrice, NumberOfBuyers, NumberOfSellers) %>%
  dplyr::filter(Underlying == "DE0005089031", Size == "SmallCap", Date >= as.Date("2019-04-27") & Date <= as.Date("2019-03-30"))
</code>```

in addition there are various merges and analysis.

Is it possible to write a loop so that R does the same operation for the other 99 ISIN numbers (e.g. DE0005089031, DE000KGX8881, DE0006070006, etc...) without copy/paste and doing them all by hand?

I am thankful for any help. :)

Edit2:
my df looks like this:

```<code>Underlying       Date ClosingPrice      Size NumberOfBuyers NumberOfSellers
DE0005089031 04.01.2016      49.5010  SmallCap              0               0
DE0005089031 04.01.2016      49.5010 MediumCap              0               0
DE0005089031 04.01.2016      49.5010  LargeCap              1               2
DE0005089031 05.01.2016      49.7855  SmallCap              0               0
DE0005089031 05.01.2016      49.7855 MediumCap              0               1
DE0005089031 05.01.2016      49.7855  LargeCap              0               0
.
.up to
.
 Underlying       Date ClosingPrice      Size NumberOfBuyers NumberOfSellers
NL0012169213 29.04.2020        38.60 MediumCap              0               0
NL0012169213 29.04.2020        38.60  LargeCap              0               0
NL0012169213 29.04.2020        38.60  SmallCap              0               1
NL0012169213 30.04.2020        37.79 MediumCap              0               0
NL0012169213 30.04.2020        37.79  LargeCap              1               0
NL0012169213 30.04.2020        37.79  SmallCap              1               1
</code>```

It has 412539 obs. of 7 variables with 99 shares

答:
As @Ronak Shah pointed out, you should take a look at group_by which groups your data according to a column (in your case underlying) and then the subsequent analysis is done. However, one can simplify also the first part of your analysis. You want your analysis done for every week, so first calculate the week (using the code from here) and then also group by week. With summarise, you only get the result of your calculations. Try to get a better grip of what dplyr can do.

```<code>library(dplyr)
library(lubridate)

data_raw <- "Underlying       Date ClosingPrice      Size NumberOfBuyers NumberOfSellers
DE0005089031 04.01.2016      49.5010  SmallCap              0               0
DE0005089031 04.01.2016      49.5010 MediumCap              0               0
DE0005089031 04.01.2016      49.5010  LargeCap              1               2
DE0005089031 05.01.2016      49.7855  SmallCap              0               0
DE0005089031 05.01.2016      49.7855 MediumCap              0               1
DE0005089031 05.01.2016      49.7855  LargeCap              0               0
DE0005089031 14.01.2016      49.5010  SmallCap              0               0
DE0005089031 14.01.2016      59.5010 MediumCap              0               0
DE0005089031 14.01.2016      69.5010  LargeCap              1               2
DE0005089031 15.01.2016      79.7855  SmallCap              0               0
DE0005089031 15.01.2016      89.7855 MediumCap              0               1
DE0005089031 15.01.2016      99.7855  LargeCap              0               0"

data <- read.table(text = data_raw, header = TRUE)

data %>%
  mutate(Date = as.Date(Date, format = "%d.%m.%Y"),
         week = (year(Date) - year(min(Date)))*52 +
           week(Date) - week(min(Date))) %>%
  group_by(Underlying, week) %>%
  summarise(calculation = log(ClosingPrice[1] / ClosingPrice[n()]))
# A tibble: 3 x 3
# Groups:   Underlying [1]
  Underlying    week calculation
  <fct>        <dbl>       <dbl>
1 DE0005089031     0    -0.00573
2 DE0005089031     1    -0.339
3 DE0005089031     2    -0.224
</code>```

Body:
For my bachelor project I conduct a performance analysis in R. Unfortunately I have no experience with loops and could not find any suitable solutions.

I got a dataframe with daily data which is divided into 3 different volumes/ sizes. For one stock I need about 2000 lines of code to analyze it on a weekly basis. In my dataframe there are about 99 shares in 3 different sizes, so I would have to copy/paste the ISIN number every time.

To get an impression here the code:

w01.2016_DE0005089031 <- df_DE0005089031 %>%
  dplyr::select(Date, ClosingPrice ) %>%
  dplyr::filter(Date >= as.Date("2016-01-04") & Date <= as.Date("2016-01-10"))

w01.2016_DE0005089031 <- log((w01.2016_DE0005089031[ nrow(w01.2016_DE0005089031),2]) / w01.2016_DE0005089031[1,2])
.
.up to
.
w18.2020_DE0005089031 <- df_DE0005089031 %>%
  dplyr::select(Date, ClosingPrice ) %>%
  dplyr::filter(Date >= as.Date("2020-04-27") & Date <= as.Date("2020-04-30"))

w18.2020_DE0005089031 <- log((w18.2020_DE0005089031[ nrow(w18.2020_DE0005089031),2]) / w18.2020_DE0005089031[1,2])

and

df01_w01_2016_SmallCap <- df %>%
  dplyr::select(Underlying, Date, Size, ClosingPrice, NumberOfBuyers, NumberOfSellers) %>%
  dplyr::filter(Underlying == "DE0005089031", Size == "SmallCap", Date >= as.Date("2016-01-04") & Date <= as.Date("2016-01-10"))
.
.up to
.
df01_w18_2020_SmallCap <- df %>%
  dplyr::select(Underlying, Date, Size, ClosingPrice, NumberOfBuyers, NumberOfSellers) %>%
  dplyr::filter(Underlying == "DE0005089031", Size == "SmallCap", Date >= as.Date("2019-04-27") & Date <= as.Date("2019-03-30"))

in addition there are various merges and analysis.

Is it possible to write a loop so that R does the same operation for the other 99 ISIN numbers (e.g. DE0005089031, DE000KGX8881, DE0006070006, etc...) without copy/paste and doing them all by hand?

I am thankful for any help. :)

Edit2:
my df looks like this:

Underlying       Date ClosingPrice      Size NumberOfBuyers NumberOfSellers
DE0005089031 04.01.2016      49.5010  SmallCap              0               0
DE0005089031 04.01.2016      49.5010 MediumCap              0               0
DE0005089031 04.01.2016      49.5010  LargeCap              1               2
DE0005089031 05.01.2016      49.7855  SmallCap              0               0
DE0005089031 05.01.2016      49.7855 MediumCap              0               1
DE0005089031 05.01.2016      49.7855  LargeCap              0               0
.
.up to
.
 Underlying       Date ClosingPrice      Size NumberOfBuyers NumberOfSellers
NL0012169213 29.04.2020        38.60 MediumCap              0               0
NL0012169213 29.04.2020        38.60  LargeCap              0               0
NL0012169213 29.04.2020        38.60  SmallCap              0               1
NL0012169213 30.04.2020        37.79 MediumCap              0               0
NL0012169213 30.04.2020        37.79  LargeCap              1               0
NL0012169213 30.04.2020        37.79  SmallCap              1               1

It has 412539 obs. of 7 variables with 99 shares

Body:
As @Ronak Shah pointed out, you should take a look at group_by which groups your data according to a column (in your case underlying) and then the subsequent analysis is done. However, one can simplify also the first part of your analysis. You want your analysis done for every week, so first calculate the week (using the code from here) and then also group by week. With summarise, you only get the result of your calculations. Try to get a better grip of what dplyr can do.

library(dplyr)
library(lubridate)

data_raw <- "Underlying       Date ClosingPrice      Size NumberOfBuyers NumberOfSellers
DE0005089031 04.01.2016      49.5010  SmallCap              0               0
DE0005089031 04.01.2016      49.5010 MediumCap              0               0
DE0005089031 04.01.2016      49.5010  LargeCap              1               2
DE0005089031 05.01.2016      49.7855  SmallCap              0               0
DE0005089031 05.01.2016      49.7855 MediumCap              0               1
DE0005089031 05.01.2016      49.7855  LargeCap              0               0
DE0005089031 14.01.2016      49.5010  SmallCap              0               0
DE0005089031 14.01.2016      59.5010 MediumCap              0               0
DE0005089031 14.01.2016      69.5010  LargeCap              1               2
DE0005089031 15.01.2016      79.7855  SmallCap              0               0
DE0005089031 15.01.2016      89.7855 MediumCap              0               1
DE0005089031 15.01.2016      99.7855  LargeCap              0               0"

data <- read.table(text = data_raw, header = TRUE)

data %>%
  mutate(Date = as.Date(Date, format = "%d.%m.%Y"),
         week = (year(Date) - year(min(Date)))*52 +
           week(Date) - week(min(Date))) %>%
  group_by(Underlying, week) %>%
  summarise(calculation = log(ClosingPrice[1] / ClosingPrice[n()]))
# A tibble: 3 x 3
# Groups:   Underlying [1]
  Underlying    week calculation
  <fct>        <dbl>       <dbl>
1 DE0005089031     0    -0.00573
2 DE0005089031     1    -0.339
3 DE0005089031     2    -0.224


问:
Shading of round objects after 'model.setThemingColor(dbId, color, true)'
I have some round elements in a model. When trying to colorize those with model.setThemingColor(dbId, color, true); then shading of the elements becomes fairly bad and the object hard to understand.

My question for a fix is then 2 different questions:

Is it possible to use the normal shading of objects on top of the model.setThemingColor(dbId, color, true); to still get shadows etc.?

Is it possible to set a tolerance for when edges should be drawn between faces? I assume this is based on som angle tolerance to avoid having too many edges in the model.

I have already tried using both loading option isAEC: true and viewer.setDisplayEdges(true) without luck.

I appreciate any advice that might push me in the right direction.

答:
I'd believe setThemingColor goes with customized mesh setting which ignores the effect of outline. I think setMaterial can  be of use. Actually, it is often used to define custom textures or transparency.

I'd think the code below could be a workaround, but with my test, it does not work with some models. When it works, the effect is like the attached image. I am checking with team and will update the answer accordingly.

```<code>//select an object
var sel = NOP_VIEWER.getSelection()
console.log('sel Id:'+sel[0])
var tree = NOP_VIEWER.model.getInstanceTree()
tree.enumNodeFragments(sel[0], (fragId) =>{
console.log('fragId:'+fragId)

var updatedM = null
var cloneM_name = 'model:'+ NOP_VIEWER.model.id.toString() + '|frag:' + fragId.toString();
console.log('cloneM_name:'+ cloneM_name)

if(cloneM_name in NOP_VIEWER.impl.matman()._materials)
{
    updatedM = NOP_VIEWER.impl.matman()._materials[cloneM_name]
    updatedM.color = new THREE.Color(1,1,0) //my color
    updatedM.needsUpdate = true;
}else{
     console.log('add new material:'+ cloneM_name)
     updatedM = NOP_VIEWER.model.getFragmentList().getMaterial(fragId).clone();
     updatedM.color = new THREE.Color(1,1,0) //my color
     updatedM.needsUpdate = true;
     //add new material for this fragment
     NOP_VIEWER.impl.matman().addMaterial(cloneM_name,updatedM,true)
}
NOP_VIEWER.model.getFragmentList().setMaterial(fragId,updatedM)
NOP_VIEWER.impl.invalidate(true,true,false)
 })
</code>```

Body:
I'd believe setThemingColor goes with customized mesh setting which ignores the effect of outline. I think setMaterial can  be of use. Actually, it is often used to define custom textures or transparency.

I'd think the code below could be a workaround, but with my test, it does not work with some models. When it works, the effect is like the attached image. I am checking with team and will update the answer accordingly.

//select an object
var sel = NOP_VIEWER.getSelection()
console.log('sel Id:'+sel[0])
var tree = NOP_VIEWER.model.getInstanceTree()
tree.enumNodeFragments(sel[0], (fragId) =>{
console.log('fragId:'+fragId)

var updatedM = null
var cloneM_name = 'model:'+ NOP_VIEWER.model.id.toString() + '|frag:' + fragId.toString();
console.log('cloneM_name:'+ cloneM_name)

if(cloneM_name in NOP_VIEWER.impl.matman()._materials)
{
    updatedM = NOP_VIEWER.impl.matman()._materials[cloneM_name]
    updatedM.color = new THREE.Color(1,1,0) //my color
    updatedM.needsUpdate = true;
}else{
     console.log('add new material:'+ cloneM_name)
     updatedM = NOP_VIEWER.model.getFragmentList().getMaterial(fragId).clone();
     updatedM.color = new THREE.Color(1,1,0) //my color
     updatedM.needsUpdate = true;
     //add new material for this fragment
     NOP_VIEWER.impl.matman().addMaterial(cloneM_name,updatedM,true)
}
NOP_VIEWER.model.getFragmentList().setMaterial(fragId,updatedM)
NOP_VIEWER.impl.invalidate(true,true,false)
 })


问:
How to get only visible markers?
Is possible to get only the visible markers? Is there any function for this?

This is the function where I have the bounds:

```<code>hereMap.addEventListener('mapviewchangeend', (evt) => {
        var bounds = hereMap.getViewModel().getLookAtData().bounds;

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

答: Can you please to know what visible marker actually implies ? however if you want to limit the visibility of markers, GeoCoordinates can be specified for a bounding box and passed in mapview, that can limit the visibility of map in the view. Also you can then set the visibility of inside markers to true. </p>

Title: How to get only visible markers?

Body:
Is possible to get only the visible markers? Is there any function for this?

This is the function where I have the bounds:

hereMap.addEventListener('mapviewchangeend', (evt) => {
        var bounds = hereMap.getViewModel().getLookAtData().bounds;

}, false);


问:
Unable to overwrite FFMPEG's encoder tag
I'm writing a small script in python that calls ffmpeg, the script works fine but I'm unable to prevent FFMPEG from overwriting the encoder tag with it's own 'Lavf58.29.100' encoder.

I tried capturing the input attributes as a varible using FFPROBE and explicitly writing the source encoder to the encoder tag, but it still transcodes with 'Lavf58.29.100' on the output file.

```<code>import subprocess

file = 'File_in.wav'

attributes = subprocess.Popen(['ffprobe', file], stdout = subprocess.PIPE, stderr = subprocess.STDOUT)

for x in attributes.stdout.readlines():
    x = x.decode(encoding='utf-8')
    if 'Stream' in x:
        bit_depth = x[24:33]

    if 'encoder' in x:
        encoder = x[22:-1]

subprocess.call(['ffmpeg', '-i', file, '-af', 'areverse', '-c:a', bit_depth, '-metadata:s:a', 'encoder=' + encoder, 'File_out.wav'])

</code>```

Here is the ffmpeg command outside of python:

```<code>ffmpeg -i 'File_in.wav' -af areverse -c:a pcm_s24le -metadata:s:a encoder='WaveLab Pro 10.0.10' 'File_out.wav'
</code>```

From MediaInfo:

Souce file - "Encoded_Application": "WaveLab Pro 10.0.10"

Output file - "Encoded_Application": "Lavf58.29.100"

Maintaining file provenace is very important so I can't have the source metadata changed.  Does anyone know a way around this?  FFMPEG seems to accept other attributes but not the encoder tag.

答:
From what I found this default behaviour can't be changed in ffmpeg - the only way around it is to use BWF MetaEdit to re-write the input encoder, after ffmpeg has finished processing.

```<code>import os
import glob
import subprocess

dir = os.getcwd()
os.makedirs(f'{dir}/_reversed', exist_ok=True)
rev_out = dir + r'/_reversed'

get_files = glob.glob(dir + '/*.wav')

def reverse_file():
    for i in get_files:
        file = i
        get_filename = os.path.splitext(str(i))[0]
        filename_only = os.path.basename(get_filename)

        attributes = subprocess.Popen(['ffprobe', file], stdout = subprocess.PIPE, stderr = subprocess.STDOUT)

    for x in attributes.stdout.readlines():
        x = x.decode(encoding='utf-8')
        if 'encoder' in x:
            encoder = x[22:-1]

        if 'Stream' in x:
            bit_depth = x[24:33]

    subprocess.call(['ffmpeg', '-i', file, '-af', 'areverse', '-c:a', bit_depth, rev_out + '/' + filename_only + '.wav'])

    subprocess.call(['bwfmetaedit', rev_out + '/' + filename_only + '.wav', '-a', '--ISFT=' + encoder])

reverse_file()
</code>```

Also here - https://github.com/realgoodegg/FFMPEG-batch-reverse

Body:
I'm writing a small script in python that calls ffmpeg, the script works fine but I'm unable to prevent FFMPEG from overwriting the encoder tag with it's own 'Lavf58.29.100' encoder.

I tried capturing the input attributes as a varible using FFPROBE and explicitly writing the source encoder to the encoder tag, but it still transcodes with 'Lavf58.29.100' on the output file.

import subprocess

file = 'File_in.wav'

attributes = subprocess.Popen(['ffprobe', file], stdout = subprocess.PIPE, stderr = subprocess.STDOUT)

for x in attributes.stdout.readlines():
    x = x.decode(encoding='utf-8')
    if 'Stream' in x:
        bit_depth = x[24:33]

    if 'encoder' in x:
        encoder = x[22:-1]

subprocess.call(['ffmpeg', '-i', file, '-af', 'areverse', '-c:a', bit_depth, '-metadata:s:a', 'encoder=' + encoder, 'File_out.wav'])

Here is the ffmpeg command outside of python:

ffmpeg -i 'File_in.wav' -af areverse -c:a pcm_s24le -metadata:s:a encoder='WaveLab Pro 10.0.10' 'File_out.wav'

From MediaInfo:

Souce file - "Encoded_Application": "WaveLab Pro 10.0.10"

Output file - "Encoded_Application": "Lavf58.29.100"

Maintaining file provenace is very important so I can't have the source metadata changed.  Does anyone know a way around this?  FFMPEG seems to accept other attributes but not the encoder tag.

Body:
From what I found this default behaviour can't be changed in ffmpeg - the only way around it is to use BWF MetaEdit to re-write the input encoder, after ffmpeg has finished processing.

import os
import glob
import subprocess

dir = os.getcwd()
os.makedirs(f'{dir}/_reversed', exist_ok=True)
rev_out = dir + r'/_reversed'

get_files = glob.glob(dir + '/*.wav')

def reverse_file():
    for i in get_files:
        file = i
        get_filename = os.path.splitext(str(i))[0]
        filename_only = os.path.basename(get_filename)

        attributes = subprocess.Popen(['ffprobe', file], stdout = subprocess.PIPE, stderr = subprocess.STDOUT)

    for x in attributes.stdout.readlines():
        x = x.decode(encoding='utf-8')
        if 'encoder' in x:
            encoder = x[22:-1]

        if 'Stream' in x:
            bit_depth = x[24:33]

    subprocess.call(['ffmpeg', '-i', file, '-af', 'areverse', '-c:a', bit_depth, rev_out + '/' + filename_only + '.wav'])

    subprocess.call(['bwfmetaedit', rev_out + '/' + filename_only + '.wav', '-a', '--ISFT=' + encoder])

reverse_file()

Also here - https://github.com/realgoodegg/FFMPEG-batch-reverse