问:
Test PHP headers with PHPUnit
I'm trying to use PHPunit to test a class that outputs some custom headers.

The problem is that on my machine this:

```<code><?php

class HeadersTest extends PHPUnit_Framework_TestCase {

    public function testHeaders()
    {
        ob_start();

        header('Location: foo');
        $headers_list = headers_list();
        header_remove();

        ob_clean();

        $this->assertContains('Location: foo', $headers_list);
    }
}
</code>```

or even this:

```<code><?php

class HeadersTest extends PHPUnit_Framework_TestCase {

    public function testHeaders()
    {
        ob_start();

        header('Location: foo');
        header_remove();

        ob_clean();
    }
}
</code>```

return this error:

```<code>name@host [~/test]# phpunit --verbose HeadersTest.php
PHPUnit 3.6.10 by Sebastian Bergmann.

E

Time: 0 seconds, Memory: 2.25Mb

There was 1 error:

1) HeadersTest::testHeaders
Cannot modify header information - headers already sent by (output started at /usr/local/lib/php/PHPUnit/Util/Printer.php:173)

/test/HeadersTest.php:9

FAILURES!
Tests: 1, Assertions: 0, Errors: 1.
</code>```

This looks as if there is something else outputting to the terminal before the test runs even though there is no other file included and there is no other character before the beginning of the PHP tag. Could it be something inside PHPunit that is causing this?

What could the issue be?

答:
Use --stderr parameter for getting headers from PHPUnit after your tests.</p>

```<code>phpunit --stderr
</code>```

Title: Test PHP headers with PHPUnit

Body:
I'm trying to use PHPunit to test a class that outputs some custom headers.

The problem is that on my machine this:

<?php

class HeadersTest extends PHPUnit_Framework_TestCase {

    public function testHeaders()
    {
        ob_start();

        header('Location: foo');
        $headers_list = headers_list();
        header_remove();

        ob_clean();

        $this->assertContains('Location: foo', $headers_list);
    }
}

or even this:

<?php

class HeadersTest extends PHPUnit_Framework_TestCase {

    public function testHeaders()
    {
        ob_start();

        header('Location: foo');
        header_remove();

        ob_clean();
    }
}

return this error:

name@host [~/test]# phpunit --verbose HeadersTest.php
PHPUnit 3.6.10 by Sebastian Bergmann.

E

Time: 0 seconds, Memory: 2.25Mb

There was 1 error:

1) HeadersTest::testHeaders
Cannot modify header information - headers already sent by (output started at /usr/local/lib/php/PHPUnit/Util/Printer.php:173)

/test/HeadersTest.php:9

FAILURES!
Tests: 1, Assertions: 0, Errors: 1.

This looks as if there is something else outputting to the terminal before the test runs even though there is no other file included and there is no other character before the beginning of the PHP tag. Could it be something inside PHPunit that is causing this?

What could the issue be?

Body:
Use --stderr parameter for getting headers from PHPUnit after your tests.

phpunit --stderr


来源: stackexchange

问:
Getting error when calling a method inside observable which returns another observable
I am new to angular and observable. I have tried flatMap, swithMap and concatMap, but nothing helps.  I have got the error " You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable." When the code of switch case 1 runs of inputprocessing method,while the default case works completely fine.

app.component.ts

```<code> export class AppComponent implements OnInit, AfterViewChecked, OnChanges {
  ProcessInput(input: string, session: string): void {
    this.appService
      .ProcessInput(input, session)//this works fine and returns the response.
      .pipe(
        concatMap((res: any) => {
          return this.inputProcessing.inputProcessing(res);
        })
      )
      .subscribe(
        res => {
          this.arr.push("TEST");
        },
        err => {
          console.log(err);
        }
      );
  }
  }
</code>```

inputprocessing.service.ts

```<code>import "reflect-metadata";
import { Injectable } from "@angular/core";
import { Container, inject, injectable, AsyncContainerModule } from "inversify";
import { OutputResponse } from "../response";
import { PrescriptionStatus } from "src/Classes/PrescriptionStatus";
import { service } from "./service.service";
import { HttpClient } from "@angular/common/http";
import { CourierMode } from "../enums/CourierMode";
import { Observable, of } from "rxjs";
import { switchMap, flatMap, concatMap } from "rxjs/operators";
import { PrescriptionStatusMain } from "src/models/PrescriptionStatusResponse";

@Injectable({
  providedIn: "root"
})
export class InputprocessingService {
  constructor(private service: service,private http: HttpClient) {}

  responseText: string;
  returnMessage: string;
  inputProcessing(response: OutputResponse): Observable<any> {

    this.responseText = response.output.generic[0].text;
    //works completely fine with default case, but when case 1: runs it gave an error
    switch (this.responseText) {
      case "1": {

        const obsFail = new Observable(observer => {
          observer.next(this.returnMessage);
          observer.error();
          observer.complete();
        });

        this.service.getStatus().pipe(
          concatMap((res: StatusMain) => {
            return obsFail ;
          })
        );
        break;
      }

      default: {
        const obs = new Observable(observer => {
          observer.next(this.responseText);
          observer.complete();
        });
        return obs;
      }
    }
  }
}
</code>```

service.ts

```<code>import * as request from "request";
import * as request_promise from "request-promise-native";
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { StatusMain } from "src/models/StatusResponse";
import { Observable } from "rxjs";
@Injectable()
export class service {
  constructor(private http: HttpClient) {}

  getStatus(): Observable<StatusMain> {
    const body = { bdate: "1999/05/01" };
    return this.http.post<StatusMain>(
      "http://localhost:49995/api/Status",
      body
    );
  }
}
</code>```

答:
inputprocessing.service.ts
This code resolved the issue.

```<code>@Injectable({
      providedIn: "root"
    })
    export class InputprocessingService {
      constructor(private service: service,private http: HttpClient) {}

      responseText: string;
      returnMessage: string;
      inputProcessing(response: OutputResponse): Observable<any> {

        this.responseText = response.output.generic[0].text;
        let returnObservable;

        //works completely fine with default case, but when case 1: runs it gave an error
        switch (this.responseText) {
          case "1": {
    //This line solved the error.
            return this.service.getStatus().pipe(map(res=>{return res}));
            break;
          }

          default: {
            returnObservable = new Observable(observer => {
              observer.next(this.responseText);
              observer.complete();
            });
          }
        }

        return returnObservable;
      }
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am new to angular and observable. I have tried flatMap, swithMap and concatMap, but nothing helps.  I have got the error " You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable." When the code of switch case 1 runs of inputprocessing method,while the default case works completely fine.

app.component.ts

 export class AppComponent implements OnInit, AfterViewChecked, OnChanges {
  ProcessInput(input: string, session: string): void {
    this.appService
      .ProcessInput(input, session)//this works fine and returns the response.
      .pipe(
        concatMap((res: any) => {
          return this.inputProcessing.inputProcessing(res);
        })
      )
      .subscribe(
        res => {
          this.arr.push("TEST");
        },
        err => {
          console.log(err);
        }
      );
  }
  }

inputprocessing.service.ts

import "reflect-metadata";
import { Injectable } from "@angular/core";
import { Container, inject, injectable, AsyncContainerModule } from "inversify";
import { OutputResponse } from "../response";
import { PrescriptionStatus } from "src/Classes/PrescriptionStatus";
import { service } from "./service.service";
import { HttpClient } from "@angular/common/http";
import { CourierMode } from "../enums/CourierMode";
import { Observable, of } from "rxjs";
import { switchMap, flatMap, concatMap } from "rxjs/operators";
import { PrescriptionStatusMain } from "src/models/PrescriptionStatusResponse";

@Injectable({
  providedIn: "root"
})
export class InputprocessingService {
  constructor(private service: service,private http: HttpClient) {}

  responseText: string;
  returnMessage: string;
  inputProcessing(response: OutputResponse): Observable<any> {

    this.responseText = response.output.generic[0].text;
    //works completely fine with default case, but when case 1: runs it gave an error
    switch (this.responseText) {
      case "1": {

        const obsFail = new Observable(observer => {
          observer.next(this.returnMessage);
          observer.error();
          observer.complete();
        });

        this.service.getStatus().pipe(
          concatMap((res: StatusMain) => {
            return obsFail ;
          })
        );
        break;
      }

      default: {
        const obs = new Observable(observer => {
          observer.next(this.responseText);
          observer.complete();
        });
        return obs;
      }
    }
  }
}

service.ts

import * as request from "request";
import * as request_promise from "request-promise-native";
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { StatusMain } from "src/models/StatusResponse";
import { Observable } from "rxjs";
@Injectable()
export class service {
  constructor(private http: HttpClient) {}

  getStatus(): Observable<StatusMain> {
    const body = { bdate: "1999/05/01" };
    return this.http.post<StatusMain>(
      "http://localhost:49995/api/Status",
      body
    );
  }
}

Body:
inputprocessing.service.ts
This code resolved the issue.

@Injectable({
      providedIn: "root"
    })
    export class InputprocessingService {
      constructor(private service: service,private http: HttpClient) {}

      responseText: string;
      returnMessage: string;
      inputProcessing(response: OutputResponse): Observable<any> {

        this.responseText = response.output.generic[0].text;
        let returnObservable;

        //works completely fine with default case, but when case 1: runs it gave an error
        switch (this.responseText) {
          case "1": {
    //This line solved the error.
            return this.service.getStatus().pipe(map(res=>{return res}));
            break;
          }

          default: {
            returnObservable = new Observable(observer => {
              observer.next(this.responseText);
              observer.complete();
            });
          }
        }

        return returnObservable;
      }
    }


问:
missing permissions for test user
I use a watcherList, which is supported by the official golang kubernetes lib, to get notifications about created, updated and removed services inside a kubernetes namespace. Here the snippet.

func (kc *KubernetesCollector) streamEvents(ctx context.Context) {
    kc.debugChannel <- fmt.Sprintf("Start streaming events from kubernetes API")

    watchList := cache.NewListWatchFromClient(kc.k8sClient.RESTClient(), "services", kc.k8sNamespace, fields.Everything())

    notificationCallbackToAddService := func(svc interface{}) {
        service := svc.(*v1.Service)
        kc.serviceNotificationChannel <- &serviceNotification{service, "add"}
    }

    notificationCallbackToDeleteService := func(svc interface{}) {
        service := svc.(*v1.Service)
        kc.serviceNotificationChannel <- &serviceNotification{service, "remove"}
    }

    callbacks := cache.ResourceEventHandlerFuncs{
        AddFunc:    notificationCallbackToAddService,
        DeleteFunc: notificationCallbackToDeleteService,
    }

    _, controller := cache.NewInformer(watchList, &v1.Service{}, time.Second*0, callbacks)
    go controller.Run(ctx.Done())
}
```

