问:
How does one end a function in dart similar to in JS typing return
In Javascript when I want to end a function I usually write return, but in the dart, if I do that then the function asks for a return statement at the end of each branch which is messy.

```<code>Function createCategory(File image) {
    String title = _categoryTitle.value;
    if(image == null || title == null || title.length == 0) {
      return null;
    }
    CategoryModel newCategory = new CategoryModel();
    if(_categories.value == null) {
      _categories.sink.add([newCategory]);
    }
    return null;
  }
</code>```

What is the correct way to do this in dart?

答:
I think your confusion comes from that your method is valid Dart code but does not really do what I guess you think. Your method has the following signature:

```<code>Function createCategory(File image) {
</code>```

This means your method is named createCategory, takes one argument of the type File and returns a Function. Since you have marked the method to return a Function, then Dart will tell you it is a problem if you just return; since this is properly not what you wanted.

If your method is not going to return any value, then you want to mark this with the return type of void like:

```<code>void createCategory(File image) {
  String title = _categoryTitle.value;
  if (image == null || title == null || title.length == 0) {
    return;
  }
  CategoryModel newCategory = new CategoryModel();
  if (_categories.value == null) {
    _categories.sink.add([newCategory]);
  }
  return;
}
</code>```

I should note, that the last return can be skipped since Dart will automatically add return; at the end of a function if it is missing.

Body:
In Javascript when I want to end a function I usually write return, but in the dart, if I do that then the function asks for a return statement at the end of each branch which is messy.

Function createCategory(File image) {
    String title = _categoryTitle.value;
    if(image == null || title == null || title.length == 0) {
      return null;
    }
    CategoryModel newCategory = new CategoryModel();
    if(_categories.value == null) {
      _categories.sink.add([newCategory]);
    }
    return null;
  }

What is the correct way to do this in dart?

Body:
I think your confusion comes from that your method is valid Dart code but does not really do what I guess you think. Your method has the following signature:

Function createCategory(File image) {

This means your method is named createCategory, takes one argument of the type File and returns a Function. Since you have marked the method to return a Function, then Dart will tell you it is a problem if you just return; since this is properly not what you wanted.

If your method is not going to return any value, then you want to mark this with the return type of void like:

void createCategory(File image) {
  String title = _categoryTitle.value;
  if (image == null || title == null || title.length == 0) {
    return;
  }
  CategoryModel newCategory = new CategoryModel();
  if (_categories.value == null) {
    _categories.sink.add([newCategory]);
  }
  return;
}

I should note, that the last return can be skipped since Dart will automatically add return; at the end of a function if it is missing.


来源: stackexchange

问:
Getting Cloud Watch Logs according to the region in which I work
I am monitoring application logs in Cloud Watch using custom metrics. I get those logs in UTC in Cloud Watch Logs. I work from India but I use the Sydney region because that is my client location.

As far as I know, there is a possibility of getting them either in UTC or our local time.When I select my local time, it shows according to Indian Standard Time.

Is there any possibility of getting those logs according to Sydney Timings? Please suggest.

答:
You can add a region setting into your local aws config which should be [userHome].aws\config:</p>

```<code>[default]
region = us-east-1
# please change to your region
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can add a region setting into your local aws config which should be [userHome].aws\config:

[default]
region = us-east-1
# please change to your region

ContentLicense: CC BY-SA 4.0


问:
Flushing footer to bottom of the page, twitter bootstrap
I am generally familiar with the technique of flushing a footer using css.

But I am having some trouble getting this approach to work for Twitter bootstrap, most likely due to the fact that Twitter bootstrap is responsive in nature. Using Twitter bootstrap I am not able to get the footer to flush to the bottom of the page using the approach described in the above blog post.

答:
this works well

html

```<code><footer></footer>
</code>```

css

```<code>html {
  position: relative;
  min-height: 100%;
  padding-bottom:90px;
}
body {
  margin-bottom: 90px;
}
footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 90px;
}
</code>```

Body:
this works well

html

<footer></footer>

css

html {
  position: relative;
  min-height: 100%;
  padding-bottom:90px;
}
body {
  margin-bottom: 90px;
}
footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 90px;
}


问:
Doctrine ManyToOne Relation not finding data with findBy method
I have a Article table that is allowed to have many comments.

And when i use findBy it does not find anything for that Article.

Here is my show Action.

```<code>$comments = $commentRepository->findBy(['article' => $article]);
dump($comments);die;
</code>```

which just outputs-.

```<code>ArticleController.php on line 52:
[]
</code>```

When i do findAll however i get 20 Results which look like this

```<code>$allComments = $commentRepository->findAll();
dump($allComments);die;

  0 => Comment^ {#881 ▼
-id: 1
-authorName: "Author name here"
-content: "Here is the comment content"
-article: Article^ {#809 ▼
  +__isInitialized__: false
  -id: 117
  -title: null
  -slug: null
  -content: null
  -publishedAt: null
  -author: null
  -heartCount: 0
  -imageFilename: null
  -createdAt: null
  -updatedAt: null
  -comments: null
   …2
}
</code>```

Here is the complete showAction method

```<code>/**
 * @Route("/news/{article}",
 *      name="article_show")
 *
 * @param Article $article
 * @param SlackClient $slack
 * @param EntityManagerInterface $entityManager
 * @param CommentRepository $commentRepository
 * @return \Symfony\Component\HttpFoundation\Response
 * @throws \Http\Client\Exception
 * @throws \Nexy\Slack\Exception\SlackApiException
 */
public function show( $article,
                     SlackClient $slack,
                     EntityManagerInterface $entityManager,
                     CommentRepository $commentRepository

)
{

    $allComments = $commentRepository->findAll();

    $comments = $commentRepository->findBy(['article' => $article]);
    dump($allComments);die;

    $repository = $entityManager->getRepository(Article::class);

    /**
     * @var Article $article
     */
    $articleResult = $repository->findOneBy(['slug' => $article]);
    if (!$articleResult) {
        throw $this->createNotFoundException('No ' . $article . ' found');
    }
</code>```

Not sure if needed but here is my Article and Comment Entitiy just to make sure i have verything here.

```<code><?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * @ORM\Entity(repositoryClass="App\Repository\ArticleRepository")
 */
class Article
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $title;

    /**
     * @Gedmo\Slug(fields={"title"})
     * @ORM\Column(type="string", length=100, unique=true)
     */
    private $slug;

    /**
     * @ORM\Column(type="text", nullable=true)
     */
    private $content;

    /**
     * @ORM\Column(type="datetime", nullable=true)
     */
    private $publishedAt;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $author;

    /**
     * @ORM\Column(type="integer")
     */
    private $heartCount = 0;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $imageFilename;

    /**
     * @ORM\Column(type="datetime")
     * @Gedmo\Timestampable(on="create")
     */
    private $createdAt;

    /**
     * @ORM\Column(type="datetime")
     * @Gedmo\Timestampable(on="update")
     */
    private $updatedAt;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Comment", mappedBy="article")
     */
    private $comments;

    public function __construct()
    {
        $this->comments = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getTitle(): ?string
    {
        return $this->title;
    }

    public function setTitle(string $title): self
    {
        $this->title = $title;

        return $this;
    }

    public function getSlug(): ?string
    {
        return $this->slug;
    }

    public function setSlug(string $slug): self
    {
        $this->slug = $slug;

        return $this;
    }

    public function getContent(): ?string
    {
        return $this->content;
    }

    public function setContent(?string $content): self
    {
        $this->content = $content;

        return $this;
    }

    public function getPublishedAt(): ?\DateTimeInterface
    {
        return $this->publishedAt;
    }

    public function setPublishedAt(?\DateTimeInterface $publishedAt): self
    {
        $this->publishedAt = $publishedAt;

        return $this;
    }

    public function getAuthor(): ?string
    {
        return $this->author;
    }

    public function setAuthor(string $author): self
    {
        $this->author = $author;

        return $this;
    }

    public function getHeartCount(): ?int
    {
        return $this->heartCount;
    }

    public function setHeartCount(int $heartCount): self
    {
        $this->heartCount = $heartCount;

        return $this;
    }

    public function getImageFilename(): ?string
    {
        return $this->imageFilename;
    }

    public function setImageFilename(?string $imageFilename): self
    {
        $this->imageFilename = $imageFilename;

        return $this;
    }

    public function getCreatedAt(): ?\DateTimeInterface
    {
        return $this->createdAt;
    }

    public function setCreatedAt(\DateTimeInterface $createdAt): self
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    public function getUpdatedAt(): ?\DateTimeInterface
    {
        return $this->updatedAt;
    }

    public function setUpdatedAt(\DateTimeInterface $updatedAt): self
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * @return Collection|Comment[]
     */
    public function getComments(): Collection
    {
        return $this->comments;
    }

    public function addComment(Comment $comment): self
    {
        if (!$this->comments->contains($comment)) {
            $this->comments[] = $comment;
            $comment->setArticle($this);
        }

        return $this;
    }

    public function removeComment(Comment $comment): self
    {
        if ($this->comments->contains($comment)) {
            $this->comments->removeElement($comment);
            // set the owning side to null (unless already changed)
            if ($comment->getArticle() === $this) {
                $comment->setArticle(null);
            }
        }

        return $this;
    }
}
</code>```

and the Comments Entitiy.

```<code><?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Timestampable\Traits\TimestampableEntity;

/**
 * @ORM\Entity(repositoryClass="App\Repository\CommentRepository")
 */
class Comment
{

    use TimestampableEntity;

    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $authorName;

    /**
     * @ORM\Column(type="text")
     */
    private $content;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Article", inversedBy="comments")
     * @ORM\JoinColumn(nullable=false)
     */
    private $article;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getAuthorName(): ?string
    {
        return $this->authorName;
    }

    public function setAuthorName(string $authorName): self
    {
        $this->authorName = $authorName;

        return $this;
    }

    public function getContent(): ?string
    {
        return $this->content;
    }

    public function setContent(string $content): self
    {
        $this->content = $content;

        return $this;
    }

    public function getArticle(): ?article
    {
        return $this->article;
    }

    public function setArticle(?article $article): self
    {
        $this->article = $article;

        return $this;
    }
}
</code>```

Please let me know if you need any other information

答:
The problem lies in showAction method.

You want to take a look at $article argument. Phpdoc says it will be instance of Article but it won't be.

Here:

```<code>$articleResult = $repository->findOneBy(['slug' => $article]);
</code>```

You assume that $article contains string representing slug.

So you search for comments by article slug and comments don't contain this information. You want to fetch them by article id.

Body:
I have a Article table that is allowed to have many comments.

And when i use findBy it does not find anything for that Article.

Here is my show Action.

$comments = $commentRepository->findBy(['article' => $article]);
dump($comments);die;

which just outputs-.

ArticleController.php on line 52:
[]

When i do findAll however i get 20 Results which look like this

$allComments = $commentRepository->findAll();
dump($allComments);die;

  0 => Comment^ {#881 ▼
-id: 1
-authorName: "Author name here"
-content: "Here is the comment content"
-article: Article^ {#809 ▼
  +__isInitialized__: false
  -id: 117
  -title: null
  -slug: null
  -content: null
  -publishedAt: null
  -author: null
  -heartCount: 0
  -imageFilename: null
  -createdAt: null
  -updatedAt: null
  -comments: null
   …2
}

Here is the complete showAction method

/**
 * @Route("/news/{article}",
 *      name="article_show")
 *
 * @param Article $article
 * @param SlackClient $slack
 * @param EntityManagerInterface $entityManager
 * @param CommentRepository $commentRepository
 * @return \Symfony\Component\HttpFoundation\Response
 * @throws \Http\Client\Exception
 * @throws \Nexy\Slack\Exception\SlackApiException
 */
public function show( $article,
                     SlackClient $slack,
                     EntityManagerInterface $entityManager,
                     CommentRepository $commentRepository

)
{

    $allComments = $commentRepository->findAll();

    $comments = $commentRepository->findBy(['article' => $article]);
    dump($allComments);die;

    $repository = $entityManager->getRepository(Article::class);

    /**
     * @var Article $article
     */
    $articleResult = $repository->findOneBy(['slug' => $article]);
    if (!$articleResult) {
        throw $this->createNotFoundException('No ' . $article . ' found');
    }

Not sure if needed but here is my Article and Comment Entitiy just to make sure i have verything here.

<?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * @ORM\Entity(repositoryClass="App\Repository\ArticleRepository")
 */
class Article
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $title;

    /**
     * @Gedmo\Slug(fields={"title"})
     * @ORM\Column(type="string", length=100, unique=true)
     */
    private $slug;

    /**
     * @ORM\Column(type="text", nullable=true)
     */
    private $content;

    /**
     * @ORM\Column(type="datetime", nullable=true)
     */
    private $publishedAt;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $author;

    /**
     * @ORM\Column(type="integer")
     */
    private $heartCount = 0;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $imageFilename;

    /**
     * @ORM\Column(type="datetime")
     * @Gedmo\Timestampable(on="create")
     */
    private $createdAt;

    /**
     * @ORM\Column(type="datetime")
     * @Gedmo\Timestampable(on="update")
     */
    private $updatedAt;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Comment", mappedBy="article")
     */
    private $comments;

    public function __construct()
    {
        $this->comments = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getTitle(): ?string
    {
        return $this->title;
    }

    public function setTitle(string $title): self
    {
        $this->title = $title;

        return $this;
    }

    public function getSlug(): ?string
    {
        return $this->slug;
    }

    public function setSlug(string $slug): self
    {
        $this->slug = $slug;

        return $this;
    }

    public function getContent(): ?string
    {
        return $this->content;
    }

    public function setContent(?string $content): self
    {
        $this->content = $content;

        return $this;
    }

    public function getPublishedAt(): ?\DateTimeInterface
    {
        return $this->publishedAt;
    }

    public function setPublishedAt(?\DateTimeInterface $publishedAt): self
    {
        $this->publishedAt = $publishedAt;

        return $this;
    }

    public function getAuthor(): ?string
    {
        return $this->author;
    }

    public function setAuthor(string $author): self
    {
        $this->author = $author;

        return $this;
    }

    public function getHeartCount(): ?int
    {
        return $this->heartCount;
    }

    public function setHeartCount(int $heartCount): self
    {
        $this->heartCount = $heartCount;

        return $this;
    }

    public function getImageFilename(): ?string
    {
        return $this->imageFilename;
    }

    public function setImageFilename(?string $imageFilename): self
    {
        $this->imageFilename = $imageFilename;

        return $this;
    }

    public function getCreatedAt(): ?\DateTimeInterface
    {
        return $this->createdAt;
    }

    public function setCreatedAt(\DateTimeInterface $createdAt): self
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    public function getUpdatedAt(): ?\DateTimeInterface
    {
        return $this->updatedAt;
    }

    public function setUpdatedAt(\DateTimeInterface $updatedAt): self
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * @return Collection|Comment[]
     */
    public function getComments(): Collection
    {
        return $this->comments;
    }

    public function addComment(Comment $comment): self
    {
        if (!$this->comments->contains($comment)) {
            $this->comments[] = $comment;
            $comment->setArticle($this);
        }

        return $this;
    }

    public function removeComment(Comment $comment): self
    {
        if ($this->comments->contains($comment)) {
            $this->comments->removeElement($comment);
            // set the owning side to null (unless already changed)
            if ($comment->getArticle() === $this) {
                $comment->setArticle(null);
            }
        }

        return $this;
    }
}

and the Comments Entitiy.

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Timestampable\Traits\TimestampableEntity;

/**
 * @ORM\Entity(repositoryClass="App\Repository\CommentRepository")
 */
class Comment
{

    use TimestampableEntity;

    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $authorName;

    /**
     * @ORM\Column(type="text")
     */
    private $content;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Article", inversedBy="comments")
     * @ORM\JoinColumn(nullable=false)
     */
    private $article;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getAuthorName(): ?string
    {
        return $this->authorName;
    }

    public function setAuthorName(string $authorName): self
    {
        $this->authorName = $authorName;

        return $this;
    }

    public function getContent(): ?string
    {
        return $this->content;
    }

    public function setContent(string $content): self
    {
        $this->content = $content;

        return $this;
    }

    public function getArticle(): ?article
    {
        return $this->article;
    }

    public function setArticle(?article $article): self
    {
        $this->article = $article;

        return $this;
    }
}

Please let me know if you need any other information

Body:
The problem lies in showAction method.

You want to take a look at $article argument. Phpdoc says it will be instance of Article but it won't be.

Here:

$articleResult = $repository->findOneBy(['slug' => $article]);

You assume that $article contains string representing slug.

So you search for comments by article slug and comments don't contain this information. You want to fetch them by article id.


问:
Kubernetes HPA deployment cannot find target resource
I'm trying to deploy my own HPA without a success.
Although while trying to deploy the official PHP of kubernetes, it worked as planned.
When I tryied to deploy my own Test Deployment with the HPA, it didn't work.

Compare 2 HPA deployments processes - Kubernetes official deployment VS My Test deployment:

Deploy the Official Kubernetes template image:

```<code>$ kubectl run php-apache --image=gcr.io/google_containers/hpa-example --requests=cpu=200m --expose --port=80
service "php-apache" created
deployment "php-apache" created
</code>```

My own Test Deployment result

```<code>{
   "apiVersion": "autoscaling/v1",
   "kind": "HorizontalPodAutoscaler",
   "metadata": {
       "annotations": {
           "autoscaling.alpha.kubernetes.io/conditions": "[{\"type\":\"AbleToScale\",\"status\":\"False\",\"lastTransitionTime\":\"2019-12-22T20:39:59Z\",\"reason\":\"FailedGetScale\",\"message\":\"the HPA controller was unable to get the target's current scale: deployments/scale.apps \\\"gw-autoscale-t6\\\" not found\"}]"
       },
       "creationTimestamp": "2019-12-22T20:39:44Z",
       "labels": {
           "app": "gw-autoscale-t6"
       },
       "name": "gw-autoscale-t6",
       "namespace": "dev",
       "resourceVersion": "17299134",
       "selfLink": "/apis/autoscaling/v1/namespaces/dev/horizontalpodautoscalers/gw-autoscale-t6",
       "uid": "2f7e014c-24fb-11ea-a4d8-a28620329da6"
   },
   "spec": {
       "maxReplicas": 3,
       "minReplicas": 1,
       "scaleTargetRef": {
           "apiVersion": "apps/v1",
           "kind": "Deployment",
           "name": "gw-autoscale-t6"
       },
       "targetCPUUtilizationPercentage": 80
   },
   "status": {
       "currentReplicas": 0,
       "desiredReplicas": 0
   }
}
</code>```

The HPA deployment yaml I used for both of the deployment above
(Official Deployment and my Test Deployment):

```<code>apiVersion: autoscaling/v2beta1
kind: HorizontalPodAutoscaler
metadata:
  name: {{ .Values.name }}
  labels:
    app: {{ .Values.name }}
  namespace: {{ .Values.namespace }}
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: {{ .Values.name }}
  minReplicas: {{ .Values.spec.replicaCountMin }}
  maxReplicas: {{ .Values.spec.replicaCountMax }}
  targetCPUUtilizationPercentage: 50
  selector:
    matchLabels:
      app: {{ .Values.name }}
  template:
    metadata:
      labels:
        app: {{ .Values.name }}
        release: {{ .Release.Name }}
        heritage: {{ .Release.Service }}
    spec:
      containers:
      - name: {{ .Chart.Name }}
        image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
</code>```

The results:

PHP HPA is working as planned

```<code>NAME        REFERENCE              TARGETS  MINPODS   MAXPODS   REPLICAS   AGE
php-apache  Deployment/php-apache  0%/50%    1        3         1          3d7h
</code>```

Test Deployment HPA is not working

```<code>NAME              REFERENCE                    TARGETS         MINPODS  MAXPODS   REPLICAS   AGE
gw-autoscale-t6   Deployment/gw-autoscale-t6   <unknown>/80%   1        3         0          11m
</code>```

The Test Deployment HPA error

```<code>Name:                                                  gw-autoscale-t6
Namespace:                                             dev
Labels:                                                app=gw-autoscale-t6
Annotations:                                           <none>
CreationTimestamp:                                     Sun, 22 Dec 2019 22:39:44 +0200
Reference:                                             Deployment/gw-autoscale-t6
Metrics:                                               ( current / target )
  resource cpu on pods  (as a percentage of request):  <unknown> / 80%
Min replicas:                                          1
Max replicas:                                          3
Deployment pods:                                       0 current / 0 desired
Conditions:
  Type         Status  Reason          Message
  ----         ------  ------          -------
  AbleToScale  False   FailedGetScale  the HPA controller was unable to get the target's current scale: deployments/scale.apps "gw-autoscale-t6" not found
Events:
  Type     Reason          Age                 From                       Message
  ----     ------          ----                ----                       -------
  Warning  FailedGetScale  27s (x81 over 20m)  horizontal-pod-autoscaler  deployments/scale.apps "gw-autoscale-t6" not found
</code>```

I have also tried a lot of other types of deployment files.

My Metrics-Service is installed.

I'm installing my deployment with Helm.

What can I do to solve this one?

The solution I found was to add the 'resources' property to the Test Deployment yaml file:

For instance: in case of scale by cpu usage, use it as followed in the deployment file.

```<code>resources:
    requests:
       cpu: {{ .Values.request.cpu }}
    limits:
       cpu: {{ .Values.limits.cpu }}
</code>```

答:
The way I solved it is by adding the cpu resources to the deployment's file and keeping only the necessary HPA deployment yaml fields.

HPA deployment file

```<code>apiVersion: autoscaling/v1
kind: HorizontalPodAutoscaler
metadata:
  name: {{ .Values.name }}
  labels:
    app: {{ .Values.name }}
  namespace: {{ .Values.namespace }}
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: {{ .Values.name }}
  minReplicas: {{ .Values.spec.replicaCountMin }}
  maxReplicas: {{ .Values.spec.replicaCountMax }}
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: {{ .Values.spec.cpuUtil }}

</code>```

Deployment file - resource addition

```<code>apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: {{ .Values.name }}
  labels:
    app: {{ .Values.name }}
  namespace: {{ .Values.namespace }}
spec:
  replicas: {{ .Values.replicaCount }}
  template:
    metadata:
      labels:
        app: {{ .Values.name }}
        release: {{ .Release.Name }}
        heritage: {{ .Release.Service }}
    spec:
      containers:
      - name: {{ .Chart.Name }}
        image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
        resources:
          requests:
            cpu: {{ .Values.request.cpu }}
          limits:
            cpu: {{ .Values.limits.cpu }}
</code>```

You must add this code:

```<code>resources:
  requests:
     cpu: {{ .Values.request.cpu }}
  limits:
     cpu: {{ .Values.limits.cpu }}
</code>```

Hope it helps :)

Body:
I'm trying to deploy my own HPA without a success.
Although while trying to deploy the official PHP of kubernetes, it worked as planned.
When I tryied to deploy my own Test Deployment with the HPA, it didn't work.

Compare 2 HPA deployments processes - Kubernetes official deployment VS My Test deployment:

Deploy the Official Kubernetes template image:

$ kubectl run php-apache --image=gcr.io/google_containers/hpa-example --requests=cpu=200m --expose --port=80
service "php-apache" created
deployment "php-apache" created

My own Test Deployment result

{
   "apiVersion": "autoscaling/v1",
   "kind": "HorizontalPodAutoscaler",
   "metadata": {
       "annotations": {
           "autoscaling.alpha.kubernetes.io/conditions": "[{\"type\":\"AbleToScale\",\"status\":\"False\",\"lastTransitionTime\":\"2019-12-22T20:39:59Z\",\"reason\":\"FailedGetScale\",\"message\":\"the HPA controller was unable to get the target's current scale: deployments/scale.apps \\\"gw-autoscale-t6\\\" not found\"}]"
       },
       "creationTimestamp": "2019-12-22T20:39:44Z",
       "labels": {
           "app": "gw-autoscale-t6"
       },
       "name": "gw-autoscale-t6",
       "namespace": "dev",
       "resourceVersion": "17299134",
       "selfLink": "/apis/autoscaling/v1/namespaces/dev/horizontalpodautoscalers/gw-autoscale-t6",
       "uid": "2f7e014c-24fb-11ea-a4d8-a28620329da6"
   },
   "spec": {
       "maxReplicas": 3,
       "minReplicas": 1,
       "scaleTargetRef": {
           "apiVersion": "apps/v1",
           "kind": "Deployment",
           "name": "gw-autoscale-t6"
       },
       "targetCPUUtilizationPercentage": 80
   },
   "status": {
       "currentReplicas": 0,
       "desiredReplicas": 0
   }
}

The HPA deployment yaml I used for both of the deployment above
(Official Deployment and my Test Deployment):

apiVersion: autoscaling/v2beta1
kind: HorizontalPodAutoscaler
metadata:
  name: {{ .Values.name }}
  labels:
    app: {{ .Values.name }}
  namespace: {{ .Values.namespace }}
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: {{ .Values.name }}
  minReplicas: {{ .Values.spec.replicaCountMin }}
  maxReplicas: {{ .Values.spec.replicaCountMax }}
  targetCPUUtilizationPercentage: 50
  selector:
    matchLabels:
      app: {{ .Values.name }}
  template:
    metadata:
      labels:
        app: {{ .Values.name }}
        release: {{ .Release.Name }}
        heritage: {{ .Release.Service }}
    spec:
      containers:
      - name: {{ .Chart.Name }}
        image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"

The results:

PHP HPA is working as planned

NAME        REFERENCE              TARGETS  MINPODS   MAXPODS   REPLICAS   AGE
php-apache  Deployment/php-apache  0%/50%    1        3         1          3d7h

Test Deployment HPA is not working

NAME              REFERENCE                    TARGETS         MINPODS  MAXPODS   REPLICAS   AGE
gw-autoscale-t6   Deployment/gw-autoscale-t6   <unknown>/80%   1        3         0          11m

The Test Deployment HPA error

Name:                                                  gw-autoscale-t6
Namespace:                                             dev
Labels:                                                app=gw-autoscale-t6
Annotations:                                           <none>
CreationTimestamp:                                     Sun, 22 Dec 2019 22:39:44 +0200
Reference:                                             Deployment/gw-autoscale-t6
Metrics:                                               ( current / target )
  resource cpu on pods  (as a percentage of request):  <unknown> / 80%
Min replicas:                                          1
Max replicas:                                          3
Deployment pods:                                       0 current / 0 desired
Conditions:
  Type         Status  Reason          Message
  ----         ------  ------          -------
  AbleToScale  False   FailedGetScale  the HPA controller was unable to get the target's current scale: deployments/scale.apps "gw-autoscale-t6" not found
Events:
  Type     Reason          Age                 From                       Message
  ----     ------          ----                ----                       -------
  Warning  FailedGetScale  27s (x81 over 20m)  horizontal-pod-autoscaler  deployments/scale.apps "gw-autoscale-t6" not found

I have also tried a lot of other types of deployment files.

My Metrics-Service is installed.

I'm installing my deployment with Helm.

What can I do to solve this one?

The solution I found was to add the 'resources' property to the Test Deployment yaml file:

For instance: in case of scale by cpu usage, use it as followed in the deployment file.

resources:
    requests:
       cpu: {{ .Values.request.cpu }}
    limits:
       cpu: {{ .Values.limits.cpu }}

Body:
The way I solved it is by adding the cpu resources to the deployment's file and keeping only the necessary HPA deployment yaml fields.

HPA deployment file

apiVersion: autoscaling/v1
kind: HorizontalPodAutoscaler
metadata:
  name: {{ .Values.name }}
  labels:
    app: {{ .Values.name }}
  namespace: {{ .Values.namespace }}
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: {{ .Values.name }}
  minReplicas: {{ .Values.spec.replicaCountMin }}
  maxReplicas: {{ .Values.spec.replicaCountMax }}
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: {{ .Values.spec.cpuUtil }}

Deployment file - resource addition

apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: {{ .Values.name }}
  labels:
    app: {{ .Values.name }}
  namespace: {{ .Values.namespace }}
spec:
  replicas: {{ .Values.replicaCount }}
  template:
    metadata:
      labels:
        app: {{ .Values.name }}
        release: {{ .Release.Name }}
        heritage: {{ .Release.Service }}
    spec:
      containers:
      - name: {{ .Chart.Name }}
        image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
        resources:
          requests:
            cpu: {{ .Values.request.cpu }}
          limits:
            cpu: {{ .Values.limits.cpu }}

You must add this code:

resources:
  requests:
     cpu: {{ .Values.request.cpu }}
  limits:
     cpu: {{ .Values.limits.cpu }}

Hope it helps :)


问:
How to get value from strings.xml to arraylist
I have the following code:

```<code>package com.sample.app;

import android.content.res.Resources;

import java.util.ArrayList;

public class Content {

    public static ArrayList<String> Names;
    public static ArrayList<String> NamesSub;
    public static ArrayList<String> Images;
    public static ArrayList<String> Wallpaper;
    public static ArrayList<String> Audio;
    public static ArrayList<String> BIG_Images;
    public static ArrayList<String> Sub_heading;
    public static ArrayList<String> Description;

    Content(){
        this.Names = new ArrayList<String>();
        this.NamesSub = new ArrayList<String>();
        this.Sub_heading = new ArrayList<String>();
        this.Images = new ArrayList<String>();
        this.Wallpaper = new ArrayList<String>();
        this.BIG_Images = new ArrayList<String>();
        this.Audio = new ArrayList<String>();
        this.Description = new ArrayList<String>();

        this.Description.add(0, "Long description");
        this.Description.add(1, "");
        this.Description.add(2, "");

    }

}

</code>```

And have a too long description for ArrayList. when I paste the description it gave me

error: constant string too long

error. After that i tried setting values from strings.xml. I am using this code for getting values:

```<code>this.Description.add(0,String.valueOf(R.string.descvalue));
</code>```

But when I run the app it prints numbers like this 2131689519 not my values.

After that i tried string-array

```<code><string-array name="descvalue">
    <item>too long value</item>
</string-array>
</code>```

And in the java file, I tried getting values with this code:

```<code>this.Description.add(0, getResources().getStringArray(R.array.descvalue)[0]);
</code>```

But when I run the app it's crashing.

So what should I do in this case? Thanks.

答:
"error: constant string too long"

for this, you can go with Text class

```<code>Text text = new Text("foo");
String s = text.getText();
text.setText(s);

</code>```

Body:
I have the following code:

package com.sample.app;

import android.content.res.Resources;

import java.util.ArrayList;

public class Content {

    public static ArrayList<String> Names;
    public static ArrayList<String> NamesSub;
    public static ArrayList<String> Images;
    public static ArrayList<String> Wallpaper;
    public static ArrayList<String> Audio;
    public static ArrayList<String> BIG_Images;
    public static ArrayList<String> Sub_heading;
    public static ArrayList<String> Description;

    Content(){
        this.Names = new ArrayList<String>();
        this.NamesSub = new ArrayList<String>();
        this.Sub_heading = new ArrayList<String>();
        this.Images = new ArrayList<String>();
        this.Wallpaper = new ArrayList<String>();
        this.BIG_Images = new ArrayList<String>();
        this.Audio = new ArrayList<String>();
        this.Description = new ArrayList<String>();

        this.Description.add(0, "Long description");
        this.Description.add(1, "");
        this.Description.add(2, "");

    }

}

And have a too long description for ArrayList. when I paste the description it gave me

error: constant string too long

error. After that i tried setting values from strings.xml. I am using this code for getting values:

this.Description.add(0,String.valueOf(R.string.descvalue));

But when I run the app it prints numbers like this 2131689519 not my values.

After that i tried string-array

<string-array name="descvalue">
    <item>too long value</item>
</string-array>

And in the java file, I tried getting values with this code:

this.Description.add(0, getResources().getStringArray(R.array.descvalue)[0]);

But when I run the app it's crashing.

So what should I do in this case? Thanks.

Body:
"error: constant string too long"

for this, you can go with Text class

Text text = new Text("foo");
String s = text.getText();
text.setText(s);


答:
Replace

```<code>this.Description.add(0,String.valueOf(R.string.descvalue));
</code>```

With

```<code>this.Description.add(0,getString(R.string.descvalue));
</code>```

but getString() needs a context.

Title: How to get value from strings.xml to arraylist

Body:
Replace

this.Description.add(0,String.valueOf(R.string.descvalue));

With

this.Description.add(0,getString(R.string.descvalue));

but getString() needs a context.


问:
Rust: Map two Vecs into a third Vec of composite structs
I have three structs:

struct A;

struct B;

struct C {
    a: Option,
    b: Option
}
```

<p>Given inputs <code>Vec<A></code> and <code>Vec<B></code> and some predicate function, I want to create an output <code>Vec<C></code>, which is a combination of the elements of the inputs, something like the following:</p>

<pre class="lang-rust prettyprint-override"><code>let aVec: Vec<A> = vec![];
let bVec: Vec<B> = vec![];
let mut cVec: Vec<C> = vec![];
for a in aVec {
    if let Some(b) = bVec.into_iter().find(predicate) {
        cVec.push(C{a: Some(a), b: Some(b)});
    }
}
</code>```

Is there a way to do this without needing B to be copyable? Both input vectors aren't required after the operation. Also, is this possible without the loop?

答:
You can:

Find the index of the element satisfying predicate. (I would use Iterator::position.)

remove or swap_remove the element at the position obtained by the previous step.

push the previously removed element into result.

In code:

```<code>use itertools; // 0.8.2
use itertools::Itertools;

struct A {}

struct B {
    n: usize,
}

struct C {
    a: Option<A>,
    b: Option<B>
}

fn  main() {
    let aVec: Vec<A> = vec![];
    let mut bVec: Vec<B> = vec![];
    let mut cVec: Vec<C> = vec![];
    for a in aVec {
        if let Some(idx) = bVec.iter()
                               .position(|b| b.n==42)
        {
            let b = bVec.remove(idx); // or swap_remove if ordering does not need to be preserved
            cVec.push(C{a: Some(a), b: Some(b)});
        }

    }
}
</code>```

Body:
I have three structs:

struct A;

struct B;

struct C {
    a: Option,
    b: Option
}

Given inputs Vec and Vec and some predicate function, I want to create an output Vec<C>, which is a combination of the elements of the inputs, something like the following:

let aVec: Vec = vec![];
let bVec: Vec = vec![];
let mut cVec: Vec<C> = vec![];
for a in aVec {
    if let Some(b) = bVec.into_iter().find(predicate) {
        cVec.push(C{a: Some(a), b: Some(b)});
    }
}

Is there a way to do this without needing B to be copyable? Both input vectors aren't required after the operation. Also, is this possible without the loop?

Body:
You can:

Find the index of the element satisfying predicate. (I would use Iterator::position.)

remove or swap_remove the element at the position obtained by the previous step.

push the previously removed element into result.

In code:

use itertools; // 0.8.2
use itertools::Itertools;

struct A {}

struct B {
    n: usize,
}

struct C {
    a: Option<A>,
    b: Option<B>
}

fn  main() {
    let aVec: Vec<A> = vec![];
    let mut bVec: Vec<B> = vec![];
    let mut cVec: Vec<C> = vec![];
    for a in aVec {
        if let Some(idx) = bVec.iter()
                               .position(|b| b.n==42)
        {
            let b = bVec.remove(idx); // or swap_remove if ordering does not need to be preserved
            cVec.push(C{a: Some(a), b: Some(b)});
        }

    }
}


问:
Heroku push master ssh problem
I get this when I am trying to push to my Heroku app:

```<code>ssh_exchange_identification: read: Connection reset by peer
fatal: The remote end hung up unexpectedly
</code>```

I tried regenerating the ssh keys and adding them to the remote, but no joy.  Any help.
Kinda stuck in a rut here!

EDIT: and now I get the same error from a different app that was working very recently. :/

答:
Heroku is having git problems - see Heroku server status:
http://status.heroku.com/

I just started getting this error now.

Title: Heroku push master ssh problem

Body:
I get this when I am trying to push to my Heroku app:

ssh_exchange_identification: read: Connection reset by peer
fatal: The remote end hung up unexpectedly

I tried regenerating the ssh keys and adding them to the remote, but no joy.  Any help.
Kinda stuck in a rut here!

EDIT: and now I get the same error from a different app that was working very recently. :/


问:
Javascript/React Native looping only update variable to last value
I'm working with react native loop to display a section header and data.

My expected output would be like:

> Section 0

data1 data2

> Section 1

data1 data2

> Section 2

data1 data2

which will loop the section according to the loop number

However, the actual output is like:
Actual Output

It only display the last looping value

```<code>import React, { Component } from 'react';
    import { Text, StyleSheet, View, SafeAreaView, SectionList } from 'react-native';

    export default class Appointment extends Component {

        constructor(props) {
            super(props)

            this.state = {
                appointmentList: [{
                    index: '',
                    data: ['']
                }]
            }
        }

        componentDidMount() {

            let appointmentListItem = {};
            let appointment = [];

            for (let i = 0; i < 3; i++) {
                console.log(i);
                appointmentListItem.index = i;
                appointmentListItem.data = ['data1', 'data2'];
                appointment.push(appointmentListItem);
            }

            this.setState({
                appointmentList: appointment
            });

        }

        render() {
            return (
                <SafeAreaView>
                    <SectionList
                        sections={this.state.appointmentList}
                        keyExtractor={(item, index) => item + index}
                        renderItem={({ item }) => <Text>{item}</Text>}
                        renderSectionHeader={({ section: { index } }) => (
                            <View style={{ backgroundColor: 'red' }}>
                                <Text>{index}</Text>
                            </View>
                        )}
                    />

                </SafeAreaView>
            )
        }
    }
</code>```

Is there any solution to this problem? Thanks a lot

答:
The variable appointmentListItem is being instantiated once, then mutated as the for loop iterates. This results in a single object reference being added to the appointment list many times, with the most recent mutation applying to all of the referenced objects.

Move the declaration of the variable appointmentListItem into the for loop body, like this:

```<code>    componentDidMount() {

        let appointment = [];

        for (let i = 0; i < 3; i++) {
            console.log(i);
            const appointmentListItem = {}
            appointmentListItem.index = i;
            appointmentListItem.data = ['data1', 'data2'];
            appointment.push(appointmentListItem);
        }

        this.setState({
            appointmentList: appointment
        });

    }
</code>```

Body:
I'm working with react native loop to display a section header and data.

My expected output would be like:

> Section 0

data1 data2

> Section 1

data1 data2

> Section 2

data1 data2

which will loop the section according to the loop number

However, the actual output is like:
Actual Output

It only display the last looping value

import React, { Component } from 'react';
    import { Text, StyleSheet, View, SafeAreaView, SectionList } from 'react-native';

    export default class Appointment extends Component {

        constructor(props) {
            super(props)

            this.state = {
                appointmentList: [{
                    index: '',
                    data: ['']
                }]
            }
        }

        componentDidMount() {

            let appointmentListItem = {};
            let appointment = [];

            for (let i = 0; i < 3; i++) {
                console.log(i);
                appointmentListItem.index = i;
                appointmentListItem.data = ['data1', 'data2'];
                appointment.push(appointmentListItem);
            }

            this.setState({
                appointmentList: appointment
            });

        }

        render() {
            return (
                <SafeAreaView>
                    <SectionList
                        sections={this.state.appointmentList}
                        keyExtractor={(item, index) => item + index}
                        renderItem={({ item }) => <Text>{item}</Text>}
                        renderSectionHeader={({ section: { index } }) => (
                            <View style={{ backgroundColor: 'red' }}>
                                <Text>{index}</Text>
                            </View>
                        )}
                    />

                </SafeAreaView>
            )
        }
    }

Is there any solution to this problem? Thanks a lot

Body:
The variable appointmentListItem is being instantiated once, then mutated as the for loop iterates. This results in a single object reference being added to the appointment list many times, with the most recent mutation applying to all of the referenced objects.

Move the declaration of the variable appointmentListItem into the for loop body, like this:

    componentDidMount() {

        let appointment = [];

        for (let i = 0; i < 3; i++) {
            console.log(i);
            const appointmentListItem = {}
            appointmentListItem.index = i;
            appointmentListItem.data = ['data1', 'data2'];
            appointment.push(appointmentListItem);
        }

        this.setState({
            appointmentList: appointment
        });

    }


问:
SyntaxError: Unexpected token '<' when dockerizing react app
I have a react project with Webpack which I'm trying to dockerize it following this article.

Dockerfile:

```<code>FROM node:12.14.1

RUN npm install webpack -g

WORKDIR /tmp
COPY package.json /tmp/
RUN npm config set registry http://registry.npmjs.org/ && npm install

WORKDIR /usr/app
COPY . /usr/app/
RUN cp -a /tmp/node_modules /usr/app/

RUN webpack

ENV NODE_ENV=production
ENV PORT=4000

CMD [ "/usr/local/bin/node", "--experimental-modules", "./src/index.js" ]

EXPOSE 4000
</code>```

docker-compose.yml:

```<code>ex_dashboard:
  build: .
  ports:
  - "80:4000"
  volumes:
  - .:/usr/app/:rw
  environment:
  - NODE_ENV=dev
  command: >
    sh -c '
      if test -d node_modules;
      then
        echo node_modules_exists ;
      else
        cp -a /tmp/node_modules /usr/app/dashboard;
      fi &&
      npm install &&
      /usr/local/bin/node --experimental-modules ./src/index.js
    '
</code>```

When I run docker-compose up, everything goes well until I encounter this error:

```<code>ex_dashboard_1  | (node:18) ExperimentalWarning: The ESM module loader is experimental.
ex_dashboard_1  | file:///usr/app/src/index.js:9
ex_dashboard_1  |   <Provider store={store}>
ex_dashboard_1  |   ^
ex_dashboard_1  |
ex_dashboard_1  | SyntaxError: Unexpected token '<'
ex_dashboard_1  |     at Loader.moduleStrategy (internal/modules/esm/translators.js:66:18)
ex_dashboard_1  |     at async link (internal/modules/esm/module_job.js:37:21)
</code>```

The whole project works well if I just run it by npm start or build it by npm run build. But I don't know why this happens in docker container.

Here is package.json:

```<code>{
  "name": "explore_dashboard",
  "version": "1.0.0",
  "description": "A dashboard for the Explore project",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "start": "cross-env NODE_ENV=development webpack-dev-server --hot",
    "build": "cross-env NODE_ENV=production webpack",
    "lint": "eslint ./src",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "https://gitlab.basalam.dev/data/explore_dashboard.git"
  },
  "author": "Gh.Sherafati",
  "license": "ISC",
  "resolve": {
    "alias": {
      "react-dom": "@hot-loader/react-dom"
    }
  },
  "devDependencies": {
    "@babel/core": "^7.8.4",
    "@babel/plugin-transform-runtime": "^7.8.3",
    "@babel/preset-env": "^7.8.4",
    "@babel/preset-react": "^7.8.3",
    "babel-eslint": "^10.0.3",
    "babel-loader": "^8.0.6",
    "cross-env": "^7.0.0",
    "css-loader": "^3.4.2",
    "eslint": "^6.1.0",
    "eslint-config-airbnb": "^18.0.1",
    "eslint-loader": "^3.0.3",
    "eslint-plugin-import": "^2.20.0",
    "eslint-plugin-jsx-a11y": "^6.2.3",
    "eslint-plugin-react": "^7.18.0",
    "eslint-plugin-react-hooks": "^1.7.0",
    "html-webpack-plugin": "^3.2.0",
    "node-sass": "^4.13.1",
    "sass-loader": "^8.0.2",
    "style-loader": "^1.1.3",
    "webpack": "^4.41.5",
    "webpack-cli": "^3.3.10",
    "webpack-dev-server": "^3.10.2"
  },
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^1.2.27",
    "@fortawesome/free-solid-svg-icons": "^5.12.1",
    "@fortawesome/react-fontawesome": "^0.1.8",
    "@hot-loader/react-dom": "^16.11.0",
    "@types/react": "^16.9.19",
    "axios": "^0.19.2",
    "react": "^16.12.0",
    "react-beautiful-dnd": "^12.2.0",
    "react-dom": "^16.12.0",
    "react-hot-loader": "^4.12.19",
    "react-redux": "^7.1.3",
    "redux": "^4.0.5",
    "redux-saga": "^1.1.3"
  }
}
</code>```

And webpack.config.js:

```<code>const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const { env } = process;