<p>In my test I declare the <code>kc.k8sClient</code> over the public api address, which is defined in <code>k8sAPI</code> variable. Additionally I set the bearer token to authenticate against the cluster and skip to verify the insecure ssl certificate.</p>

<pre class="lang-golang prettyprint-override"><code>func TestK8sWatchList(t *testing.T) {
    require := require.New(t)
    ...
    k8sConfig, err := clientcmd.BuildConfigFromFlags(k8sAPI, "")
    require.NoError(err)

    k8sConfig.BearerToken = "<bearerToken>"
    k8sConfig.Transport = &http.Transport{
        TLSClientConfig: &tls.Config{
            InsecureSkipVerify: true,
        },
    }
    k8sClient, err := kubernetes.NewForConfig(k8sConfig)

    k8sCollector := NewK8sCollector(k8sClient, k8sNamespace)

    ...
}
</code>```

When I execute the test, I receive the following error messages:

go test -v -timeout 500s <replaced>/t1k/pkg/collector -run TestK8sWatchList
=== RUN   TestK8sWatchList
11.02.2020 16:55:55 DEBUG: Start streaming events from kubernetes API
E0211 16:55:51.706530  121803 reflector.go:153] pkg/mod/k8s.io/client-go@v0.0.0-20200106225816-7985654fe8ee/tools/cache/reflector.go:105: Failed to list *v1.Service: forbidden: User "system:serviceaccount:t1k:t1k-test-serviceaccount" cannot get path "/namespaces/t1k/services"
E0211 16:55:52.707520  121803 reflector.go:153] pkg/mod/k8s.io/client-go@v0.0.0-20200106225816-7985654fe8ee/tools/cache/reflector.go:105: Failed to list *v1.Service: forbidden: User "system:serviceaccount:t1k:t1k-test-serviceaccount" cannot get path "/namespaces/t1k/services"
E0211 16:55:53.705539  121803 reflector.go:153] pkg/mod/k8s.io/client-go@v0.0.0-20200106225816-7985654fe8ee/tools/cache/reflector.go:105: Failed to list *v1.Service: forbidden: User "system:serviceaccount:t1k:t1k-test-serviceaccount" cannot get path "/namespaces/t1k/services"
```

<p>I don't understand why I get the error message, because the service account "t1k-test-serviceaccount" has in my opinion all required permissions. Now the defined service account, role and rolebinding for the test user.</p>

```apiVersion: v1
kind: ServiceAccount
metadata:
  namespace: t1k
  name: t1k-test-serviceaccount
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: t1k
  name: t1k-test-role
rules:
- apiGroups: [""]   # "" indicates the core API group
  resources: ["*"]
  verbs: ["*"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  namespace: t1k
  name: t1k-test-rolebinding
subjects:
- name: t1k-test-serviceaccount
  kind: ServiceAccount
  apiGroup: ""
roleRef:
  name: t1k-test-role
  kind: Role
  apiGroup: rbac.authorization.k8s.io
```

Additional informations:

kubeadm version 1.15.9

kubectl version 1.17.2

golib versions

k8s.io/api v0.17.2

k8s.io/apimachinery v0.17.2

k8s.io/client-go v0.0.0-20200106225816-7985654fe8ee

k8s.io/utils v0.0.0-20200117235808-5f6fbceb4c31 // indirect

答:
I found the solution. The k8sClientSet attribut of the KubernetesCollector struct was a pointer. The reflection function of the package pkg/mod/k8s.io/client-go@v0.0.0-20200106225816-7985654fe8ee can not handle pointer objects.

type KubernetesCollector struct {
    ...
    k8sClient *kubernetes.ClientSet
    namespace string
    ...
}
```

<p>I replaced the k8sClient with the <code>CoreV1Interface</code> from <code>k8s.io/client-go/kubernetes/typed/core/v1</code>. Therefore I changed the call for the ListWatch.</p>

<pre class="lang-golang prettyprint-override"><code>type KubernetesCollector struct {
   ....
   iface         corev1.CoreV1Interface
   namespace     string
   ....
}

func (kc *KubernetesCollector) start(ctx context.Context) {
    watchList := cache.NewListWatchFromClient(kc.iface.RESTClient(), "services", kc.namespace, fields.Everything())
    ....
}
</code>```

Title: missing permissions for test user

Body:
I use a watcherList, which is supported by the official golang kubernetes lib, to get notifications about created, updated and removed services inside a kubernetes namespace. Here the snippet.

func (kc *KubernetesCollector) streamEvents(ctx context.Context) {
    kc.debugChannel <- fmt.Sprintf("Start streaming events from kubernetes API")

    watchList := cache.NewListWatchFromClient(kc.k8sClient.RESTClient(), "services", kc.k8sNamespace, fields.Everything())

    notificationCallbackToAddService := func(svc interface{}) {
        service := svc.(*v1.Service)
        kc.serviceNotificationChannel <- &serviceNotification{service, "add"}
    }

    notificationCallbackToDeleteService := func(svc interface{}) {
        service := svc.(*v1.Service)
        kc.serviceNotificationChannel <- &serviceNotification{service, "remove"}
    }

    callbacks := cache.ResourceEventHandlerFuncs{
        AddFunc:    notificationCallbackToAddService,
        DeleteFunc: notificationCallbackToDeleteService,
    }

    _, controller := cache.NewInformer(watchList, &v1.Service{}, time.Second*0, callbacks)
    go controller.Run(ctx.Done())
}

In my test I declare the kc.k8sClient over the public api address, which is defined in k8sAPI variable. Additionally I set the bearer token to authenticate against the cluster and skip to verify the insecure ssl certificate.

func TestK8sWatchList(t *testing.T) {
    require := require.New(t)
    ...
    k8sConfig, err := clientcmd.BuildConfigFromFlags(k8sAPI, "")
    require.NoError(err)

    k8sConfig.BearerToken = "<bearerToken>"
    k8sConfig.Transport = &http.Transport{
        TLSClientConfig: &tls.Config{
            InsecureSkipVerify: true,
        },
    }
    k8sClient, err := kubernetes.NewForConfig(k8sConfig)

    k8sCollector := NewK8sCollector(k8sClient, k8sNamespace)

    ...
}

When I execute the test, I receive the following error messages:

go test -v -timeout 500s <replaced>/t1k/pkg/collector -run TestK8sWatchList
=== RUN   TestK8sWatchList
11.02.2020 16:55:55 DEBUG: Start streaming events from kubernetes API
E0211 16:55:51.706530  121803 reflector.go:153] pkg/mod/k8s.io/client-go@v0.0.0-20200106225816-7985654fe8ee/tools/cache/reflector.go:105: Failed to list *v1.Service: forbidden: User "system:serviceaccount:t1k:t1k-test-serviceaccount" cannot get path "/namespaces/t1k/services"
E0211 16:55:52.707520  121803 reflector.go:153] pkg/mod/k8s.io/client-go@v0.0.0-20200106225816-7985654fe8ee/tools/cache/reflector.go:105: Failed to list *v1.Service: forbidden: User "system:serviceaccount:t1k:t1k-test-serviceaccount" cannot get path "/namespaces/t1k/services"
E0211 16:55:53.705539  121803 reflector.go:153] pkg/mod/k8s.io/client-go@v0.0.0-20200106225816-7985654fe8ee/tools/cache/reflector.go:105: Failed to list *v1.Service: forbidden: User "system:serviceaccount:t1k:t1k-test-serviceaccount" cannot get path "/namespaces/t1k/services"

I don't understand why I get the error message, because the service account "t1k-test-serviceaccount" has in my opinion all required permissions. Now the defined service account, role and rolebinding for the test user.

apiVersion: v1
kind: ServiceAccount
metadata:
  namespace: t1k
  name: t1k-test-serviceaccount
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: t1k
  name: t1k-test-role
rules:
- apiGroups: [""]   # "" indicates the core API group
  resources: ["*"]
  verbs: ["*"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  namespace: t1k
  name: t1k-test-rolebinding
subjects:
- name: t1k-test-serviceaccount
  kind: ServiceAccount
  apiGroup: ""
roleRef:
  name: t1k-test-role
  kind: Role
  apiGroup: rbac.authorization.k8s.io

Additional informations:

kubeadm version 1.15.9

kubectl version 1.17.2

golib versions

k8s.io/api v0.17.2

k8s.io/apimachinery v0.17.2

k8s.io/client-go v0.0.0-20200106225816-7985654fe8ee

k8s.io/utils v0.0.0-20200117235808-5f6fbceb4c31 // indirect

Body:
I found the solution. The k8sClientSet attribut of the KubernetesCollector struct was a pointer. The reflection function of the package pkg/mod/k8s.io/client-go@v0.0.0-20200106225816-7985654fe8ee can not handle pointer objects.

type KubernetesCollector struct {
    ...
    k8sClient *kubernetes.ClientSet
    namespace string
    ...
}

I replaced the k8sClient with the CoreV1Interface from k8s.io/client-go/kubernetes/typed/core/v1. Therefore I changed the call for the ListWatch.

type KubernetesCollector struct {
   ....
   iface         corev1.CoreV1Interface
   namespace     string
   ....
}

func (kc *KubernetesCollector) start(ctx context.Context) {
    watchList := cache.NewListWatchFromClient(kc.iface.RESTClient(), "services", kc.namespace, fields.Everything())
    ....
}


问:
multi lingual website html setup
I am currently setting up a multi lingual website that is to support different languages, english and spanish for starters and french in the future.

I have the content etc localized but now I want to make sure that have all meta tags and http headers, lang attribute on body tag, xml:lang etc are correct for the culture selected at the time.

Is there anywhere outline on the internet that outlines what needs to be configured for multi lingual html sites? Anyone have any advice/tips on this.

答:
As far as I know, there are no such "must haves". All of these are optional (maybe with an exception of character encoding). What you might need:

Character encoding declaration

That is for sure, you need content type and character encoding declaration:

```<code><META http-equiv="Content-Type" content="text/html; charset=UTF-8">
</code>```

For obvious reasons UTF-8 is recommended.

Language declaration

Language could be declared with lang attribute, which is defined for most of HTML elements. Therefore you can set it document-wide, body-wide or anywhere you please:

```<code><html lang="de">
  <body lang="es">
     <p lang="pl">Jakiś tekst</p>
  </body>
</html>
</code>```

Of course that would be nice if these tags make sense (unlike in example above), so it is common to set lang tag for body and for paragraphs (if it happens that given paragraph is in different language than body).

The content of lang attribute is two letter ISO 639 language code (ISO 639-1 to be precise). The same applies to xml:lang (which could be declared in XHTML web sites).

Directionality

If it happens that you will face the challenge of localizing web site into Hebrew, Arabic or other Right-To-Left language, you will also need to apply dir attribute. Just like in case of lang, this attribute is optional and could be placed almost anywhere. If it is omitted, dir="LTR" is assumed. Example:

```<code><body lang="ar" dir="RTL">
</code>```

That's I am afraid it. Multilingual support for web sites is still kind of grey area, and support is not the best to say the least. For example, you would need to care yourself for providing valid formatting of dates, numbers, currencies and similar artifacts.

Also, you would need to remember not to use gems like CSS text-transform: uppercase | lowercase, JavaScript's uppercase and lowercase related functions, as well as JavaScript's toLocalizedString() functions. These gems are very unreliable and doesn't work correctly.

ContentLicense: CC BY-SA 3.0

Title: multi lingual website html setup

Body:
As far as I know, there are no such "must haves". All of these are optional (maybe with an exception of character encoding). What you might need:

Character encoding declaration

That is for sure, you need content type and character encoding declaration:

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">

For obvious reasons UTF-8 is recommended.

Language declaration

Language could be declared with lang attribute, which is defined for most of HTML elements. Therefore you can set it document-wide, body-wide or anywhere you please:

<html lang="de">
  <body lang="es">
     <p lang="pl">Jakiś tekst</p>
  </body>
</html>

Of course that would be nice if these tags make sense (unlike in example above), so it is common to set lang tag for body and for paragraphs (if it happens that given paragraph is in different language than body).

The content of lang attribute is two letter ISO 639 language code (ISO 639-1 to be precise). The same applies to xml:lang (which could be declared in XHTML web sites).

Directionality

If it happens that you will face the challenge of localizing web site into Hebrew, Arabic or other Right-To-Left language, you will also need to apply dir attribute. Just like in case of lang, this attribute is optional and could be placed almost anywhere. If it is omitted, dir="LTR" is assumed. Example:

<body lang="ar" dir="RTL">

That's I am afraid it. Multilingual support for web sites is still kind of grey area, and support is not the best to say the least. For example, you would need to care yourself for providing valid formatting of dates, numbers, currencies and similar artifacts.

Also, you would need to remember not to use gems like CSS text-transform: uppercase | lowercase, JavaScript's uppercase and lowercase related functions, as well as JavaScript's toLocalizedString() functions. These gems are very unreliable and doesn't work correctly.


问:
How to delete few middle commits in gitlab?
I need a help in git/gitlab.
I got gitlab with test repo e.g. 6 commits:
A->B->C->D->E->F
Commit A is first and F the last one.
How Can I do this: remove commits B,C,D,E?
I want to have only the first one and last one"
A->F
I do it because my repo weights a lot.
What commands shoul I enter?</p>

答:
Generally you would like to do is to use interactive rebase as suggested by another answer.

If you are familiar with how rebase works, you can also do something like:

```<code>git rebase rev-of-E rev-of-F --onto rev-of-A
</code>```

e.g. if your HEAD is at F, you can do

```<code>git rebase HEAD~ HEAD --onto HEAD~5
</code>```

Body:
Generally you would like to do is to use interactive rebase as suggested by another answer.

If you are familiar with how rebase works, you can also do something like:

git rebase rev-of-E rev-of-F --onto rev-of-A

e.g. if your HEAD is at F, you can do

git rebase HEAD~ HEAD --onto HEAD~5


问:
pushing multi dimentional array within array js
I have declared an array variable and I want to push new data but it doesn't work. below is my code

```<code>let locations = [
  [2.4333,4.45333],
  [3.45454,5.222325]
]
</code>```

here is the code pushing to locations variable

```<code> for (var j=0;j<res.length;j++) {
    locations.push([res[j]['lat'], res[j]['long']])
    //4.3333, 4.33444
 }
</code>```

and this is the code to display

```<code>for (i = 0; i < locations.length; i++) {
  position: new google.maps.LatLng(locations[i][0], locations[i][1])
}
</code>```

This is what I'm getting in console log

```<code>> Array[]
console.log(locations.length)// 0
</code>```

Thanks

答:
You have used the wrong variable in loop.</p>

```<code>for (var j=0;j<res.length;j++) {
    latlong.push([res[j]['lat'], res[j]['long']])
 }
</code>```

Body:
I have declared an array variable and I want to push new data but it doesn't work. below is my code

let locations = [
  [2.4333,4.45333],
  [3.45454,5.222325]
]

here is the code pushing to locations variable

 for (var j=0;j<res.length;j++) {
    locations.push([res[j]['lat'], res[j]['long']])
    //4.3333, 4.33444
 }

and this is the code to display

for (i = 0; i < locations.length; i++) {
  position: new google.maps.LatLng(locations[i][0], locations[i][1])
}

This is what I'm getting in console log

> Array[]
console.log(locations.length)// 0

Thanks

Body:
You have used the wrong variable in loop.

for (var j=0;j<res.length;j++) {
    latlong.push([res[j]['lat'], res[j]['long']])
 }


问:
The product definition is not pulling in dependencies from the required features
I am converting a plug-in-based RCP product to a feature-based one. I have grouped the plug-ins into 4 features and have created a traget definition containing all the required plug-ins.

When I view the dependency lists of each new feature, they look about right but when I run the product, I get a long list of Missing Constraint errors which seem to refer to plug-ins listed the Dependencies of my features.

Do I need to explicitly define these plug-ins as Included plug-ins in each feature definition? Why isn't the project definition itself loading the plug-ins automatically?

答:
The 'Run Configuration' for your RCP in the 'Run > Run Configurations...' menu determines what is available when your run your code from within Eclipse.

On the 'Plug-ins' tab you can select 'features selected below' on the 'Launch with' combo to select your features. Use the 'Validate Plug-ins' button to check the selection.

For building (maven + tycho is strongly recommended) the features in the .product file are used.

On the 'Overview' tab of the .product editor select 'features' for 'the product configuration is based on' combo

On the 'Content' tab add your features.

Example contents configuration:

Example run configuration:


问:
Store array from firebase database
l am trying to build a project using Angular and angularfire. My project is about drawing polygons using leaflet map, then pushing coordinates of a polygon to a database. I have successfully pushed an array to the database, but I have a problem to retrieve coordinates from database.

Database Structure :

```<code>{
  "Locations" : {
    "-M0M9kqEbE0FVMzIZAg0" : {
      "text" : [ [ {
        "lat" : 35.97800618085566,
        "lng" : 42.03369140625001
      }, {
        "lat" : 33.88865750124075,
        "lng" : 41.46240234375001
      } ] ]
    }
  }
}
</code>```

I am trying to store array above in class ts not in html.

My code :

```<code>    export class WeatherNowComponent {

      itemsRef: AngularFireList<any>;
      items: Observable<any[]>;

      coords :any
      constructor(private db: AngularFireDatabase) {

        this.itemsRef = this.db.list('Locations')
        // Use snapshotChanges().map() to store the key
        this.items = this.itemsRef.snapshotChanges().pipe(
          map(changes =>
            changes.map(c => ({ key: c.payload.key, ...c.payload.val() }))
          )
        );

        this.db.list('Locations').snapshotChanges().subscribe((markers: any) => {

          console.log(markers)
          markers.forEach(singlemarker => {
            console.log(singlemarker)

   // ADD COORDS to MAP POLYGON
    var polygon = L.polygon([singlemarker.text.lat,singlemarker.text.lng], {color: 'red'}).addTo(this.map);
          });
        });

        console.log(this.items)
      }

    }
</code>```

So I have only key array in console log without rest of array objects.

答:
If you calling a spread operator on purpose because it is an array try assigning it to a property value in the object literal definition.

```<code>{ key: c.payload.key, values: ...c.payload.val() }
</code>```

Edit: Based on your comment I would still say still just assign the array of coordinates (lat/lng property pairs objects) to the values property to iterate over later. I assume the .val() method must return the array of those values. Otherwise please post what .val() returns.

Also, I noticed something else you should check.

The observable is calling the RxJs pipe() method to map but I didn't notice a subscribe() anywhere. While .pipe() lets you map and filter the callback needs a subscribe.

Edit #2: Based on your second comment below. What you are asking for is still unclear to me. So I will give two more possible answers based on the comment: "okay , my question is how i can get array directly ?"

```<code>// Possibility #1
// Simplest is to store off the returned data into the coords variable for later processing.
// You can then get the array directly at any later point just by accessing the coords

this.db.list('Locations').snapshotChanges().subscribe((markers: any) => {
    coords = markers;
});

// Possibility #2
// Since the data structure you are using works like a dictionary data structure
// Define some structures to store off the data and get at the array data directly later

// Define this somewhere outside your class
interface ICoordinate {
    lat: string;
    lng: string;
}

// Initialize coordinate dictionary
let coordinates: { [key: string] : ICoordinate[]; } = {};

// Retrieve locations and store off coordinates to get at the array data directly
this.db.list('Locations')
    .snapshotChanges()
    .subscribe((markers: any) => {
        coordinates[markers.key] = ICoordinate[];

        markers.forEach(singlemarker => {
           coordinates[markers.key].push({ lat: singlemarker.text.lat, lng: singlemarker.text.lng });
        });
    });
</code>```

Edit #3: Oh yes, I see. The array needed to be initialized before adding to it.

Updated code. Also, as an additional help to you on future questions it is very helpful if you have a snippet. S.O. question to refer to: I've been told to create a "runnable" example with "Stack Snippets", how do I do that?

Hopefully that helps.

Happy coding!

Title: Store array from firebase database

Body:
l am trying to build a project using Angular and angularfire. My project is about drawing polygons using leaflet map, then pushing coordinates of a polygon to a database. I have successfully pushed an array to the database, but I have a problem to retrieve coordinates from database.

Database Structure :

{
  "Locations" : {
    "-M0M9kqEbE0FVMzIZAg0" : {
      "text" : [ [ {
        "lat" : 35.97800618085566,
        "lng" : 42.03369140625001
      }, {
        "lat" : 33.88865750124075,
        "lng" : 41.46240234375001
      } ] ]
    }
  }
}

I am trying to store array above in class ts not in html.

My code :

    export class WeatherNowComponent {

      itemsRef: AngularFireList<any>;
      items: Observable<any[]>;

      coords :any
      constructor(private db: AngularFireDatabase) {

        this.itemsRef = this.db.list('Locations')
        // Use snapshotChanges().map() to store the key
        this.items = this.itemsRef.snapshotChanges().pipe(
          map(changes =>
            changes.map(c => ({ key: c.payload.key, ...c.payload.val() }))
          )
        );

        this.db.list('Locations').snapshotChanges().subscribe((markers: any) => {

          console.log(markers)
          markers.forEach(singlemarker => {
            console.log(singlemarker)

   // ADD COORDS to MAP POLYGON
    var polygon = L.polygon([singlemarker.text.lat,singlemarker.text.lng], {color: 'red'}).addTo(this.map);
          });
        });

        console.log(this.items)
      }

    }

So I have only key array in console log without rest of array objects.

Body:
If you calling a spread operator on purpose because it is an array try assigning it to a property value in the object literal definition.

{ key: c.payload.key, values: ...c.payload.val() }

Edit: Based on your comment I would still say still just assign the array of coordinates (lat/lng property pairs objects) to the values property to iterate over later. I assume the .val() method must return the array of those values. Otherwise please post what .val() returns.

Also, I noticed something else you should check.

The observable is calling the RxJs pipe() method to map but I didn't notice a subscribe() anywhere. While .pipe() lets you map and filter the callback needs a subscribe.

Edit #2: Based on your second comment below. What you are asking for is still unclear to me. So I will give two more possible answers based on the comment: "okay , my question is how i can get array directly ?"

// Possibility #1
// Simplest is to store off the returned data into the coords variable for later processing.
// You can then get the array directly at any later point just by accessing the coords

this.db.list('Locations').snapshotChanges().subscribe((markers: any) => {
    coords = markers;
});

// Possibility #2
// Since the data structure you are using works like a dictionary data structure
// Define some structures to store off the data and get at the array data directly later

// Define this somewhere outside your class
interface ICoordinate {
    lat: string;
    lng: string;
}

// Initialize coordinate dictionary
let coordinates: { [key: string] : ICoordinate[]; } = {};

// Retrieve locations and store off coordinates to get at the array data directly
this.db.list('Locations')
    .snapshotChanges()
    .subscribe((markers: any) => {
        coordinates[markers.key] = ICoordinate[];

        markers.forEach(singlemarker => {
           coordinates[markers.key].push({ lat: singlemarker.text.lat, lng: singlemarker.text.lng });
        });
    });

Edit #3: Oh yes, I see. The array needed to be initialized before adding to it.

Updated code. Also, as an additional help to you on future questions it is very helpful if you have a snippet. S.O. question to refer to: I've been told to create a "runnable" example with "Stack Snippets", how do I do that?

Hopefully that helps.

Happy coding!


问:
Django MultiSelectField: Make some choices readonly when editing
I'm using Django MultiSelectField to store a project's category/categories.

My requirement is as follows: A project can have one or more categories. When creating a project initially, the user should be able to select any of the categories listed in the select field. If a user selects 'Not Applicable', then the other categories become disabled.

When editing a project, user should not be able to unselect the originally selected categorie(s), but he can add/select other categories in addition to the original ones. The originally selected categories should be readonly when editing.

My model looks like this:

```<code>from multiselectfield import MultiSelectField
(...)

class Project(models.Model):

    CAT_0 = 0
    CAT_1 = 1
    CAT_2 = 2
    CAT_3 = 3

    PROJECT_CATEGORIES = (
        (CAT_0, _('Not Applicable')),
        (CAT_1, _('My Category 1')),
        (CAT_2, _('My Category 2')),
        (CAT_3, _('My Category 3')),
    )
    (...)
    project_categories =  MultiSelectField(choices=PROJECT_CATEGORIES, max_choices=3, default=CAT_0)
</code>```

And my forms.py

```<code>class ProjectForm(ModelForm):

    class Meta:
        model = Project
        (...)

    def __init__(self, *args, **kwargs):
        super(ProjectForm, self).__init__(*args, **kwargs)
        (...)

        if self.instance.pk:
            for choice in self.fields['project_categories'].choices:
                if str(choice[0]) in self.instance.project_categories:
                    #TODO: Make this choice to be readonly i.e. user should not be able to uncheck it
                else:
                    #TODO: Leave the choice as it is i.e. user can select/check it

            # This is what I had earlier, but it makes all the choices to be readonly. Not what I want
            self.fields['strategic_objectives'].widget.attrs['readonly'] = True
            self.fields['strategic_objectives'].widget.attrs['disabled'] = True
</code>```

How do I make sure that the original categories are shown as readonly?
Is this the way to go about it or JS will be a better option?

答:
I had the same problem as you and solved it with the help of this blogpost.
Basically it is necessary to modify the widget which is used to display the choices to be able to mark some choices as disabled.

So I created a widgets.py with the following content:

from django.forms import CheckboxSelectMultiple

class CheckboxSelectMultipleWithDisabled(CheckboxSelectMultiple):

    def __init__(self, *args, **kwargs):
        self.disabled = kwargs.pop("disabled", set())

        super().__init__(*args, **kwargs)

    def create_option(self, *args, **kwargs):
        options_dict = super().create_option(*args, **kwargs)

        if options_dict["value"] in self.disabled:
            options_dict["attrs"]["disabled"] = True

        return options_dict
```

<p>Then in the constructor of the form class (<code>ProjectForm</code>) I exchanged the widget of the respective field (<code>project_categories</code>) and used the added <code>disabled</code> keyword argument introduced above:</p>

<pre class="lang-py prettyprint-override"><code>    def __init__(self, *args, **kwargs):
        super(ProjectForm, self).__init__(*args, **kwargs)

        # fill a local 'disabled' set/list/tuple/... variable using your logic

        self.fields['project_categories'].widget = CheckboxSelectMultipleWithDisabled(
            choices=self.fields['project_categories'].choices,
            disabled=disabled
        )
</code>```

Also do not forget to import the new widget to use it: from .widgets import CheckboxSelectMultipleWithDisabled.

What levi posted is still true, though: you can remove the disabled tag in the html code in your browser and be able to modify the choice again.
So without any extra validation you have to trust your users.

A similar solution is presented in the answer to this question.

Body:
I'm using Django MultiSelectField to store a project's category/categories.

My requirement is as follows: A project can have one or more categories. When creating a project initially, the user should be able to select any of the categories listed in the select field. If a user selects 'Not Applicable', then the other categories become disabled.

When editing a project, user should not be able to unselect the originally selected categorie(s), but he can add/select other categories in addition to the original ones. The originally selected categories should be readonly when editing.

My model looks like this:

from multiselectfield import MultiSelectField
(...)

class Project(models.Model):

    CAT_0 = 0
    CAT_1 = 1
    CAT_2 = 2
    CAT_3 = 3

    PROJECT_CATEGORIES = (
        (CAT_0, _('Not Applicable')),
        (CAT_1, _('My Category 1')),
        (CAT_2, _('My Category 2')),
        (CAT_3, _('My Category 3')),
    )
    (...)
    project_categories =  MultiSelectField(choices=PROJECT_CATEGORIES, max_choices=3, default=CAT_0)

And my forms.py

class ProjectForm(ModelForm):

    class Meta:
        model = Project
        (...)

    def __init__(self, *args, **kwargs):
        super(ProjectForm, self).__init__(*args, **kwargs)
        (...)

        if self.instance.pk:
            for choice in self.fields['project_categories'].choices:
                if str(choice[0]) in self.instance.project_categories:
                    #TODO: Make this choice to be readonly i.e. user should not be able to uncheck it
                else:
                    #TODO: Leave the choice as it is i.e. user can select/check it

            # This is what I had earlier, but it makes all the choices to be readonly. Not what I want
            self.fields['strategic_objectives'].widget.attrs['readonly'] = True
            self.fields['strategic_objectives'].widget.attrs['disabled'] = True

How do I make sure that the original categories are shown as readonly?
Is this the way to go about it or JS will be a better option?

Body:
I had the same problem as you and solved it with the help of this blogpost.
Basically it is necessary to modify the widget which is used to display the choices to be able to mark some choices as disabled.

So I created a widgets.py with the following content:

from django.forms import CheckboxSelectMultiple

class CheckboxSelectMultipleWithDisabled(CheckboxSelectMultiple):

    def __init__(self, *args, **kwargs):
        self.disabled = kwargs.pop("disabled", set())

        super().__init__(*args, **kwargs)

    def create_option(self, *args, **kwargs):
        options_dict = super().create_option(*args, **kwargs)

        if options_dict["value"] in self.disabled:
            options_dict["attrs"]["disabled"] = True

        return options_dict

Then in the constructor of the form class (ProjectForm) I exchanged the widget of the respective field (project_categories) and used the added disabled keyword argument introduced above:

    def __init__(self, *args, **kwargs):
        super(ProjectForm, self).__init__(*args, **kwargs)

        # fill a local 'disabled' set/list/tuple/... variable using your logic

        self.fields['project_categories'].widget = CheckboxSelectMultipleWithDisabled(
            choices=self.fields['project_categories'].choices,
            disabled=disabled
        )

Also do not forget to import the new widget to use it: from .widgets import CheckboxSelectMultipleWithDisabled.

What levi posted is still true, though: you can remove the disabled tag in the html code in your browser and be able to modify the choice again.
So without any extra validation you have to trust your users.

A similar solution is presented in the answer to this question.


问:
How can I randomize coordinates in javascript canvas?
Newbie here, currently learning how to code. My teacher gave me the task of proving myself in canvas by making a smiley face on my own.
This is the result so far.

Now he gave me the task of randomizing the coordinates, so that the smiley as a whole appears in a new place everytime (whether that happens on load or through a button is my decision).

Edit: to clarify, my problem lies more within the logic behind altering the coordinates of my canvas. I've tried to figure out how to do this, and know that I'll need Math.random for that.

Edit: to clarify, my problem lies more within the logic behind

My code:

```<code><body onload="draw();">
    <canvas id="canvas" width="150" height="150"></canvas>

    <script type="application/javascript">
        function draw() {
            var canvas = document.getElementById("canvas");
            var smiley = canvas.getContext("2d");

                //Face shape
                smiley.beginPath();
                smiley.arc(75, 75, 50, 0, Math.PI * 2, true);

                //Right eye
                smiley.moveTo(65,55);
                smiley.arc(55,55,10,0, Math.PI * 2, true);

                //Left eye
                smiley.moveTo(105,55);
                smiley.arc(95,55,10,0, Math.PI * 2, true);

                //Mouth
                smiley.moveTo(35,75);
                smiley.arc(75, 75, 40, 0, Math.PI, false);
                smiley.moveTo(36,81);
                smiley.lineTo(114,81);
                smiley.stroke();

                //Pupils
                smiley.beginPath(58,55);
                smiley.moveTo(58,55);
                smiley.arc(55,55,3,0, Math.PI*2,true);
                smiley.moveTo(98,55);
                smiley.arc(95,55,3,0, Math.PI*2, true);
                smiley.fill()

                //Hair
                smiley.beginPath(75,25);
                smiley.moveTo(75,25);
                smiley.lineTo(75,5);
                smiley.moveTo(79,5);
                smiley.lineTo(78,25);
                smiley.moveTo(72,25);
                smiley.lineTo(71,5);
                smiley.stroke();

                //Nose
                smiley.beginPath();
                smiley.moveTo(73,50);
                smiley.lineTo(67,67);
                smiley.lineTo(80,70);
                smiley.stroke();

                smiley.beginPath()
                smiley.moveTo(73,50);
                smiley.lineTo(63,69);
                smiley.lineTo(80,70);
                smiley.lineTo(67,67);
                smiley.lineTo(73,50);
                smiley.fill();
                smiley.endPath();
            }

    </script>
</body>
</code>```

Thank you for your help.

答:
Hello you need to use Math.random() which gives a number between 0 and 1. But you need a range between 50 and canvasWidth-50
I expanded canvas width to demonstrate randomness more

    <canvas id="canvas" width="450px" height="450px"></canvas>

```

Body:
Newbie here, currently learning how to code. My teacher gave me the task of proving myself in canvas by making a smiley face on my own.
This is the result so far.

Now he gave me the task of randomizing the coordinates, so that the smiley as a whole appears in a new place everytime (whether that happens on load or through a button is my decision).

Edit: to clarify, my problem lies more within the logic behind altering the coordinates of my canvas. I've tried to figure out how to do this, and know that I'll need Math.random for that.

Edit: to clarify, my problem lies more within the logic behind

My code:

    <canvas id="canvas" width="150" height="150"></canvas>

Thank you for your help.

Body:
Hello you need to use Math.random() which gives a number between 0 and 1. But you need a range between 50 and canvasWidth-50
I expanded canvas width to demonstrate randomness more

<body onload="draw();">
    <canvas id="canvas" width="450px" height="450px"></canvas>

    <script type="application/javascript">
        function draw() {
        var canvas=document.getElementById("canvas");
        var x=Math.random()*(canvas.width-100)-25; //smiley's width 100 and your initial value was +75 it needed to be 100/2=50
        var y=Math.random()*(canvas.height-100)-25; //smiley's height 100 and your initial value was +75 it needed to be 100/2=50
            var canvas = document.getElementById("canvas");
            var smiley = canvas.getContext("2d");

                //Face shape
                smiley.beginPath();
                smiley.arc(75+x, 75+y, 50, 0, Math.PI * 2, true);

                //Right eye
                smiley.moveTo(65+x,55+y);
                smiley.arc(55+x,55+y,10,0, Math.PI * 2, true);

                //Left eye
                smiley.moveTo(105+x,55+y);
                smiley.arc(95+x,55+y,10,0, Math.PI * 2, true);

                //Mouth
                smiley.moveTo(35+x,75+y);
                smiley.arc(75+x, 75+y, 40, 0, Math.PI, false);
                smiley.moveTo(36+x,81+y);
                smiley.lineTo(114+x,81+y);
                smiley.stroke();

                //Pupils
                smiley.beginPath(58+x,55+y);
                smiley.moveTo(58+x,55+y);
                smiley.arc(55+x,55+y,3,0, Math.PI*2,true);
                smiley.moveTo(98+x,55+y);
                smiley.arc(95+x,55+y,3,0, Math.PI*2, true);
                smiley.fill()

                //Hair
                smiley.beginPath(75+x,25+y);
                smiley.moveTo(75+x,25+y);
                smiley.lineTo(75+x,5+y);
                smiley.moveTo(79+x,5+y);
                smiley.lineTo(78+x,25+y);
                smiley.moveTo(72+x,25+y);
                smiley.lineTo(71+x,5+y);
                smiley.stroke();

                //Nose
                smiley.beginPath();
                smiley.moveTo(73+x,50+y);
                smiley.lineTo(67+x,67+y);
                smiley.lineTo(80+x,70+y);
                smiley.stroke();

                smiley.moveTo(73+x,50+y);
                smiley.lineTo(63+x,69+y);
                smiley.lineTo(80+x,70+y);
                smiley.lineTo(67+x,67+y);
                smiley.lineTo(73+x,50+y);
                smiley.fill();
            }

    </script>
</body>


问:
Got 'Cannot find module' error when I tried to import certain JS file
I am currently learning JS and this is codes from practice.
(which is from YDKJSY)

This is a publication.js

```<code>function printDetails(title,author,pubDate) {
    console.log(`
    Title: ${ title }
    By: ${ author }
    ${ pubDate } `
    );
}
export function create(title,author,pubDate) {
    var publicAPI = {
        print() {
            printDetails(title,author,pubDate);
        }
     };
return publicAPI;
}
</code>```

And this blogpost.js import publication.js

```<code>import { create as createPub } from "publication.js";
function printDetails(pub,URL) {
    pub.print(); console.log(URL);
}
export function create(title,author,pubDate,URL) {
    var pub = createPub(title,author,pubDate);
var publicAPI = { print() { printDetails(pub,URL);
        }
    };
return publicAPI;
}
</code>```

And finally main.js import blogpost.js

```<code>import { create as newBlogPost } from "blogpost.js";
var forAgainstLet = newBlogPost(
    "For and against let",
    "Kyle Simpson",
    "October 27, 2014",
    "https://davidwalsh.name/for-and-against-let"
);
</code>```

I converted these code by babel and got converted codes.

PS C:\users\leepc\babel> npm run build

```<code>> babel@1.0.0 build C:\users\leepc\babel
> babel ./public/src -d ./public/lib -w

public\src\blogpost.js -> public\lib\blogpost.js
public\src\main.js -> public\lib\main.js
public\src\publication.js -> public\lib\publication.js
</code>```

but when I do npm run build and tried to run main.js I got this,

PS C:\users\leepc\babel\public\lib> node main.js

```<code>internal/modules/cjs/loader.js:984
  throw err;
  ^

Error: Cannot find module 'blogpost.js'
Require stack:
    at Module.require
(internal/modules/cjs/loader.js:1043:19)
    at require (internal/modules/cjs/helpers.js:77:18)
    at Object.<anonymous>
(C:\users\leepc\babel\public\lib\main.js:3:17)
    at Module._compile
(internal/modules/cjs/loader.js:1157:30)    3:17)
    at Object.Module._extensions..js