module.exports = {
  entry: './src/index.js',
  mode: env.NODE_ENV,
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ['babel-loader', 'eslint-loader'],
      },
      {
        test: /\.s[ac]ss$/i,
        use: [
          // Creates `style` nodes from JS strings
          'style-loader',
          // Translates CSS into CommonJS
          'css-loader',
          // Compiles Sass to CSS
          'sass-loader',
        ],
      },
    ],
  },
  resolve: {
    extensions: ['*', '.js', '.jsx'],
  },
  output: {
    path: path.join(__dirname, '/build'),
    publicPath: '/',
    filename: 'bundle.js',
  },
  plugins: [
    new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(env.NODE_ENV) }),
    new HtmlWebpackPlugin({
      template: path.resolve('./src/index.html'),
    }),
  ],
  devServer: {
    contentBase: './build',
    hot: true,
  },
  devtool: env.NODE_ENV === 'development' ? 'cheap-module-eval-source-map' : undefined,
};
</code>```

Also index.js:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './redux/store';
import App from './components/App';
import './scss/main.scss';

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('app'),
);

module.hot.accept();
</code>```

答:
Finally I've solve the issue by using nginx and running the build version in the container getting help from this great article.

The new Dockerfile and docker-compose.yml follows:

Dockerfile:

```<code>FROM node:12.14.1 as build
WORKDIR /app
COPY . /app
ENV PATH /app/node_modules/.bin:$PATH
RUN npm install
RUN npm run build
FROM nginx:alpine
COPY --from=build /app/build /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
</code>```