(internal/modules/cjs/loader.js:117
7:10)
    at Module.load (internal/modules/cjs/loader.js:1001:32)
    at Function.Module._load
(internal/modules/cjs/loader.js:900:14)

    at Function.executeUserEntryPoint [as runMain]
(internal/modules/run
_main.js:74:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
'C:\\users\\leepc\\babel\\public\\lib\\main.js' ]

}
</code>```

I checked whether I forgot any installment.

PS C:\users\leepc\babel> npm ls --depth=0

```<code>babel@1.0.0 C:\users\leepc\babel
+-- @babel/core@7.8.4
+-- babel-cli@6.26.0
+-- babel-preset-env@1.7.0
`-- babel-preset-es2015@6.24.1
</code>```

Lastley, about .babelrc

```<code>{
  "presets": ["env"]
}
</code>```

and package.json build,

```<code>{
    ...
    "build": "babel ./public/src -d ./public/lib -w"
  }
</code>```

I used node.js preset, but it got weird errors so I just left if with "env".

Sorry for a messy and long code, but I have been trouble for this problem these days and can't get to further studying.
Please let me know is there any other information I have to post and edit in this question.

edit:
is this maybe becasue I put all of this files in a same folder?
should I have to put these in a certain different folder?
This is a picture of my practice project folder