docker-compose.yml:

```<code>version: "3"
services:
  explore_dashboard:
    container_name: explore_dashboard
    build:
      context: .
      dockerfile:
        Dockerfile
    ports:
      - "8081:80"
</code>```

nginx.conf:

```<code>server {
    listen 80;
    location / {
      root   /usr/share/nginx/html;
      index  index.html index.htm;
      try_files $uri $uri/ /index.html;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
      root   /usr/share/nginx/html;
    }
  }
</code>```

Now I'm able to run the app on http://127.0.0.1:8081/ running:

```<code>docker-compose up
</code>```

Body:
I have a react project with Webpack which I'm trying to dockerize it following this article.

Dockerfile:

FROM node:12.14.1

RUN npm install webpack -g

WORKDIR /tmp
COPY package.json /tmp/
RUN npm config set registry http://registry.npmjs.org/ && npm install

WORKDIR /usr/app
COPY . /usr/app/
RUN cp -a /tmp/node_modules /usr/app/

RUN webpack

ENV NODE_ENV=production
ENV PORT=4000

CMD [ "/usr/local/bin/node", "--experimental-modules", "./src/index.js" ]

EXPOSE 4000

docker-compose.yml:

ex_dashboard:
  build: .
  ports:
  - "80:4000"
  volumes:
  - .:/usr/app/:rw
  environment:
  - NODE_ENV=dev
  command: >
    sh -c '
      if test -d node_modules;
      then
        echo node_modules_exists ;
      else
        cp -a /tmp/node_modules /usr/app/dashboard;
      fi &&
      npm install &&
      /usr/local/bin/node --experimental-modules ./src/index.js
    '

When I run docker-compose up, everything goes well until I encounter this error:

ex_dashboard_1  | (node:18) ExperimentalWarning: The ESM module loader is experimental.
ex_dashboard_1  | file:///usr/app/src/index.js:9
ex_dashboard_1  |   <Provider store={store}>
ex_dashboard_1  |   ^
ex_dashboard_1  |
ex_dashboard_1  | SyntaxError: Unexpected token '<'
ex_dashboard_1  |     at Loader.moduleStrategy (internal/modules/esm/translators.js:66:18)
ex_dashboard_1  |     at async link (internal/modules/esm/module_job.js:37:21)

The whole project works well if I just run it by npm start or build it by npm run build. But I don't know why this happens in docker container.

Here is package.json:

{
  "name": "explore_dashboard",
  "version": "1.0.0",
  "description": "A dashboard for the Explore project",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "start": "cross-env NODE_ENV=development webpack-dev-server --hot",
    "build": "cross-env NODE_ENV=production webpack",
    "lint": "eslint ./src",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "https://gitlab.basalam.dev/data/explore_dashboard.git"
  },
  "author": "Gh.Sherafati",
  "license": "ISC",
  "resolve": {
    "alias": {
      "react-dom": "@hot-loader/react-dom"
    }
  },
  "devDependencies": {
    "@babel/core": "^7.8.4",
    "@babel/plugin-transform-runtime": "^7.8.3",
    "@babel/preset-env": "^7.8.4",
    "@babel/preset-react": "^7.8.3",
    "babel-eslint": "^10.0.3",
    "babel-loader": "^8.0.6",
    "cross-env": "^7.0.0",
    "css-loader": "^3.4.2",
    "eslint": "^6.1.0",
    "eslint-config-airbnb": "^18.0.1",
    "eslint-loader": "^3.0.3",
    "eslint-plugin-import": "^2.20.0",
    "eslint-plugin-jsx-a11y": "^6.2.3",
    "eslint-plugin-react": "^7.18.0",
    "eslint-plugin-react-hooks": "^1.7.0",
    "html-webpack-plugin": "^3.2.0",
    "node-sass": "^4.13.1",
    "sass-loader": "^8.0.2",
    "style-loader": "^1.1.3",
    "webpack": "^4.41.5",
    "webpack-cli": "^3.3.10",
    "webpack-dev-server": "^3.10.2"
  },
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^1.2.27",
    "@fortawesome/free-solid-svg-icons": "^5.12.1",
    "@fortawesome/react-fontawesome": "^0.1.8",
    "@hot-loader/react-dom": "^16.11.0",
    "@types/react": "^16.9.19",
    "axios": "^0.19.2",
    "react": "^16.12.0",
    "react-beautiful-dnd": "^12.2.0",
    "react-dom": "^16.12.0",
    "react-hot-loader": "^4.12.19",
    "react-redux": "^7.1.3",
    "redux": "^4.0.5",
    "redux-saga": "^1.1.3"
  }
}

And webpack.config.js:

const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const { env } = process;

module.exports = {
  entry: './src/index.js',
  mode: env.NODE_ENV,
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ['babel-loader', 'eslint-loader'],
      },
      {
        test: /\.s[ac]ss$/i,
        use: [
          // Creates `style` nodes from JS strings
          'style-loader',
          // Translates CSS into CommonJS
          'css-loader',
          // Compiles Sass to CSS
          'sass-loader',
        ],
      },
    ],
  },
  resolve: {
    extensions: ['*', '.js', '.jsx'],
  },
  output: {
    path: path.join(__dirname, '/build'),
    publicPath: '/',
    filename: 'bundle.js',
  },
  plugins: [
    new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(env.NODE_ENV) }),
    new HtmlWebpackPlugin({
      template: path.resolve('./src/index.html'),
    }),
  ],
  devServer: {
    contentBase: './build',
    hot: true,
  },
  devtool: env.NODE_ENV === 'development' ? 'cheap-module-eval-source-map' : undefined,
};

Also index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './redux/store';
import App from './components/App';
import './scss/main.scss';

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('app'),
);

module.hot.accept();

Body:
Finally I've solve the issue by using nginx and running the build version in the container getting help from this great article.

The new Dockerfile and docker-compose.yml follows:

Dockerfile:

FROM node:12.14.1 as build
WORKDIR /app
COPY . /app
ENV PATH /app/node_modules/.bin:$PATH
RUN npm install
RUN npm run build
FROM nginx:alpine
COPY --from=build /app/build /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

docker-compose.yml:

version: "3"
services:
  explore_dashboard:
    container_name: explore_dashboard
    build:
      context: .
      dockerfile:
        Dockerfile
    ports:
      - "8081:80"

nginx.conf:

server {
    listen 80;
    location / {
      root   /usr/share/nginx/html;
      index  index.html index.htm;
      try_files $uri $uri/ /index.html;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
      root   /usr/share/nginx/html;
    }
  }

Now I'm able to run the app on http://127.0.0.1:8081/ running:

docker-compose up


问:
var module = require() or const {module} = require()?
Whats the diference between this two require methods:

```<code>1. var xx = require('module')
2. const {xx} = require('module')
</code>```

I saw the first onde I can access xx as variable, with all script exported by module.. and second xx are undefined. How to access second "method" or is it a method too construct module to use {}

thanks

答:
The first puts the full module handle in a variable named xx.

The second gets the xx property from the module handle and puts it in a variable named xx.   So, the second would be the same as:

```<code>const xx = require('module').xx;
</code>```

Also the first is using var and the second is using const, but I assume you already knew about that difference.

Said a different way:

This:

```<code>const {xx} = require('module');
</code>```

is a shortcut for this:

```<code>const xx = require('module').xx;
</code>```

It's most useful as a shortcut when using require(), when you want to get a bunch of properties from the module and assign them all to top level variables in your module like this:

```<code>const {xx, yy, zz, aa, bb, cc} = require('module');
</code>```

which would obviously take a lot more code to replicate than that single line if you weren't using the object destructuring syntax.