答:
Have you followed the setup steps from https://www.npmjs.com/package/babel-plugin-import ?

```<code>npm install babel-plugin-import --save-dev
</code>```

In .babelrc

```<code>{
  "plugins": [["import", options]]
}
</code>```

Body:
I am currently learning JS and this is codes from practice.
(which is from YDKJSY)

This is a publication.js

function printDetails(title,author,pubDate) {
    console.log(`
    Title: ${ title }
    By: ${ author }
    ${ pubDate } `
    );
}
export function create(title,author,pubDate) {
    var publicAPI = {
        print() {
            printDetails(title,author,pubDate);
        }
     };
return publicAPI;
}

And this blogpost.js import publication.js

import { create as createPub } from "publication.js";
function printDetails(pub,URL) {
    pub.print(); console.log(URL);
}
export function create(title,author,pubDate,URL) {
    var pub = createPub(title,author,pubDate);
var publicAPI = { print() { printDetails(pub,URL);
        }
    };
return publicAPI;
}

And finally main.js import blogpost.js

import { create as newBlogPost } from "blogpost.js";
var forAgainstLet = newBlogPost(
    "For and against let",
    "Kyle Simpson",
    "October 27, 2014",
    "https://davidwalsh.name/for-and-against-let"
);

I converted these code by babel and got converted codes.

PS C:\users\leepc\babel> npm run build

> babel@1.0.0 build C:\users\leepc\babel
> babel ./public/src -d ./public/lib -w

public\src\blogpost.js -> public\lib\blogpost.js
public\src\main.js -> public\lib\main.js
public\src\publication.js -> public\lib\publication.js

but when I do npm run build and tried to run main.js I got this,

PS C:\users\leepc\babel\public\lib> node main.js