FYI, all of this is just a form of object destructuring (a feature added to Javascript in ES6).  It's not anything specific for require(), it's just that require() often returns an object with a bunch of properties that one is interested in.  See this article "A Dead Simple into to Destructuring" for a nice summary of what object destructuring does.

Body:
Whats the diference between this two require methods:

1. var xx = require('module')
2. const {xx} = require('module')

I saw the first onde I can access xx as variable, with all script exported by module.. and second xx are undefined. How to access second "method" or is it a method too construct module to use {}

thanks

Body:
The first puts the full module handle in a variable named xx.

The second gets the xx property from the module handle and puts it in a variable named xx.   So, the second would be the same as:

const xx = require('module').xx;

Also the first is using var and the second is using const, but I assume you already knew about that difference.

Said a different way:

This:

const {xx} = require('module');

is a shortcut for this:

const xx = require('module').xx;

It's most useful as a shortcut when using require(), when you want to get a bunch of properties from the module and assign them all to top level variables in your module like this:

const {xx, yy, zz, aa, bb, cc} = require('module');

which would obviously take a lot more code to replicate than that single line if you weren't using the object destructuring syntax.

FYI, all of this is just a form of object destructuring (a feature added to Javascript in ES6).  It's not anything specific for require(), it's just that require() often returns an object with a bunch of properties that one is interested in.  See this article "A Dead Simple into to Destructuring" for a nice summary of what object destructuring does.


问:
Kafka MirrorMaker2 topics - replication factor
I am testing kafka mirror maker 2 in my local. Running 2 zookeepers and 2 kafka brokers. They are running as individual instance. So, 2 clusters in my local with 1 broker on each cluster. The brokers are running fine. Now, when i tries running the mirror maker on my local, running into the following issues.

```<code>[2020-02-14 16:58:18,371] ERROR [Worker clientId=connect-2, groupId=dest-mm2] Uncaught exception in herder work thread, exiting:  (org.apache.kafka.connect.runtime.distributed.DistributedHerder:290)
org.apache.kafka.connect.errors.ConnectException: Error while attempting to create/find topic(s) 'mm2-offsets.dest.internal'
    at org.apache.kafka.connect.util.TopicAdmin.createTopics(TopicAdmin.java:262)
    at org.apache.kafka.connect.storage.KafkaOffsetBackingStore$1.run(KafkaOffsetBackingStore.java:99)
    at org.apache.kafka.connect.util.KafkaBasedLog.start(KafkaBasedLog.java:128)
    at org.apache.kafka.connect.storage.KafkaOffsetBackingStore.start(KafkaOffsetBackingStore.java:109)
    at org.apache.kafka.connect.runtime.Worker.start(Worker.java:186)
    at org.apache.kafka.connect.runtime.AbstractHerder.startServices(AbstractHerder.java:121)
    at org.apache.kafka.connect.runtime.distributed.DistributedHerder.run(DistributedHerder.java:277)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.util.concurrent.ExecutionException: org.apache.kafka.common.errors.InvalidReplicationFactorException: Replication factor: 3 larger than available brokers: 1.
    at org.apache.kafka.common.internals.KafkaFutureImpl.wrapAndThrow(KafkaFutureImpl.java:45)
    at org.apache.kafka.common.internals.KafkaFutureImpl.access$000(KafkaFutureImpl.java:32)
    at org.apache.kafka.common.internals.KafkaFutureImpl$SingleWaiter.await(KafkaFutureImpl.java:89)
    at org.apache.kafka.common.internals.KafkaFutureImpl.get(KafkaFutureImpl.java:260)
    at org.apache.kafka.connect.util.TopicAdmin.createTopics(TopicAdmin.java:229)
    ... 11 more
Caused by: org.apache.kafka.common.errors.InvalidReplicationFactorException: Replication factor: 3 larger than available brokers: 1.
[2020-02-14 16:58:18,371] ERROR [Worker clientId=connect-1, groupId=source-mm2] Uncaught exception in herder work thread, exiting:  (org.apache.kafka.connect.runtime.distributed.DistributedHerder:290)
org.apache.kafka.connect.errors.ConnectException: Error while attempting to create/find topic(s) 'mm2-offsets.source.internal'
    at org.apache.kafka.connect.util.TopicAdmin.createTopics(TopicAdmin.java:262)
    at org.apache.kafka.connect.storage.KafkaOffsetBackingStore$1.run(KafkaOffsetBackingStore.java:99)
    at org.apache.kafka.connect.util.KafkaBasedLog.start(KafkaBasedLog.java:128)
    at org.apache.kafka.connect.storage.KafkaOffsetBackingStore.start(KafkaOffsetBackingStore.java:109)
    at org.apache.kafka.connect.runtime.Worker.start(Worker.java:186)
    at org.apache.kafka.connect.runtime.AbstractHerder.startServices(AbstractHerder.java:121)
    at org.apache.kafka.connect.runtime.distributed.DistributedHerder.run(DistributedHerder.java:277)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.util.concurrent.ExecutionException: org.apache.kafka.common.errors.InvalidReplicationFactorException: Replication factor: 3 larger than available brokers: 1.
    at org.apache.kafka.common.internals.KafkaFutureImpl.wrapAndThrow(KafkaFutureImpl.java:45)
    at org.apache.kafka.common.internals.KafkaFutureImpl.access$000(KafkaFutureImpl.java:32)
    at org.apache.kafka.common.internals.KafkaFutureImpl$SingleWaiter.await(KafkaFutureImpl.java:89)
    at org.apache.kafka.common.internals.KafkaFutureImpl.get(KafkaFutureImpl.java:260)
    at org.apache.kafka.connect.util.TopicAdmin.createTopics(TopicAdmin.java:229)
    ... 11 more
Caused by: org.apache.kafka.common.errors.InvalidReplicationFactorException: Replication factor: 3 larger than available brokers: 1.
</code>```

This error is happening since there is only one broker in my local and mirror maker is trying to create offset topics with replication factor 3. How can I set the config to change the replication factor to 1.

I tried as below, but still the same error. not sure what is the correct config.

mm2.properties

```<code># mm2.properties
name=source->dest
clusters=source, dest

source.bootstrap.servers=localhost:9091
dest.bootstrap.servers=localhost:9092

source->dest.enabled=true

topics=test-3 groups=test-6-group
offsets.storage.replication.factor=1
source.replication.factor=1
dest.replication.factor=1

mm2-offsets.source.internal.replication.factor=1
mm2-offsets.dest.internal.replication.factor=1
</code>```

答:
It works after adding the below 2 props.</p>

```<code>config.storage.replication.factor=1
status.storage.replication.factor=1
</code>```

Body:
I am testing kafka mirror maker 2 in my local. Running 2 zookeepers and 2 kafka brokers. They are running as individual instance. So, 2 clusters in my local with 1 broker on each cluster. The brokers are running fine. Now, when i tries running the mirror maker on my local, running into the following issues.

[2020-02-14 16:58:18,371] ERROR [Worker clientId=connect-2, groupId=dest-mm2] Uncaught exception in herder work thread, exiting:  (org.apache.kafka.connect.runtime.distributed.DistributedHerder:290)
org.apache.kafka.connect.errors.ConnectException: Error while attempting to create/find topic(s) 'mm2-offsets.dest.internal'
    at org.apache.kafka.connect.util.TopicAdmin.createTopics(TopicAdmin.java:262)
    at org.apache.kafka.connect.storage.KafkaOffsetBackingStore$1.run(KafkaOffsetBackingStore.java:99)
    at org.apache.kafka.connect.util.KafkaBasedLog.start(KafkaBasedLog.java:128)
    at org.apache.kafka.connect.storage.KafkaOffsetBackingStore.start(KafkaOffsetBackingStore.java:109)
    at org.apache.kafka.connect.runtime.Worker.start(Worker.java:186)
    at org.apache.kafka.connect.runtime.AbstractHerder.startServices(AbstractHerder.java:121)
    at org.apache.kafka.connect.runtime.distributed.DistributedHerder.run(DistributedHerder.java:277)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.util.concurrent.ExecutionException: org.apache.kafka.common.errors.InvalidReplicationFactorException: Replication factor: 3 larger than available brokers: 1.
    at org.apache.kafka.common.internals.KafkaFutureImpl.wrapAndThrow(KafkaFutureImpl.java:45)
    at org.apache.kafka.common.internals.KafkaFutureImpl.access$000(KafkaFutureImpl.java:32)
    at org.apache.kafka.common.internals.KafkaFutureImpl$SingleWaiter.await(KafkaFutureImpl.java:89)
    at org.apache.kafka.common.internals.KafkaFutureImpl.get(KafkaFutureImpl.java:260)
    at org.apache.kafka.connect.util.TopicAdmin.createTopics(TopicAdmin.java:229)
    ... 11 more
Caused by: org.apache.kafka.common.errors.InvalidReplicationFactorException: Replication factor: 3 larger than available brokers: 1.
[2020-02-14 16:58:18,371] ERROR [Worker clientId=connect-1, groupId=source-mm2] Uncaught exception in herder work thread, exiting:  (org.apache.kafka.connect.runtime.distributed.DistributedHerder:290)
org.apache.kafka.connect.errors.ConnectException: Error while attempting to create/find topic(s) 'mm2-offsets.source.internal'
    at org.apache.kafka.connect.util.TopicAdmin.createTopics(TopicAdmin.java:262)
    at org.apache.kafka.connect.storage.KafkaOffsetBackingStore$1.run(KafkaOffsetBackingStore.java:99)
    at org.apache.kafka.connect.util.KafkaBasedLog.start(KafkaBasedLog.java:128)
    at org.apache.kafka.connect.storage.KafkaOffsetBackingStore.start(KafkaOffsetBackingStore.java:109)
    at org.apache.kafka.connect.runtime.Worker.start(Worker.java:186)
    at org.apache.kafka.connect.runtime.AbstractHerder.startServices(AbstractHerder.java:121)
    at org.apache.kafka.connect.runtime.distributed.DistributedHerder.run(DistributedHerder.java:277)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.util.concurrent.ExecutionException: org.apache.kafka.common.errors.InvalidReplicationFactorException: Replication factor: 3 larger than available brokers: 1.
    at org.apache.kafka.common.internals.KafkaFutureImpl.wrapAndThrow(KafkaFutureImpl.java:45)
    at org.apache.kafka.common.internals.KafkaFutureImpl.access$000(KafkaFutureImpl.java:32)
    at org.apache.kafka.common.internals.KafkaFutureImpl$SingleWaiter.await(KafkaFutureImpl.java:89)
    at org.apache.kafka.common.internals.KafkaFutureImpl.get(KafkaFutureImpl.java:260)
    at org.apache.kafka.connect.util.TopicAdmin.createTopics(TopicAdmin.java:229)
    ... 11 more
Caused by: org.apache.kafka.common.errors.InvalidReplicationFactorException: Replication factor: 3 larger than available brokers: 1.

This error is happening since there is only one broker in my local and mirror maker is trying to create offset topics with replication factor 3. How can I set the config to change the replication factor to 1.

I tried as below, but still the same error. not sure what is the correct config.

mm2.properties

# mm2.properties
name=source->dest
clusters=source, dest

source.bootstrap.servers=localhost:9091
dest.bootstrap.servers=localhost:9092

source->dest.enabled=true

topics=test-3 groups=test-6-group
offsets.storage.replication.factor=1
source.replication.factor=1
dest.replication.factor=1

mm2-offsets.source.internal.replication.factor=1
mm2-offsets.dest.internal.replication.factor=1

Body:
It works after adding the below 2 props.

config.storage.replication.factor=1
status.storage.replication.factor=1


问:
How to get Local Currency for SKProduct | Display IAP Price in Swift
I am trying to display the price of an in app purchase using the local currency, so the correct dollar is displayed for both US & CA as well as Euro, GBP etc.

I know each SKProduct has a price which appears during the transaction as an alert view, this appears when confirming the purchase.

However I want to display the price before confirmation.

I was thinking to do something like this:

```<code>//Products Array
var productsArray: Array<SKProduct!> = []

//Request Products
    func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) {
        if response.products.count != 0 {
            for product in response.products {
                print("\(product.localizedTitle)")
                productsArray.append(product)
            }
        }
        else {
            print("There are no products.")
        }

        if response.invalidProductIdentifiers.count != 0 {
            print("\(response.invalidProductIdentifiers.description)")
        }
     }

let item = SKProduct
  for i in productsArray {
    if i.localizedTitle == "com.Company.App.item1"
      item = i
    }
  }
</code>```

But this doesn't work as i Doesn't seem to have a price property.

Does anybody know how I can set a label text to the price of an iAP using the correct local currency?

For example £1.49 GBP is $1.99 US dollars using Apples Pricing Matrix and outputting the value should match the values of the product price when confirming the transaction.

答:
Simply  you just need to do the following</p>

```<code>product.priceLocale.currencyCode
</code>```

Body:
I am trying to display the price of an in app purchase using the local currency, so the correct dollar is displayed for both US & CA as well as Euro, GBP etc.

I know each SKProduct has a price which appears during the transaction as an alert view, this appears when confirming the purchase.

However I want to display the price before confirmation.

I was thinking to do something like this:

//Products Array
var productsArray: Array<SKProduct!> = []

//Request Products
    func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) {
        if response.products.count != 0 {
            for product in response.products {
                print("\(product.localizedTitle)")
                productsArray.append(product)
            }
        }
        else {
            print("There are no products.")
        }

        if response.invalidProductIdentifiers.count != 0 {
            print("\(response.invalidProductIdentifiers.description)")
        }
     }

let item = SKProduct
  for i in productsArray {
    if i.localizedTitle == "com.Company.App.item1"
      item = i
    }
  }

But this doesn't work as i Doesn't seem to have a price property.

Does anybody know how I can set a label text to the price of an iAP using the correct local currency?

For example £1.49 GBP is $1.99 US dollars using Apples Pricing Matrix and outputting the value should match the values of the product price when confirming the transaction.

Body:
Simply  you just need to do the following

product.priceLocale.currencyCode


问:
How to create a loop 1M with random numbers >100000
My teacher asked me to create a loop that will be executed 1M times.
I tried for(long i=0;i<1000000;i++), but the program is crashing. The maximum number that the program accepts is 10.000.

Any ideas? Is this possible?

Also he asked me to create a random number >100.000. I am using rand();. Should I use a different method?

this is the code:

```<code>start_time = clock();
for(long i=0;i<1000000;i++){
   num1 = rand();
   num2=rand();
   gcd1(num1,num2);
}

end_time = clock();

elapsed_time = (end_time - start_time) / CLOCKS_PER_SEC;

printf( "time is %.3f seconds\n", elapsed_time );
system("pause");
</code>```

This the gcd:

```<code>int gcd1(int x, int y){
    int z;
    if (x<y)
        z=x+1;
    else if (y<x)
        z=y+1;
    do{
        z=z-1;
    }
    while((x%z!=0) or (y%z!=0));
        return z;
    }
}
</code>```

答:
In this statement

```<code>while((x%z!=0) or (y%z!=0));
</code>```

my compiler i(llvm-gcc-4.2) won't compile it.  I'm just learning c but I think you want to change the "or" to "||"

Body:
My teacher asked me to create a loop that will be executed 1M times.
I tried for(long i=0;i<1000000;i++), but the program is crashing. The maximum number that the program accepts is 10.000.

Any ideas? Is this possible?

Also he asked me to create a random number >100.000. I am using rand();. Should I use a different method?

this is the code:

start_time = clock();
for(long i=0;i<1000000;i++){
   num1 = rand();
   num2=rand();
   gcd1(num1,num2);
}

end_time = clock();

elapsed_time = (end_time - start_time) / CLOCKS_PER_SEC;

printf( "time is %.3f seconds\n", elapsed_time );
system("pause");

This the gcd:

int gcd1(int x, int y){
    int z;
    if (x<y)
        z=x+1;
    else if (y<x)
        z=y+1;
    do{
        z=z-1;
    }
    while((x%z!=0) or (y%z!=0));
        return z;
    }
}

Body:
In this statement

while((x%z!=0) or (y%z!=0));

my compiler i(llvm-gcc-4.2) won't compile it.  I'm just learning c but I think you want to change the "or" to "||"


答:
It's cause your module is export as a object with out method xxx.
Example:

```<code>module.exports ={abc : ()=>{}}
</code>```

var xx = require('module') , you can call function abc by : xxx.abc()

you only call abc by const {abc} = require('module')
You can't call xxx in case 2 because there is no method with name xxx

Title: var module = require() or const {module} = require()?

Body:
It's cause your module is export as a object with out method xxx.
Example:

module.exports ={abc : ()=>{}}

var xx = require('module') , you can call function abc by : xxx.abc()

you only call abc by const {abc} = require('module')
You can't call xxx in case 2 because there is no method with name xxx


问:
Echo results from mysqli_Query
I'm making a personal script for my own use, and I need to know how to echo the results from a mysqli_query. My code is as follows:</p>

```<code>$conn = mysqli_connect($servername, $username, $password, $dbname);

if(isset($_POST['commercial'])){
if (isset($_POST['0'])){
    $sql = "SELECT email FROM CommercialEmails WHERE articleid = '$_POST[article]' AND dripid = 1 AND sent='a'";
    $resultsd1 = mysqli_query($conn, $sql);
    echo $resultsd1;
}
if (isset ($_POST['1'])){
    $sql = "SELECT email FROM CommercialEmails WHERE articleid = '$_POST[article]' AND dripid = 2 AND sent='a'";
    $resultsd2 = mysqli_query($conn, $sql);
    echo $resultsd2;
}
if (isset($_POST['2'])){
    $sql = "SELECT email FROM CommercialEmails WHERE articleid = '$_POST[article]' AND dripid = 3 AND sent='a'";
    $resultsd3 = mysqli_query($conn, $sql);
    echo $resultsd3;
}
if (isset ($_POST['3'])){
    $sql = "SELECT email FROM CommercialEmails WHERE articleid = '$_POST[article]' AND dripid = 4 AND sent='a'";
    $resultsd4 = mysqli_query($conn, $sql);
    echo $resultsd4;
}
if (isset ($_POST['4'])){
    $sql = "SELECT email FROM CommercialEmails WHERE articleid = '$_POST[article]' AND dripid = 5 AND sent='a'";
    $resultsd5 = mysqli_query($conn, $sql);
    echo $resultsd5;
}

}
?>
</code>```

答:
You can simply loop on the result object with foreach loop. If you want to fetch all the rows into a PHP variable you can use fetch_all().

```<code>$result = mysqli_query($conn, 'SELECT ...');
foreach($result as $row) {
    print_r($row);
    // do something with each row
}
// or
$result = $conn->('SELECT ...')->fetch_all(MYSQLI_ASSOC);
foreach($result as $row) {
    print_r($row);
    // do something with each row
}
</code>```

However, in your case you should not be using mysqli_query() at all! This leaves you vulnerable to SQL injection. You must use parameter binding, which is available with prepared statements.

For example your fixed query would look like this:

```<code>$stmt = $con->prepare("SELECT email FROM CommercialEmails WHERE articleid = ? AND dripid = 1 AND sent = 'a' ");
$stmt->bind_param('s', $_POST['article']);
$stmt->execute();
$result = $stmt->get_result();
foreach ($result as $row) {
    print_r($row);
}
</code>```

The difference is that my variable is not separate from the SQL, so there is no risk of injection. You should never allow any variable input directly in SQL query. Doing this properly is really not that difficult.

Also, you don't really need to repeat the code so much. You can parameterize dripid too and reduce the number of lines in your code.

Title: Echo results from mysqli_Query

Body:
I'm making a personal script for my own use, and I need to know how to echo the results from a mysqli_query. My code is as follows:

$conn = mysqli_connect($servername, $username, $password, $dbname);

if(isset($_POST['commercial'])){
if (isset($_POST['0'])){
    $sql = "SELECT email FROM CommercialEmails WHERE articleid = '$_POST[article]' AND dripid = 1 AND sent='a'";
    $resultsd1 = mysqli_query($conn, $sql);
    echo $resultsd1;
}
if (isset ($_POST['1'])){
    $sql = "SELECT email FROM CommercialEmails WHERE articleid = '$_POST[article]' AND dripid = 2 AND sent='a'";
    $resultsd2 = mysqli_query($conn, $sql);
    echo $resultsd2;
}
if (isset($_POST['2'])){
    $sql = "SELECT email FROM CommercialEmails WHERE articleid = '$_POST[article]' AND dripid = 3 AND sent='a'";
    $resultsd3 = mysqli_query($conn, $sql);
    echo $resultsd3;
}
if (isset ($_POST['3'])){
    $sql = "SELECT email FROM CommercialEmails WHERE articleid = '$_POST[article]' AND dripid = 4 AND sent='a'";
    $resultsd4 = mysqli_query($conn, $sql);
    echo $resultsd4;
}
if (isset ($_POST['4'])){
    $sql = "SELECT email FROM CommercialEmails WHERE articleid = '$_POST[article]' AND dripid = 5 AND sent='a'";
    $resultsd5 = mysqli_query($conn, $sql);
    echo $resultsd5;
}

}
?>

Body:
You can simply loop on the result object with foreach loop. If you want to fetch all the rows into a PHP variable you can use fetch_all().

$result = mysqli_query($conn, 'SELECT ...');
foreach($result as $row) {
    print_r($row);
    // do something with each row
}
// or
$result = $conn->('SELECT ...')->fetch_all(MYSQLI_ASSOC);
foreach($result as $row) {
    print_r($row);
    // do something with each row
}