internal/modules/cjs/loader.js:984
  throw err;
  ^

Error: Cannot find module 'blogpost.js'
Require stack:
    at Module.require
(internal/modules/cjs/loader.js:1043:19)
    at require (internal/modules/cjs/helpers.js:77:18)
    at Object.<anonymous>
(C:\users\leepc\babel\public\lib\main.js:3:17)
    at Module._compile
(internal/modules/cjs/loader.js:1157:30)    3:17)
    at Object.Module._extensions..js
(internal/modules/cjs/loader.js:117
7:10)
    at Module.load (internal/modules/cjs/loader.js:1001:32)
    at Function.Module._load
(internal/modules/cjs/loader.js:900:14)

    at Function.executeUserEntryPoint [as runMain]
(internal/modules/run
_main.js:74:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
'C:\\users\\leepc\\babel\\public\\lib\\main.js' ]

}

I checked whether I forgot any installment.

PS C:\users\leepc\babel> npm ls --depth=0

babel@1.0.0 C:\users\leepc\babel
+-- @babel/core@7.8.4
+-- babel-cli@6.26.0
+-- babel-preset-env@1.7.0
`-- babel-preset-es2015@6.24.1

Lastley, about .babelrc

{
  "presets": ["env"]
}

and package.json build,

{
    ...
    "build": "babel ./public/src -d ./public/lib -w"
  }

I used node.js preset, but it got weird errors so I just left if with "env".

Sorry for a messy and long code, but I have been trouble for this problem these days and can't get to further studying.
Please let me know is there any other information I have to post and edit in this question.

edit:
is this maybe becasue I put all of this files in a same folder?
should I have to put these in a certain different folder?
This is a picture of my practice project folder

Body:
Have you followed the setup steps from https://www.npmjs.com/package/babel-plugin-import ?

npm install babel-plugin-import --save-dev

In .babelrc

{
  "plugins": [["import", options]]
}


问:
What is the substitue for the attr_protected in rails 5?
```<code>class Oregano < ApplicationRecord
  attr_protected :person_id
end
</code>```

This throws me back with an error

```<code>/activerecord-5.0.5/lib/active_record/dynamic_matchers.rb:21:in `method_missing': undefined method `attr_protected' for #<Class:0x000055b38448bd58> (NoMethodError).
</code>```

What should be the substitue in the rails 5 upgrade for this?

答:
No mass assignment allowed for Rails 5

Instead of having attr_protected :person_id in your model, use strong parameters. You'll do this in your OreganosController:

```<code>def oregano_params
  params.require(:oregano).permit(:person_id)
end
</code>```

Body:
class Oregano < ApplicationRecord
  attr_protected :person_id
end

This throws me back with an error

/activerecord-5.0.5/lib/active_record/dynamic_matchers.rb:21:in `method_missing': undefined method `attr_protected' for #<Class:0x000055b38448bd58> (NoMethodError).

What should be the substitue in the rails 5 upgrade for this?

Body:
No mass assignment allowed for Rails 5

Instead of having attr_protected :person_id in your model, use strong parameters. You'll do this in your OreganosController:

def oregano_params
  params.require(:oregano).permit(:person_id)
end


问:
What causes this vue-router async component error - TypeError: undefined is not an object (evaluating 't.__esModule')?
I notice a lot of errors in Sentry with the following stack trace:

```<code>TypeError: undefined is not an object (evaluating 't.__esModule')
  at isESModule(./node_modules/vue-router/dist/vue-router.esm.js:1955:3)
  at ? (./node_modules/vue-router/dist/vue-router.esm.js:1882:27)
  at promiseReactionJob([native code])
</code>```

I'm having a lot of trouble reproducing the error myself and figuring out what causes it. Looking at the vue-router source, it comes from this function:

  function isESModule (obj) {
    return obj.__esModule || (hasSymbol && obj[Symbol.toStringTag] === 'Module')
  }
```

<p>So <code>obj</code> is undefined. If we go one level up we get this function:</p>

<pre class="lang-js prettyprint-override"><code>  function resolveAsyncComponents (matched) {
    return function (to, from, next) {
      var hasAsync = false;
      var pending = 0;
      var error = null;

      flatMapComponents(matched, function (def, _, match, key) {
        // if it's a function and doesn't have cid attached,
        // assume it's an async component resolve function.
        // we are not using Vue's default async resolving mechanism because
        // we want to halt the navigation until the incoming component has been
        // resolved.
        if (typeof def === 'function' && def.cid === undefined) {
          hasAsync = true;
          pending++;

          var resolve = once(function (resolvedDef) {
            if (isESModule(resolvedDef)) {
              resolvedDef = resolvedDef.default;
            }
            // save resolved on async factory in case it's used elsewhere
            def.resolved = typeof resolvedDef === 'function'
              ? resolvedDef
              : _Vue.extend(resolvedDef);
            match.components[key] = resolvedDef;
            pending--;
            if (pending <= 0) {
              next();
            }
          });

...
</code>```

So it looks like resolvedDef is undefined.

My guess is that the Vue router resolves an async component successfully but it ends up undefined and there's nothing in the code to account for that case.

I'm using vue-router 3.1.3 and these errors always happen only on iOS (Safari or Chrome).

I've tried Googling the error and I can't seem to find a single reference to it anywhere else. I'm also not able to post an issue on the vue-router Github because I'm not able to provide a minimal reproduction.

Often (but not always) Sentry also shows this console log preceding the error:

```<code>console [vue-analytics] An error occured! Please check your connection or disable your AD blocker
logger console
extra {"arguments":["[vue-analytics] An error occured! Please check your connection or disable your AD blocker"]}
</code>```

I'm not sure if that's related though.

One crazy solution I'm thinking of is deployed a patched version of vue-router where it throws an error with more useful context in the case where resolvedDef is undefined. That error would hopefully end up in our Sentry logs.

What's causing this error?

答:
I forked the vue-router library and patched resolveAsyncComponents with this line:

if (!resolvedDef) {
  window.onerror(`router wtf ${matched.join(',')} ${def} ${_} ${match} ${key} ${pending} ${hasAsync} ${error}`);
}
```

<p>Eventually the following error appeared in Sentry:</p>

```router wtf [object Object] function(){return u(Promise.all([n.e("dashboard~orders~products~publicUser"),n.e("dashboard~discounts~products~publicUser"),n.e("orders~publicUser~tips"),n.e("publicUser~tips"),n.e("publicUser")]).then(n.bind(null,"89c6")))...
```

<p>In production, our Vue app seems to load these components with an initiator called bootstrap:</p>

<p><img src="https://i.stack.imgur.com/4JoqG.png" alt="asycn component loading"></p>

<p>Then it hit me that we use the following wrapper around every single async component import in <code>router.js</code>:</p>

<pre class="lang-js prettyprint-override"><code>      {
        path: 'dashboard',
        name: 'dashboard',
        component: () =>
          handleChunkLoadError(
            import(/* webpackChunkName: 'dashboard' */ '../views/Dashboard')
          ),
      },
</code>```

function handleChunkLoadError(importPromise) {
  return importPromise.catch(() => {
    Vue.toasted.error('Network error encountered', {
      duration: null,
      action: {
        text: 'Reload',
        onClick: () => window.location.reload(),
      },
    });
  });
}
```

<p>It's supposed to show a toast that allows the user to refresh the page if a chunk failed to load. </p>

<p>But we were forgetting to pass along the error to vue-router:</p>

<pre class="lang-js prettyprint-override"><code>function handleChunkLoadError(importPromise) {
  return importPromise.catch(error => {
    Vue.toasted.error('Network error encountered', {
      duration: null,
      action: {
        text: 'Reload',
        onClick: () => window.location.reload(),
      },
    });

    return error;
  });
}
</code>```

Returning the error in the .catch handler fixes the issue.

Body:
I notice a lot of errors in Sentry with the following stack trace:

TypeError: undefined is not an object (evaluating 't.__esModule')
  at isESModule(./node_modules/vue-router/dist/vue-router.esm.js:1955:3)
  at ? (./node_modules/vue-router/dist/vue-router.esm.js:1882:27)
  at promiseReactionJob([native code])

I'm having a lot of trouble reproducing the error myself and figuring out what causes it. Looking at the vue-router source, it comes from this function:

  function isESModule (obj) {
    return obj.__esModule || (hasSymbol && obj[Symbol.toStringTag] === 'Module')
  }

So obj is undefined. If we go one level up we get this function:

  function resolveAsyncComponents (matched) {
    return function (to, from, next) {
      var hasAsync = false;
      var pending = 0;
      var error = null;

      flatMapComponents(matched, function (def, _, match, key) {
        // if it's a function and doesn't have cid attached,
        // assume it's an async component resolve function.
        // we are not using Vue's default async resolving mechanism because
        // we want to halt the navigation until the incoming component has been
        // resolved.
        if (typeof def === 'function' && def.cid === undefined) {
          hasAsync = true;
          pending++;

          var resolve = once(function (resolvedDef) {
            if (isESModule(resolvedDef)) {
              resolvedDef = resolvedDef.default;
            }
            // save resolved on async factory in case it's used elsewhere
            def.resolved = typeof resolvedDef === 'function'
              ? resolvedDef
              : _Vue.extend(resolvedDef);
            match.components[key] = resolvedDef;
            pending--;
            if (pending <= 0) {
              next();
            }
          });

...

So it looks like resolvedDef is undefined.

My guess is that the Vue router resolves an async component successfully but it ends up undefined and there's nothing in the code to account for that case.

I'm using vue-router 3.1.3 and these errors always happen only on iOS (Safari or Chrome).

I've tried Googling the error and I can't seem to find a single reference to it anywhere else. I'm also not able to post an issue on the vue-router Github because I'm not able to provide a minimal reproduction.

Often (but not always) Sentry also shows this console log preceding the error:

console [vue-analytics] An error occured! Please check your connection or disable your AD blocker
logger console
extra {"arguments":["[vue-analytics] An error occured! Please check your connection or disable your AD blocker"]}

I'm not sure if that's related though.

One crazy solution I'm thinking of is deployed a patched version of vue-router where it throws an error with more useful context in the case where resolvedDef is undefined. That error would hopefully end up in our Sentry logs.

What's causing this error?

Body:
I forked the vue-router library and patched resolveAsyncComponents with this line:

if (!resolvedDef) {
  window.onerror(`router wtf ${matched.join(',')} ${def} ${_} ${match} ${key} ${pending} ${hasAsync} ${error}`);
}

Eventually the following error appeared in Sentry:

router wtf [object Object] function(){return u(Promise.all([n.e("dashboard~orders~products~publicUser"),n.e("dashboard~discounts~products~publicUser"),n.e("orders~publicUser~tips"),n.e("publicUser~tips"),n.e("publicUser")]).then(n.bind(null,"89c6")))...

In production, our Vue app seems to load these components with an initiator called bootstrap:

Then it hit me that we use the following wrapper around every single async component import in router.js:

      {
        path: 'dashboard',
        name: 'dashboard',
        component: () =>
          handleChunkLoadError(
            import(/* webpackChunkName: 'dashboard' */ '../views/Dashboard')
          ),
      },

function handleChunkLoadError(importPromise) {
  return importPromise.catch(() => {
    Vue.toasted.error('Network error encountered', {
      duration: null,
      action: {
        text: 'Reload',
        onClick: () => window.location.reload(),
      },
    });
  });
}

It's supposed to show a toast that allows the user to refresh the page if a chunk failed to load.

But we were forgetting to pass along the error to vue-router:

function handleChunkLoadError(importPromise) {
  return importPromise.catch(error => {
    Vue.toasted.error('Network error encountered', {
      duration: null,
      action: {
        text: 'Reload',
        onClick: () => window.location.reload(),
      },
    });

    return error;
  });
}

Returning the error in the .catch handler fixes the issue.


问:
Function not sending alert in browser HTML, JavaScript
Newbie to HTML and Javascript here.

I am coding up a very basic program that allows a user to enter a card number and the browser should say if it is a valid number (between 13-16 digits) or not.

The website pulls up and shows everything I want it to, but when a number is entered (valid or invalid) the alert is not sent to say if the number was good or not.

Any suggestions on how I can fix this?

```<code><!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Card Reader</title>
  <link type=’text/css’/>
  <script>
    'use strict';
    function getNumber(cardNum) {
        if (cardNum.length > 16 || cardNum.length < 13) {
            alert(‘This is not valid.’);
            return false;}
        else {
            alert(‘This is valid.’);
            return true;}
    }
  </script>
</head>

<body onload=“document.cardNum()”>

<h4> Enter Credit Card Number: </h4>
<form>
    <input type='text' id=‘cardNum’ name=‘cardNum’/>
    <br>
    <input type="submit" value=Submit onclick = “getNumber(cardNum)”/>
</form>

</body>
</html>
</code>```

答:
As Shubham oli suggested you can also make use of HTML5 validations as below.</p>

```<code><form >
    <input type='text'  id="cardNum"  name="cardNum" required pattern='[0-9]{13,16}'/ >
    <br>
    <input type="submit" value='Submit' >
</form>
</code>```

Body:
Newbie to HTML and Javascript here.

I am coding up a very basic program that allows a user to enter a card number and the browser should say if it is a valid number (between 13-16 digits) or not.

The website pulls up and shows everything I want it to, but when a number is entered (valid or invalid) the alert is not sent to say if the number was good or not.

Any suggestions on how I can fix this?

<!doctype html>

  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Card Reader</title>
  <link type=’text/css’/>

 Enter Credit Card Number:

<form>
    <input type='text' id=‘cardNum’ name=‘cardNum’/>

    <input type="submit" value=Submit onclick = “getNumber(cardNum)”/>
</form>

Body:
As Shubham oli suggested you can also make use of HTML5 validations as below.

<form >
    <input type='text'  id="cardNum"  name="cardNum" required pattern='[0-9]{13,16}'/ >
    <br>
    <input type="submit" value='Submit' >
</form>


问:
Right way to fetch parent table with it's child tables
I have one to many relationship on parent and child tables. And trying to fetch parent table with it's child tables as json.

I tried something like below.

```<code>if (request.method == "GET"):

    parents = Parent.objects.all()
    datas = []
    childTables = []
    for parent in parents:

        #fetching parent first and creating DICT for json
        #also creating an array for the child tables

        parentDict = {
            "id": parent.id,
            "project_name": parent.project_name,
            childTables: childTables,
        }

        #then fetching child tables NO problem at this part as well.
        childs = parent.child_set.filter(parent_id=parent)
        for child in childs:
            #creating a DICT FOR THE json.
            childDict = {
                "id":child.id,
                "ad_kind":child.ad_kind,
                "parent_id":child.parent_id,
            }

            #i am trying to append project's childs into ParentDict
            #but still it's appending all childs into every ParentDict...
            #not just its parent's childs.
            parentDict["childTables"].append(childDict)

        #at last append all parent table inside an array and send it as JSON.
        datas.append(parentDict)

    return JsonResponse(datas, safe=False)
</code>```

the problem starts when I try to append child tables inside it's parent dict. But in above way, I just append all childs into every parent dict...

is there any other simpler way to achieve this?

答:
Python lists are mutable, and you are only creating one "childTables" list instance before the parent loop.  The dictionary key that references childTables references the original list, so each addition to the list appends values to that same list.

To fix this, simply create a new list on each parent iteration:

```<code>for parent in Parent.objects.all():

    parentDict = {
        "id": parent.id,
        "project_name": parent.project_name,
        childTables: [],
    }
</code>```

On a side note, this is not the best way to convert Django querysets into JSON objects.  For that I would recommend using django rest framework.

Body:
I have one to many relationship on parent and child tables. And trying to fetch parent table with it's child tables as json.

I tried something like below.

if (request.method == "GET"):

    parents = Parent.objects.all()
    datas = []
    childTables = []
    for parent in parents:

        #fetching parent first and creating DICT for json
        #also creating an array for the child tables

        parentDict = {
            "id": parent.id,
            "project_name": parent.project_name,
            childTables: childTables,
        }

        #then fetching child tables NO problem at this part as well.
        childs = parent.child_set.filter(parent_id=parent)
        for child in childs:
            #creating a DICT FOR THE json.
            childDict = {
                "id":child.id,
                "ad_kind":child.ad_kind,
                "parent_id":child.parent_id,
            }

            #i am trying to append project's childs into ParentDict
            #but still it's appending all childs into every ParentDict...
            #not just its parent's childs.
            parentDict["childTables"].append(childDict)

        #at last append all parent table inside an array and send it as JSON.
        datas.append(parentDict)

    return JsonResponse(datas, safe=False)

the problem starts when I try to append child tables inside it's parent dict. But in above way, I just append all childs into every parent dict...

is there any other simpler way to achieve this?

Body:
Python lists are mutable, and you are only creating one "childTables" list instance before the parent loop.  The dictionary key that references childTables references the original list, so each addition to the list appends values to that same list.

To fix this, simply create a new list on each parent iteration:

for parent in Parent.objects.all():

    parentDict = {
        "id": parent.id,
        "project_name": parent.project_name,
        childTables: [],
    }

On a side note, this is not the best way to convert Django querysets into JSON objects.  For that I would recommend using django rest framework.