However, in your case you should not be using mysqli_query() at all! This leaves you vulnerable to SQL injection. You must use parameter binding, which is available with prepared statements.

For example your fixed query would look like this:

$stmt = $con->prepare("SELECT email FROM CommercialEmails WHERE articleid = ? AND dripid = 1 AND sent = 'a' ");
$stmt->bind_param('s', $_POST['article']);
$stmt->execute();
$result = $stmt->get_result();
foreach ($result as $row) {
    print_r($row);
}

The difference is that my variable is not separate from the SQL, so there is no risk of injection. You should never allow any variable input directly in SQL query. Doing this properly is really not that difficult.

Also, you don't really need to repeat the code so much. You can parameterize dripid too and reduce the number of lines in your code.


问:
Huggingface Transformers ByteLevelBPETokenizer tokenizer not found
I'm trying to run through the (new) tutorial here: https://huggingface.co/blog/how-to-train, but hit an error trying to load the ByteLevelBPETokenizer. I started from an existing conda env and also tried with a totally fresh env, but both give the same error:

Exception has occurred: ImportError
cannot import name 'ByteLevelBPETokenizer' from 'tokenizers' (/home/james/anaconda3/envs/torch/lib/python3.7/site-packages/tokenizers/__init__.py)

Any thoughts as to what might be wrong?

I'm on Ubuntu 18.04, Python 3.7

答:
Okay, turns out the transformers installer pulls an older version (0.0.11). So...

```<code>pip uninstall tokenizers
pip install tokenizers==0.4.2
</code>```

...fixes it.
It does issues a warning: ERROR: transformers 2.4.1 has requirement tokenizers==0.0.11, but you'll have tokenizers 0.4.2 which is incompatible., but this can safely be ignored (this answer came from @julien-c at huggingface/tokenizers).

Body:
Okay, turns out the transformers installer pulls an older version (0.0.11). So...

pip uninstall tokenizers
pip install tokenizers==0.4.2

...fixes it.
It does issues a warning: ERROR: transformers 2.4.1 has requirement tokenizers==0.0.11, but you'll have tokenizers 0.4.2 which is incompatible., but this can safely be ignored (this answer came from @julien-c at huggingface/tokenizers).


问:
Dynamically Created Inputs with Javascript Don't Show Drop Down List
I am building a part that includes text input (which has a drop down list using a database), and dynamically add more of the same inputs. The first input looks like this:

After I add another input dynamically, the second input can't show the drop down list. It looks like this:

I didn't have a js/ajax education so trying to edit the code parts of js which I found on internet, using my java knowledge.

The html part of the first row is as following:

```<code><tr class="no-border" id="articles">
    <td class="text-center" style="padding: 7px;padding-right: 0;padding-left: 0;">
        <i class="fas fa-plus" name="add" id="add"></i>
    </td>
    <td style="padding: 5px;">
        <div class="dropdown">
            <input type="text" class="form-control form-control-sm" name="product1" id="product1" autocomplete="off" required form="purchaseForm" />
        </div>
    </td>
    <td style="padding: 5px; max-width: 40px;">
        <input type="number" class="form-control form-control-sm" step="0.001" required />
    </td>
    <td style="padding: 5px; max-width: 40px;">
        <input type="number" class="form-control form-control-sm" step="0.001" required />
    </td>
</tr>
</code>```

The javascript part to create new row and create drop down list are as the following:

```<code>var i=1;
$('#add').click(function(){
    i++;
    $('#dynamic_field').append('<tr class="no-border" id="row'+i+'"><td class="text-center" style="padding: 7px;padding-right: 0;padding-left: 0;"><button class="btn btn_remove" name="remove" id="'+i+'" type="button" style="padding: 0;"><i class="fas fa-minus"></i></button></td><td style="padding: 5px;"><div class="dropdown"><input type="text" class="form-control form-control-sm" name="product'+i+'" id="product'+i+'" autocomplete="off" required form="purchaseForm" /></div></td><td style="padding: 5px; max-width: 40px;"><input type="number" class="form-control form-control-sm" step="0.001" required /></td><td style="padding: 5px; max-width: 40px;"><input type="number" class="form-control form-control-sm" step="0.001" required /></td></tr>');
});

$(document).on('click', '.btn_remove', function(){
    var button_id = $(this).attr("id");
    $('#row'+button_id+'').remove();
});

for(j = 1; j < (i + 1); j++){
    $('#product'+j).typeahead({
        source: function (query, result) {
            $.ajax({
                url: "searchProducts.php",
                data: 'query=' + query,
                dataType: "json",
                type: "POST",
                success: function (data) {
                    result($.map(data, function (item) {
                        return item;
                    }));
                }
            });
        }
    });
}
</code>```

And yes, dynamically created inputs are named product2, product3, so on... With td and divs are identical with the original one.
Well, I am sure that the problem is a result of my ignorance of javascript working principals. Any help will be appreciated. Thanks all.

答:
The solution is as simple as Mujibur mentioned in comment.
Calling the function to create the drop down list in $('#add').click(function(){, right after creating the row solved it:

I modified the first call for only product1 input instead of trying to loop it in a for loop, and copied the function for each dynamically created product as I don't know how to create functions and call them.

```<code>$('#product1').typeahead({
    source: function (query, result) {
        $.ajax({
            url: "searchProducts.php",
            data: 'query=' + query,
            dataType: "json",
            type: "POST",
            success: function (data) {
                result($.map(data, function (item) {
                    return item;
                }));
            }
        });
    }
});

var i=1;
$('#add').click(function(){
    i++;
    $('#dynamic_field').append('<tr class="no-border" id="row'+i+'"><td class="text-center" style="padding: 7px;padding-right: 0;padding-left: 0;"><button class="btn btn_remove" name="remove" id="'+i+'" type="button" style="padding: 0;"><i class="fas fa-minus"></i></button></td><td style="padding: 5px;"><div class="dropdown"><input type="text" class="form-control form-control-sm" name="product'+i+'" id="product'+i+'" autocomplete="off" required form="purchaseForm" /></div></td><td style="padding: 5px; max-width: 40px;"><input type="number" class="form-control form-control-sm" step="0.001" required /></td><td style="padding: 5px; max-width: 40px;"><input type="number" class="form-control form-control-sm" step="0.001" required /></td></tr>');
    $('#product'+i).typeahead({
    source: function (query, result) {
        $.ajax({
            url: "searchProducts.php",
            data: 'query=' + query,
            dataType: "json",
            type: "POST",
            success: function (data) {
                result($.map(data, function (item) {
                    return item;
                }));
            }
        });
    }
});
});
</code>```

Body:
I am building a part that includes text input (which has a drop down list using a database), and dynamically add more of the same inputs. The first input looks like this:

After I add another input dynamically, the second input can't show the drop down list. It looks like this:

I didn't have a js/ajax education so trying to edit the code parts of js which I found on internet, using my java knowledge.

The html part of the first row is as following:

            <input type="text" class="form-control form-control-sm" name="product1" id="product1" autocomplete="off" required form="purchaseForm" />

        <input type="number" class="form-control form-control-sm" step="0.001" required />

        <input type="number" class="form-control form-control-sm" step="0.001" required />

The javascript part to create new row and create drop down list are as the following:

var i=1;
$('#add').click(function(){
    i++;
    $('#dynamic_field').append('
<button class="btn btn_remove" name="remove" id="'+i+'" type="button" style="padding: 0;"></button>
<input type="text" class="form-control form-control-sm" name="product'+i+'" id="product'+i+'" autocomplete="off" required form="purchaseForm" />
	<input type="number" class="form-control form-control-sm" step="0.001" required />	<input type="number" class="form-control form-control-sm" step="0.001" required />
');
});

$(document).on('click', '.btn_remove', function(){
    var button_id = $(this).attr("id");
    $('#row'+button_id+'').remove();
});

for(j = 1; j < (i + 1); j++){
    $('#product'+j).typeahead({
        source: function (query, result) {
            $.ajax({
                url: "searchProducts.php",
                data: 'query=' + query,
                dataType: "json",
                type: "POST",
                success: function (data) {
                    result($.map(data, function (item) {
                        return item;
                    }));
                }
            });
        }
    });
}

And yes, dynamically created inputs are named product2, product3, so on... With td and divs are identical with the original one.
Well, I am sure that the problem is a result of my ignorance of javascript working principals. Any help will be appreciated. Thanks all.

Body:
The solution is as simple as Mujibur mentioned in comment.
Calling the function to create the drop down list in $('#add').click(function(){, right after creating the row solved it:

I modified the first call for only product1 input instead of trying to loop it in a for loop, and copied the function for each dynamically created product as I don't know how to create functions and call them.

$('#product1').typeahead({
    source: function (query, result) {
        $.ajax({
            url: "searchProducts.php",
            data: 'query=' + query,
            dataType: "json",
            type: "POST",
            success: function (data) {
                result($.map(data, function (item) {
                    return item;
                }));
            }
        });
    }
});

var i=1;
$('#add').click(function(){
    i++;
    $('#dynamic_field').append('<tr class="no-border" id="row'+i+'"><td class="text-center" style="padding: 7px;padding-right: 0;padding-left: 0;"><button class="btn btn_remove" name="remove" id="'+i+'" type="button" style="padding: 0;"><i class="fas fa-minus"></i></button></td><td style="padding: 5px;"><div class="dropdown"><input type="text" class="form-control form-control-sm" name="product'+i+'" id="product'+i+'" autocomplete="off" required form="purchaseForm" /></div></td><td style="padding: 5px; max-width: 40px;"><input type="number" class="form-control form-control-sm" step="0.001" required /></td><td style="padding: 5px; max-width: 40px;"><input type="number" class="form-control form-control-sm" step="0.001" required /></td></tr>');
    $('#product'+i).typeahead({
    source: function (query, result) {
        $.ajax({
            url: "searchProducts.php",
            data: 'query=' + query,
            dataType: "json",
            type: "POST",
            success: function (data) {
                result($.map(data, function (item) {
                    return item;
                }));
            }
        });
    }
});
});


问:
git central repository and Team
I have been playing around with GIT on my local computer.

As I have gain a bit of knowledge using GIT like add, commit, merge, branch, checkout, status.

I still have more to learn but im confuse one thing.. how does git handle team?

For example:

Developer A computer

Developer B computer

Developer C computer

Central repository (Server)

All Developers working on the same project.

From what I understood (correct me if im wrong).. A ,B and C developers push their branch (master?) to central repository via SSH remote.

But on the central repository, how do I get information or which files (or branch?) that has been pushed from the developers... What would it look like on the central repository?

On the central repository, how would handle merges developers work?

Thanks.

答:
May I suggest that you take open reading Pro Git, and freely distrubuted book about Git: http://progit.org/

And in particular the chapter about maintaining a project: http://progit.org/book/ch5-3.html

Happy travels ;)

Title: git central repository and Team