问:
Initializing a matrix using a list with a string in it
Here is my code:

```<code>extensions [matrix]
..
sources-own[keyword1 keyword2 keyword3 keyword4 extrinsic-fitness visits]
..
to setup
create-sources
ask source 0  [
    set keyword1 (matrix:from-row-list [["cat"][2]])
]
...
..
.
</code>```

Now, when I click on SETUP and inspect "source 0", it shows the matrix to be initialized as the following:

```<code>{{matrix:  [ [ 0 ][ 2 ] ]}}
</code>```

Try as I might, I cannot get it to accept the string "cat" in place of the "0" in the first column.

答:
OK, I got it.

A matrix in Netlogo can only hold numbers. One needs to use a "list" instead.

Body:
Here is my code:

extensions [matrix]
..
sources-own[keyword1 keyword2 keyword3 keyword4 extrinsic-fitness visits]
..
to setup
create-sources
ask source 0  [
    set keyword1 (matrix:from-row-list [["cat"][2]])
]
...
..
.

Now, when I click on SETUP and inspect "source 0", it shows the matrix to be initialized as the following:

{{matrix:  [ [ 0 ][ 2 ] ]}}

Try as I might, I cannot get it to accept the string "cat" in place of the "0" in the first column.


来源: stackexchange

答:
```<code>scikit-learn==0.21.3

2020-06-02T07:59:38.012426+00:00 app[web.1]:     import sklearn.linear_model._logistic
2020-06-02T07:59:38.012470+00:00 app[web.1]: ModuleNotFoundError: No module named 'sklearn.linear_model._logistic'
</code>```

Here is scikit-learn 0.21.x:

https://github.com/scikit-learn/scikit-learn/tree/0.21.X/sklearn/linear_model

Here is scikit-learn stable:

https://github.com/scikit-learn/scikit-learn/tree/master/sklearn/linear_model

Notice how in 0.21.x _logistic.py doesn't exist. On your working development environment do:

python3 -m pip freeze > requirements.txt

ContentLicense: CC BY-SA 4.0

Title: Getting an error : ModuleNotFoundError: No module named 'sklearn.linear_model._logistic' in Heroku

Body:
Getting an error: ModuleNotFoundError: No module named 'sklearn.linear_model._logistic'

Requirements.txt:

gunicorn==19.9.0
pandas==0.25.0
requests==2.22.0
scikit-learn==0.21.3
scipy==1.3.1
python-dateutil==2.8.1

Logs:

2020-06-02T07:59:31.971060+00:00 heroku[web.1]: Starting process with command `gunicorn app:app`
2020-06-02T07:59:34.365130+00:00 app[web.1]: [2020-06-02 07:59:34 +0000] [4] [INFO] Starting gunicorn 19.9.0
2020-06-02T07:59:34.365824+00:00 app[web.1]: [2020-06-02 07:59:34 +0000] [4] [INFO] Listening at: http://0.0.0.0:58585 (4)
2020-06-02T07:59:34.365932+00:00 app[web.1]: [2020-06-02 07:59:34 +0000] [4] [INFO] Using worker: sync
2020-06-02T07:59:34.370144+00:00 app[web.1]: [2020-06-02 07:59:34 +0000] [10] [INFO] Booting worker with pid: 10
2020-06-02T07:59:34.444717+00:00 app[web.1]: [2020-06-02 07:59:34 +0000] [18] [INFO] Booting worker with pid: 18
2020-06-02T07:59:36.981072+00:00 heroku[web.1]: Starting process with command `gunicorn app:app`
2020-06-02T07:59:38.011940+00:00 app[web.1]: [2020-06-02 07:59:38 +0000] [18] [ERROR] Exception in worker process
2020-06-02T07:59:38.011983+00:00 app[web.1]: Traceback (most recent call last):
2020-06-02T07:59:38.011984+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
2020-06-02T07:59:38.011985+00:00 app[web.1]:     worker.init_process()
2020-06-02T07:59:38.011986+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, in init_process
2020-06-02T07:59:38.011986+00:00 app[web.1]:     self.load_wsgi()
2020-06-02T07:59:38.011987+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
2020-06-02T07:59:38.011987+00:00 app[web.1]:     self.wsgi = self.app.wsgi()
2020-06-02T07:59:38.011987+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi
2020-06-02T07:59:38.011988+00:00 app[web.1]:     self.callable = self.load()
2020-06-02T07:59:38.011988+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
2020-06-02T07:59:38.011989+00:00 app[web.1]:     return self.load_wsgiapp()
2020-06-02T07:59:38.011989+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
2020-06-02T07:59:38.011989+00:00 app[web.1]:     return util.import_app(self.app_uri)
2020-06-02T07:59:38.011990+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 350, in import_app
2020-06-02T07:59:38.011990+00:00 app[web.1]:     __import__(module)
2020-06-02T07:59:38.011990+00:00 app[web.1]:   File "/app/app.py", line 4, in <module>
2020-06-02T07:59:38.011991+00:00 app[web.1]:     import sklearn.linear_model._logistic
2020-06-02T07:59:38.012000+00:00 app[web.1]: ModuleNotFoundError: No module named 'sklearn.linear_model._logistic'
2020-06-02T07:59:38.012410+00:00 app[web.1]: [2020-06-02 07:59:38 +0000] [10] [ERROR] Exception in worker process
2020-06-02T07:59:38.012411+00:00 app[web.1]: Traceback (most recent call last):
2020-06-02T07:59:38.012412+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
2020-06-02T07:59:38.012412+00:00 app[web.1]:     worker.init_process()
2020-06-02T07:59:38.012413+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, in init_process
2020-06-02T07:59:38.012413+00:00 app[web.1]:     self.load_wsgi()
2020-06-02T07:59:38.012414+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
2020-06-02T07:59:38.012414+00:00 app[web.1]:     self.wsgi = self.app.wsgi()
2020-06-02T07:59:38.012414+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi
2020-06-02T07:59:38.012415+00:00 app[web.1]:     self.callable = self.load()
2020-06-02T07:59:38.012415+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
2020-06-02T07:59:38.012415+00:00 app[web.1]:     return self.load_wsgiapp()
2020-06-02T07:59:38.012424+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
2020-06-02T07:59:38.012425+00:00 app[web.1]:     return util.import_app(self.app_uri)
2020-06-02T07:59:38.012425+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 350, in import_app
2020-06-02T07:59:38.012425+00:00 app[web.1]:     __import__(module)
2020-06-02T07:59:38.012426+00:00 app[web.1]:   File "/app/app.py", line 4, in <module>
2020-06-02T07:59:38.012426+00:00 app[web.1]:     import sklearn.linear_model._logistic
2020-06-02T07:59:38.012470+00:00 app[web.1]: ModuleNotFoundError: No module named 'sklearn.linear_model._logistic'
2020-06-02T07:59:38.013250+00:00 app[web.1]: [2020-06-02 07:59:38 +0000] [18] [INFO] Worker exiting (pid: 18)
2020-06-02T07:59:38.013864+00:00 app[web.1]: [2020-06-02 07:59:38 +0000] [10] [INFO] Worker exiting (pid: 10)
2020-06-02T07:59:38.241359+00:00 app[web.1]: Traceback (most recent call last):
2020-06-02T07:59:38.241366+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 210, in run
2020-06-02T07:59:38.241723+00:00 app[web.1]:     self.sleep()
2020-06-02T07:59:38.241728+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 360, in sleep
2020-06-02T07:59:38.241955+00:00 app[web.1]:     ready = select.select([self.PIPE[0]], [], [], 1.0)
2020-06-02T07:59:38.241960+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 245, in handle_chld
2020-06-02T07:59:38.242155+00:00 app[web.1]:     self.reap_workers()
2020-06-02T07:59:38.242156+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 525, in reap_workers
2020-06-02T07:59:38.242436+00:00 app[web.1]:     raise HaltServer(reason, self.WORKER_BOOT_ERROR)
2020-06-02T07:59:38.242479+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
2020-06-02T07:59:38.242485+00:00 app[web.1]:
2020-06-02T07:59:38.242486+00:00 app[web.1]: During handling of the above exception, another exception occurred:
2020-06-02T07:59:38.242486+00:00 app[web.1]:
2020-06-02T07:59:38.242489+00:00 app[web.1]: Traceback (most recent call last):
2020-06-02T07:59:38.242515+00:00 app[web.1]:   File "/app/.heroku/python/bin/gunicorn", line 8, in <module>
2020-06-02T07:59:38.242642+00:00 app[web.1]:     sys.exit(run())
2020-06-02T07:59:38.242646+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 61, in run
2020-06-02T07:59:38.242786+00:00 app[web.1]:     WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run()
2020-06-02T07:59:38.242790+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 223, in run
2020-06-02T07:59:38.242963+00:00 app[web.1]:     super(Application, self).run()
2020-06-02T07:59:38.242967+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 72, in run
2020-06-02T07:59:38.243100+00:00 app[web.1]:     Arbiter(self).run()
2020-06-02T07:59:38.243104+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 232, in run
2020-06-02T07:59:38.243269+00:00 app[web.1]:     self.halt(reason=inst.reason, exit_status=inst.exit_status)
2020-06-02T07:59:38.243274+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 345, in halt
2020-06-02T07:59:38.243478+00:00 app[web.1]:     self.stop()
2020-06-02T07:59:38.243482+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 393, in stop
2020-06-02T07:59:38.243692+00:00 app[web.1]:     time.sleep(0.1)
2020-06-02T07:59:38.243696+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 245, in handle_chld
2020-06-02T07:59:38.243865+00:00 app[web.1]:     self.reap_workers()
2020-06-02T07:59:38.243869+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 525, in reap_workers
2020-06-02T07:59:38.244116+00:00 app[web.1]:     raise HaltServer(reason, self.WORKER_BOOT_ERROR)
2020-06-02T07:59:38.244120+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>```

Body:
scikit-learn==0.21.3

2020-06-02T07:59:38.012426+00:00 app[web.1]:     import sklearn.linear_model._logistic
2020-06-02T07:59:38.012470+00:00 app[web.1]: ModuleNotFoundError: No module named 'sklearn.linear_model._logistic'

Here is scikit-learn 0.21.x:

https://github.com/scikit-learn/scikit-learn/tree/0.21.X/sklearn/linear_model

Here is scikit-learn stable:

https://github.com/scikit-learn/scikit-learn/tree/master/sklearn/linear_model

Notice how in 0.21.x _logistic.py doesn't exist. On your working development environment do:

python3 -m pip freeze > requirements.txt


问:
kubectl port forwarding timeout issue
While using kubectl port-forward function I was able to succeed in port forwarding a local port to a remote port. However it seems that after a few minutes idling the connection is dropped. Not sure why that is so.

Here is the command used to portforward:

```<code>kubectl --namespace somenamespace port-forward somepodname 50051:50051
</code>```

Error message:

```<code>Forwarding from 127.0.0.1:50051 -> 50051
Forwarding from [::1]:50051 -> 50051
E1125 17:18:55.723715    9940 portforward.go:178] lost connection to pod
</code>```

Was hoping to be able to keep the connection up

答:
For windows make such bat (God forgive me)</p>

```<code>:1
oc port-forward PODNAME 8003:8080
goto 1
</code>```

ContentLicense: CC BY-SA 3.0

Title: kubectl port forwarding timeout issue

Body:
While using kubectl port-forward function I was able to succeed in port forwarding a local port to a remote port. However it seems that after a few minutes idling the connection is dropped. Not sure why that is so.

Here is the command used to portforward:

kubectl --namespace somenamespace port-forward somepodname 50051:50051

Error message:

Forwarding from 127.0.0.1:50051 -> 50051
Forwarding from [::1]:50051 -> 50051
E1125 17:18:55.723715    9940 portforward.go:178] lost connection to pod

Was hoping to be able to keep the connection up

Body:
For windows make such bat (God forgive me)

:1
oc port-forward PODNAME 8003:8080
goto 1


问:
Elasticsearch terms aggregation and lowercase values
I am using the following search query to populate an autocomplete dropdown with values based on what the user types.

```<code>{
    _source: 'event',
    query: {
        simple_query_string: {
            query: ''+term+'*', // converts to string; adds * to match prefix
            fields: ['event']
        }
    },
    size:0,
    track_total_hits: false,
    aggs: {
        filterValues: {
            composite: {
                size: 100,
                sources: [
                    { "filterValue": { "terms": { "field": 'event', "missing_bucket": true } } }
                ],
                after: { 'event': after }
            },
        }
    }
}
</code>```

Field value used for indexing: UYB 4.9.0 AJF 5 Qnihsbm.

Currently if the user types the first letter u or U, Elasticsearch will return the above value in lowercase uyb 4.9.0 ajf 5 qnihsbm. How can I maintain this behaviour but return the value exactly as it was indexed? i.e UYB 4.9.0 AJF 5 Qnihsbm

Field mapping

```<code>"mappings": {
    "properties": {
        "event": {
            "type": "keyword",
            "normalizer": "normalizer_1"
        },
        .....
    }
}
</code>```

ES Config

```<code>"settings": {
    "analysis": {
        "normalizer": {
            "normalizer_1": {
                "type": "custom",
                "char_filter": [],
                "filter": ["lowercase", "asciifolding"]
            }
        }
    }
},
</code>```

答:
if you have _source enabled then you can use source filtering to retrieve the indexed value .

https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-source-field.html for more info on _source field and its use-cases.

Body:
I am using the following search query to populate an autocomplete dropdown with values based on what the user types.

{
    _source: 'event',
    query: {
        simple_query_string: {
            query: ''+term+'*', // converts to string; adds * to match prefix
            fields: ['event']
        }
    },
    size:0,
    track_total_hits: false,
    aggs: {
        filterValues: {
            composite: {
                size: 100,
                sources: [
                    { "filterValue": { "terms": { "field": 'event', "missing_bucket": true } } }
                ],
                after: { 'event': after }
            },
        }
    }
}

Field value used for indexing: UYB 4.9.0 AJF 5 Qnihsbm.

Currently if the user types the first letter u or U, Elasticsearch will return the above value in lowercase uyb 4.9.0 ajf 5 qnihsbm. How can I maintain this behaviour but return the value exactly as it was indexed? i.e UYB 4.9.0 AJF 5 Qnihsbm

Field mapping

"mappings": {
    "properties": {
        "event": {
            "type": "keyword",
            "normalizer": "normalizer_1"
        },
        .....
    }
}

ES Config

"settings": {
    "analysis": {
        "normalizer": {
            "normalizer_1": {
                "type": "custom",
                "char_filter": [],
                "filter": ["lowercase", "asciifolding"]
            }
        }
    }
},


问:
What is side effect in C?
Wikipedia says that:

In computer science, an operation, function or expression is said to have a side effect if it modifies some state variable value(s) outside its local environment, that is to say has an observable effect besides returning a value (the main effect) to the invoker of the operation.

But how can we access a variable outside its local environment, can anyone explain this situation, side effect, main effect and sequence point comprehensibly?

答:
A State is the attribute of a program which tells about the behavior of the program/function/variable.

for example, observe the state of "i" (variable):

```<code>int i = 0; // here state of i is only dependent on the value its holding. lets denote the time when i is having a value 0 as State A.
i++; // i = 1, that means its no longer 0 i.e. state changed to state B
i++ // i = 2 . State C
i--; // i = 1, state B
i += 0; // state B
</code>```

Side effects:
In general, when someone talks about side-effects in a function (regardless of the language), they are talking about changes to the state of the program outside of changes to the function parameters and the object itself.

The way I like to visualize side effect:

```<code>----------------------
            \ <= side effect
           ----------------
</code>```

A function with no side effects in C (where we disregard the possibility of a function being a member function) might look like this:

```<code>int stateOfP(int a, char *p)
{
  *p = 0;
   return a+1;
}
</code>```

In this case, the program has modified a location in memory pointed to by p, but as p is a memory location pointed to in an argument, we don’t count that as a side effect.

A function without side effects is a good thing, for a few reasons.

First, the absence of side effects makes it easier for the compiler to optimize use of the function.

Second, side effects make it much more difficult to prove the correctness of a program.

Finally, when using multiple threads, particularly in a C program, side effects can have undetermined outcomes. For example, if two threads modify an ordinary global variable in a C program without some special locking mechanism, the program’s outcome is undefined.

What does it look like when a function has side effects? Something like this:

```<code>int a = 0;
void stateChange(int p)
{
  a++; // here the function is having side effects as 'a' is not its attribute
  return;
}
</code>```

Title: What is side effect in C?

Body:
A State is the attribute of a program which tells about the behavior of the program/function/variable.

for example, observe the state of "i" (variable):

int i = 0; // here state of i is only dependent on the value its holding. lets denote the time when i is having a value 0 as State A.
i++; // i = 1, that means its no longer 0 i.e. state changed to state B
i++ // i = 2 . State C
i--; // i = 1, state B
i += 0; // state B

Side effects:
In general, when someone talks about side-effects in a function (regardless of the language), they are talking about changes to the state of the program outside of changes to the function parameters and the object itself.

The way I like to visualize side effect:

----------------------
            \ <= side effect
           ----------------

A function with no side effects in C (where we disregard the possibility of a function being a member function) might look like this:

int stateOfP(int a, char *p)
{
  *p = 0;
   return a+1;
}

In this case, the program has modified a location in memory pointed to by p, but as p is a memory location pointed to in an argument, we don’t count that as a side effect.

A function without side effects is a good thing, for a few reasons.

First, the absence of side effects makes it easier for the compiler to optimize use of the function.

Second, side effects make it much more difficult to prove the correctness of a program.

Finally, when using multiple threads, particularly in a C program, side effects can have undetermined outcomes. For example, if two threads modify an ordinary global variable in a C program without some special locking mechanism, the program’s outcome is undefined.

What does it look like when a function has side effects? Something like this:

int a = 0;
void stateChange(int p)
{
  a++; // here the function is having side effects as 'a' is not its attribute
  return;
}


问:
Pod shows as "Terminating" after node is shutdown
There was a pod named n404-neo4j-core-1 running on k8s-slave2. After k8s-slave2 was turned off, the pod was stuck with the Terminating.

I was expecting the pod to be deleted and a new pod be created on another node.
If this problem is not resolved, the neo4j cluster failed to keep HA.

```<code>kubectl get pods -o wide
    NAME                                     READY   STATUS        RESTARTS   AGE     IP          NODE         NOMINATED NODE   READINESS GATES
    n404-neo4j-core-0                        1/1     Running       0          3d19h   ***   k8s-node1    <none>           <none>
    n404-neo4j-core-1                        1/1     Terminating   0          78m     ***   k8s-slave2   <none>           <none>

    kubectl describe pod n404-neo4j-core-1

Name:                      n404-neo4j-core-1
Namespace:                 default
Priority:                  0
PriorityClassName:         <none>
Node:                      k8s-slave2/10.176.6.67
Start Time:                Mon, 01 Jun 2020 23:53:13 -0700
Labels:                    app.kubernetes.io/component=core
                           app.kubernetes.io/instance=n404
                           app.kubernetes.io/managed-by=Helm
                           app.kubernetes.io/name=neo4j
                           controller-revision-hash=n404-neo4j-core-67484bd88
                           helm.sh/chart=neo4j-4.0.4-1
                           statefulset.kubernetes.io/pod-name=n404-neo4j-core-1
Annotations:               <none>
Status:                    Terminating (lasts 21m)
Termination Grace Period:  30s
IP:                        10.36.0.1
Controlled By:             StatefulSet/n404-neo4j-core
Containers:
  n404-neo4j:
    Container ID:  docker://a045d7747678ca62734800d153d01f634b9972b527289541d357cbc27456bf7b
    Image:         neo4j:4.0.4-enterprise
    Image ID:      docker-pullable://neo4j@sha256:714d83e56a5db61eb44d65c114720f8cb94b06cd044669e16957aac1bd1b5c34
    Ports:         5000/TCP, 7000/TCP, 6000/TCP, 7474/TCP, 7687/TCP, 3637/TCP
    Host Ports:    0/TCP, 0/TCP, 0/TCP, 0/TCP, 0/TCP, 0/TCP
    Command:
      /bin/bash
      -c
      export core_idx=$(hostname | sed 's|.*-||')

      # Processes key configuration elements and exports env vars we need.
      . /helm-init/init.sh

      # We advertise the discovery-lb addresses (see discovery-lb.yaml) because
      # it is for internal cluster comms and is limited to private ports.
      export DISCOVERY_HOST="discovery-n404-neo4j-${core_idx}.default.svc.cluster.local"
      export NEO4J_causal__clustering_discovery__advertised__address="$DISCOVERY_HOST:5000"
      export NEO4J_causal__clustering_transaction__advertised__address="$DISCOVERY_HOST:6000"
      export NEO4J_causal__clustering_raft__advertised__address="$DISCOVERY_HOST:7000"

      echo "Starting Neo4j CORE $core_idx on $HOST"
      exec /docker-entrypoint.sh "neo4j"

    State:          Running
      Started:      Mon, 01 Jun 2020 23:53:14 -0700
    Ready:          True
    Restart Count:  0
    Liveness:       tcp-socket :7687 delay=300s timeout=2s period=10s #success=1 #failure=3
    Readiness:      tcp-socket :7687 delay=120s timeout=2s period=10s #success=1 #failure=3
    Environment Variables from:
      n404-neo4j-common-config  ConfigMap  Optional: false
      n404-neo4j-core-config    ConfigMap  Optional: false
    Environment:
      NEO4J_SECRETS_PASSWORD:  <set to the key 'neo4j-password' in secret 'n404-neo4j-secrets'>  Optional: false
    Mounts:
      /data from datadir (rw)
      /helm-init from init-script (rw)
      /plugins from plugins (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from n404-neo4j-sa-token-jp7g9 (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   True
  PodScheduled      True
Volumes:
  datadir:
    Type:       PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)
    ClaimName:  datadir-n404-neo4j-core-1
    ReadOnly:   false
  init-script:
    Type:      ConfigMap (a volume populated by a ConfigMap)
    Name:      n404-init-script
    Optional:  false
  plugins:
    Type:       EmptyDir (a temporary directory that shares a pod's lifetime)
    Medium:
    SizeLimit:  <unset>
  n404-neo4j-sa-token-jp7g9:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  n404-neo4j-sa-token-jp7g9
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  svc=neo4j
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
</code>```

答:
You should not down a Kubernetes node at sudden. If you do, you'll end up with some strange scenarios like this.

First, cordon the node. It notifies the scheduler the given node is not available for scheduling anymore.

kubectl cordon <node>

Then, drain the node. It moves the running pods to another node/nodes.

kubectl drain <node>

Now, you're safe to remove the node from the cluster.

Body:
There was a pod named n404-neo4j-core-1 running on k8s-slave2. After k8s-slave2 was turned off, the pod was stuck with the Terminating.

I was expecting the pod to be deleted and a new pod be created on another node.
If this problem is not resolved, the neo4j cluster failed to keep HA.

kubectl get pods -o wide
    NAME                                     READY   STATUS        RESTARTS   AGE     IP          NODE         NOMINATED NODE   READINESS GATES
    n404-neo4j-core-0                        1/1     Running       0          3d19h   ***   k8s-node1    <none>           <none>
    n404-neo4j-core-1                        1/1     Terminating   0          78m     ***   k8s-slave2   <none>           <none>

    kubectl describe pod n404-neo4j-core-1

Name:                      n404-neo4j-core-1
Namespace:                 default
Priority:                  0
PriorityClassName:         <none>
Node:                      k8s-slave2/10.176.6.67
Start Time:                Mon, 01 Jun 2020 23:53:13 -0700
Labels:                    app.kubernetes.io/component=core
                           app.kubernetes.io/instance=n404
                           app.kubernetes.io/managed-by=Helm
                           app.kubernetes.io/name=neo4j
                           controller-revision-hash=n404-neo4j-core-67484bd88
                           helm.sh/chart=neo4j-4.0.4-1
                           statefulset.kubernetes.io/pod-name=n404-neo4j-core-1
Annotations:               <none>
Status:                    Terminating (lasts 21m)
Termination Grace Period:  30s
IP:                        10.36.0.1
Controlled By:             StatefulSet/n404-neo4j-core
Containers:
  n404-neo4j:
    Container ID:  docker://a045d7747678ca62734800d153d01f634b9972b527289541d357cbc27456bf7b
    Image:         neo4j:4.0.4-enterprise
    Image ID:      docker-pullable://neo4j@sha256:714d83e56a5db61eb44d65c114720f8cb94b06cd044669e16957aac1bd1b5c34
    Ports:         5000/TCP, 7000/TCP, 6000/TCP, 7474/TCP, 7687/TCP, 3637/TCP
    Host Ports:    0/TCP, 0/TCP, 0/TCP, 0/TCP, 0/TCP, 0/TCP
    Command:
      /bin/bash
      -c
      export core_idx=$(hostname | sed 's|.*-||')

      # Processes key configuration elements and exports env vars we need.
      . /helm-init/init.sh

      # We advertise the discovery-lb addresses (see discovery-lb.yaml) because
      # it is for internal cluster comms and is limited to private ports.
      export DISCOVERY_HOST="discovery-n404-neo4j-${core_idx}.default.svc.cluster.local"
      export NEO4J_causal__clustering_discovery__advertised__address="$DISCOVERY_HOST:5000"
      export NEO4J_causal__clustering_transaction__advertised__address="$DISCOVERY_HOST:6000"
      export NEO4J_causal__clustering_raft__advertised__address="$DISCOVERY_HOST:7000"

      echo "Starting Neo4j CORE $core_idx on $HOST"
      exec /docker-entrypoint.sh "neo4j"

    State:          Running
      Started:      Mon, 01 Jun 2020 23:53:14 -0700
    Ready:          True
    Restart Count:  0
    Liveness:       tcp-socket :7687 delay=300s timeout=2s period=10s #success=1 #failure=3
    Readiness:      tcp-socket :7687 delay=120s timeout=2s period=10s #success=1 #failure=3
    Environment Variables from:
      n404-neo4j-common-config  ConfigMap  Optional: false
      n404-neo4j-core-config    ConfigMap  Optional: false
    Environment:
      NEO4J_SECRETS_PASSWORD:  <set to the key 'neo4j-password' in secret 'n404-neo4j-secrets'>  Optional: false
    Mounts:
      /data from datadir (rw)
      /helm-init from init-script (rw)
      /plugins from plugins (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from n404-neo4j-sa-token-jp7g9 (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   True
  PodScheduled      True
Volumes:
  datadir:
    Type:       PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)
    ClaimName:  datadir-n404-neo4j-core-1
    ReadOnly:   false
  init-script:
    Type:      ConfigMap (a volume populated by a ConfigMap)
    Name:      n404-init-script
    Optional:  false
  plugins:
    Type:       EmptyDir (a temporary directory that shares a pod's lifetime)
    Medium:
    SizeLimit:  <unset>
  n404-neo4j-sa-token-jp7g9:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  n404-neo4j-sa-token-jp7g9
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  svc=neo4j
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s


答:
You should have another field in your mapping that is not lowercased and that's the one you search on.

```<code>"mappings": {
    "properties": {
        "event": {
            "type": "keyword",
            "fields": {
                "search": {
                    "type": "keyword",
                    "normalizer": "normalizer_1",
                }
            }
        },
        .....
    }
}
</code>```

Your query would then need to run on event.search instead of `event``

```<code>    simple_query_string: {
        query: ''+term+'*', // converts to string; adds * to match prefix
        fields: ['event.search']
    }                      ^
                           |
                       add this
</code>```

All the rest can stay the same.

Title: Elasticsearch terms aggregation and lowercase values

Body:
You should have another field in your mapping that is not lowercased and that's the one you search on.

"mappings": {
    "properties": {
        "event": {
            "type": "keyword",
            "fields": {
                "search": {
                    "type": "keyword",
                    "normalizer": "normalizer_1",
                }
            }
        },
        .....
    }
}

Your query would then need to run on event.search instead of `event``

    simple_query_string: {
        query: ''+term+'*', // converts to string; adds * to match prefix
        fields: ['event.search']
    }                      ^
                           |
                       add this

All the rest can stay the same.


问:
Yesod fails to install (namely the text package)
I'm trying to install Yesod via cabal, but it keeps failing on installing Data.Text.

I tried installing text separately with cabal install text, resulting in an error message:

```<code>Resolving dependencies...
Configuring text-0.11.1.0...
Preprocessing library text-0.11.1.0...
Building text-0.11.1.0...

Data/Text/Lazy/Builder/RealFloat.hs:21:7:
    Could not find module `Data.Text.Lazy.Builder.RealFloat.Functions':
      Use -v to see a list of the files searched for.
cabal: Error: some packages failed to install:
text-0.11.1.0 failed during the building phase. The exception was:
ExitFailure 1
</code>```

Investigating the directory structure of the text package that was downloaded, I find that there really is no Data/Text/Lazy/Builder/RealFloat/Functions.hs.  The closest thing is Data/Text/Lazy/Builder/Functions.hs (but this doesn't contain the function RealFloat.hs was trying to import, which was roundTo).

How can I fix this?

答: This is a ghc7.0 related issue (and listed at hackage under "Build failure"). Try to install text-0.11.0.8 that should work for yesod.</p>

Body:
I'm trying to install Yesod via cabal, but it keeps failing on installing Data.Text.

I tried installing text separately with cabal install text, resulting in an error message:

Resolving dependencies...
Configuring text-0.11.1.0...
Preprocessing library text-0.11.1.0...
Building text-0.11.1.0...

Data/Text/Lazy/Builder/RealFloat.hs:21:7:
    Could not find module `Data.Text.Lazy.Builder.RealFloat.Functions':
      Use -v to see a list of the files searched for.
cabal: Error: some packages failed to install:
text-0.11.1.0 failed during the building phase. The exception was:
ExitFailure 1

Investigating the directory structure of the text package that was downloaded, I find that there really is no Data/Text/Lazy/Builder/RealFloat/Functions.hs.  The closest thing is Data/Text/Lazy/Builder/Functions.hs (but this doesn't contain the function RealFloat.hs was trying to import, which was roundTo).

How can I fix this?


问:
How to interpolate a variable in IconData in Flutter?
I want to show the icon of a social media.

```<code>String socialMedia = 'facebook';
</code>```

Then in my build function I want to use this variable in my Icon widget

```<code>Icon(FontAwesomeIcons.socialMedia)
</code>```

How can I interpolate this variable? Is it possible?
It would become easy for me if I could use the variable like this. Because now I can use the variable to change the icon accordingly.

答:
You can copy paste run full code below

You can use package https://pub.dev/packages/icons_helper

You can use getIconUsingPrefix and for FontAwesome Icon you can prefix string with fa.

code snippet

```<code>Icon(getIconUsingPrefix(name: 'fa.fiveHundredPx'),
                color: Theme.of(context).backgroundColor, size: 128.0),
Icon(getIconUsingPrefix(name: 'fa.facebook'),
    color: Theme.of(context).backgroundColor, size: 128.0),
Icon(getIconUsingPrefix(name: 'add'),
    color: Theme.of(context).backgroundColor, size: 128.0),
</code>```

working demo

full code

```<code>import 'package:flutter/material.dart';
import 'package:icons_helper/icons_helper.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Icon(getIconUsingPrefix(name: 'fa.fiveHundredPx'),
                color: Theme.of(context).backgroundColor, size: 128.0),
            Icon(getIconUsingPrefix(name: 'fa.facebook'),
                color: Theme.of(context).backgroundColor, size: 128.0),
            Icon(getIconUsingPrefix(name: 'add'),
                color: Theme.of(context).backgroundColor, size: 128.0),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}
</code>```

Body:
I want to show the icon of a social media.

String socialMedia = 'facebook';

Then in my build function I want to use this variable in my Icon widget

Icon(FontAwesomeIcons.socialMedia)

How can I interpolate this variable? Is it possible?
It would become easy for me if I could use the variable like this. Because now I can use the variable to change the icon accordingly.

Body:
You can copy paste run full code below

You can use package https://pub.dev/packages/icons_helper

You can use getIconUsingPrefix and for FontAwesome Icon you can prefix string with fa.

code snippet

Icon(getIconUsingPrefix(name: 'fa.fiveHundredPx'),
                color: Theme.of(context).backgroundColor, size: 128.0),
Icon(getIconUsingPrefix(name: 'fa.facebook'),
    color: Theme.of(context).backgroundColor, size: 128.0),
Icon(getIconUsingPrefix(name: 'add'),
    color: Theme.of(context).backgroundColor, size: 128.0),

working demo

full code

import 'package:flutter/material.dart';
import 'package:icons_helper/icons_helper.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Icon(getIconUsingPrefix(name: 'fa.fiveHundredPx'),
                color: Theme.of(context).backgroundColor, size: 128.0),
            Icon(getIconUsingPrefix(name: 'fa.facebook'),
                color: Theme.of(context).backgroundColor, size: 128.0),
            Icon(getIconUsingPrefix(name: 'add'),
                color: Theme.of(context).backgroundColor, size: 128.0),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}


问:
Sharing doesn't work on Google Apps Script Editor
I am working on Google Apps Script. I want to share the Google Apps Script Editor to another account.I use Chrome browser.

I clicked File > Sharing in the editor. But I got this error:

I tried to remove all the cache and cookies and histories from the browser. but, same.

答:
If you want to share a script bound to spreadsheet you need to share the spreadsheet itself

It is no possible to share a bound script is the spreadsheet is not shared

If the spreadsheet is shared, there is no need to explicitly share the script


问:
IIS only processing one request at a time
We have an asp.net web application that works fine in our environment.  One of our partners tries to the exact same code in their environment and can only process one request at a time.  For example, there is only page that calls a long running stored procedure (5 minutes).  If you call that page and the try to open a new page, the new page won't serve until after the first page has completed.  We can see the request back up by looking at the worker processes for their application pool.   They are running IIS 8.5 on a windows 2012 server.  They're also running SQL Server 2016.

The database connection is structured the same as as in our environment.  The stored procedure is not wrapped in a transaction.  Any ideas what might be causing this behavior?

答:
IIS also can work in the Debug mode, when it is enabled, Asp is limited to processing one request at a time in a single-threaded manner.

Open “InetMgr” or IIS manager, double click ASP under the IIS section of the website. Check the below settings in Asp section.

See the below discussion for more information.

IIS7 - only serves up one page at a time. It's a making me crAzY!


问:
fatal- 'origin' does not appear to be a git repository
I created a remote repo then create a local one locally:

```<code>git init
</code>```

then added the files i need using git add then git commit  -m "something"

finally git push origin master

I got this error fatal:

```<code>'origin' does not appear to be a git repository
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

should i like the remote and local in some command or something? and if so is it ok if i already added and commited or should i start over locally?

EDIT:

Apparently i should add git remote add origin ssh://git@example.com:1234/myRepo.git
 but what should i replace that ssh with as in where can i find my version of what i should add.

Got this error :

```<code>! [rejected]        master -> master (fetch first)
error: failed to push some refs to
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
</code>```

答:
Run below command

```<code>git remote add origin git@github.com:xxxx/xxxx.git
</code>```

no SSH please!

Body:
I created a remote repo then create a local one locally:

git init

then added the files i need using git add then git commit  -m "something"

finally git push origin master

I got this error fatal:

'origin' does not appear to be a git repository
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

should i like the remote and local in some command or something? and if so is it ok if i already added and commited or should i start over locally?

EDIT:

Apparently i should add git remote add origin ssh://git@example.com:1234/myRepo.git
 but what should i replace that ssh with as in where can i find my version of what i should add.

Got this error :

! [rejected]        master -> master (fetch first)
error: failed to push some refs to
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

Body:
Run below command

git remote add origin git@github.com:xxxx/xxxx.git

no SSH please!


问:
How to work with multiple promise and resolve with Promise.all?
I am trying to put multiple promises inside an array and when i am console the promiseArray getting an empty array.don't know how it prints an empty array. and userRecord is the auth and inside that email is there i am resolving then i am trying to solve the problem in this way</p>

```<code>const fn = async campaign => {
  const promiseArray = [];
  if (campaign.stage === "active") {
    userRecord.map(async data => {
      if (data.email !== "" && data.email !== undefined) {
        const sendEmail = await SES.sendRawEmail(params).promise();
        promiseArray.push(sendEmail);
      }
    });
  }
  if (campaign.stage === "joined") {
    userRecord.map(async data => {
      if (data.email !== "" && data.email !== undefined) {
        const sendEmailJoined = await SES.sendRawEmail(params).promise();
        promiseArray.push(sendEmailJoined);
      }
    });
  }
console.log(promiseArray)
  //I am trying to resolve this in two ways
  await Promise.all(promiseArray);
  //here is the second method
  await Promise.all(
    promiseArray.map(async promise => {
      await promise;
    })
  );
};
</code>```

答:
You are just a bit confused where to use async and await. Don't use it for your mapping functions and don't await the function when pushing it into your promise array.

// helper function to simulate async
const SES = {
    sendRawEmail: async params => {
      return new Promise(res => {
        setTimeout(async () => {
            console.log(params);
            res();
        }, Math.random() * 1000);
      });
    }
}

const fn = async campaign => {

    const promiseArray = [];
    // some sample data for simulation
    const userRecord = [{ email: "a@a.ch", params: 1 }, { email: "b@b.ch", params: 2 }, { email: "c@c.ch", params: 3 }, { email: "d@d.ch", params: 4 }];
    // I cleaned up your if a bit as you dublicate code here
    if (campaign.stage === "active" || campaign.stage === "joined") {
        // also don't use await here
        // replace map with forEach as it suits your problem better as @Benjamin Eckardt pointed out
        userRecord.forEach(data => {
            if (data.email) {
                // don't use await here
                // const sendEmailJoined = await SES.sendRawEmail(params).promise();
                // i made a little shortcut here
                promiseArray.push(SES.sendRawEmail(data));
            }
        });
    }

    await Promise.all(promiseArray)
    console.log("finish");
};

fn({ stage: "active" });```

Body:
I am trying to put multiple promises inside an array and when i am console the promiseArray getting an empty array.don't know how it prints an empty array. and userRecord is the auth and inside that email is there i am resolving then i am trying to solve the problem in this way

const fn = async campaign => {
  const promiseArray = [];
  if (campaign.stage === "active") {
    userRecord.map(async data => {
      if (data.email !== "" && data.email !== undefined) {
        const sendEmail = await SES.sendRawEmail(params).promise();
        promiseArray.push(sendEmail);
      }
    });
  }
  if (campaign.stage === "joined") {
    userRecord.map(async data => {
      if (data.email !== "" && data.email !== undefined) {
        const sendEmailJoined = await SES.sendRawEmail(params).promise();
        promiseArray.push(sendEmailJoined);
      }
    });
  }
console.log(promiseArray)
  //I am trying to resolve this in two ways
  await Promise.all(promiseArray);
  //here is the second method
  await Promise.all(
    promiseArray.map(async promise => {
      await promise;
    })
  );
};


问:
Overwriting init() in python. TypeError: __init__() takes 1 positional argument but 3 were given
```<code>class A:
    x = 0

    def __init__(self, a, b):
        self.a = a
        self.b = b
        A.x += 1

    def __init__(self):
        A.x += 1

    def displayCount(self):
        print('Count : %d' % A.x)

    def display(self):
        print('a :', self.a, ' b :', self.b)

a1 = A('George', 25000)
a2 = A('John', 30000)
a3 = A()
a1.display()
a2.display()
print(A.x)
</code>```

I expect output as:

a : George  b : 25000

a : John  b : 30000

3

But I'm getting this error:

TypeError: init() takes 1 positional argument but 3 were given

Help out a beginner

Thanks.

答:
You can't have overloaded methods in a Python class.

This will result in just the second __init__ staying around and the first one will be discarded:

```<code>def __init__(self, a, b):  # Will get shadowed and thrown away.
    self.a = a
    self.b = b
    A.x += 1

def __init__(self):  # Only this one will be left in the class.
    A.x += 1
</code>```

You can achieve pretty much the same functionality with parameter defaults:

```<code>def __init__(self, a=None, b=None):
    self.a = a
    self.b = b
    A.x += 1
</code>```

Body:
class A:
    x = 0

    def __init__(self, a, b):
        self.a = a
        self.b = b
        A.x += 1

    def __init__(self):
        A.x += 1

    def displayCount(self):
        print('Count : %d' % A.x)

    def display(self):
        print('a :', self.a, ' b :', self.b)

a1 = A('George', 25000)
a2 = A('John', 30000)
a3 = A()
a1.display()
a2.display()
print(A.x)

I expect output as:

a : George  b : 25000

a : John  b : 30000

3

But I'm getting this error:

TypeError: init() takes 1 positional argument but 3 were given

Help out a beginner

Thanks.

Body:
You can't have overloaded methods in a Python class.

This will result in just the second __init__ staying around and the first one will be discarded:

def __init__(self, a, b):  # Will get shadowed and thrown away.
    self.a = a
    self.b = b
    A.x += 1

def __init__(self):  # Only this one will be left in the class.
    A.x += 1

You can achieve pretty much the same functionality with parameter defaults:

def __init__(self, a=None, b=None):
    self.a = a
    self.b = b
    A.x += 1


问:
Why is my fibonacci function using a javascript while loop not working?
Why is my code to generate a fibonacci sequence not working? Fibonacci sequence would go like this: [0,1,1,2,3,5,8,13,21,34] when n=10 and so on if greater, where the last two numbers are added to give the next number. I tried this using a while loop as I initially tried using a for loop but I couldn't determine a change to put in the (). I don't think there are any problems in the first 8 lines of the code as I tried them before and they worked so problem is after but I can't figure it out...thanks in advance!

```<code>var seq = [];

function fibonacciGenerator(n) {

    if (n === 1) {
      seq.push(0);

    } else if (n === 2) {
      seq.push(0, 1);

    } else if (n > 2) {
      seq.push(0, 1);

      while(len < n) {
 var len = seq.length;
        seq.push(seq[len] + seq[len - 1]);
      }
    }

  return seq;
}

console.log(fibonacciGenerator(10));
</code>```

Edit: This is the code that works for n=1 and n=2 hence I'm convinced that the problem is in the while loop but I can't figure it out. :

```<code>var seq = [];

function fibonacciGenerator(n) {

if (n === 1) {
  seq.push(0);

} else if (n === 2) {
  seq.push(0, 1);

}
return seq;
}

console.log(fibonacciGenerator(2));
</code>```

Now my console is printing [0,1]

Edit:

Ok guys I fixed the code myself and now it works if anyone wants to know how to use while loop for fib seq here it is:

```<code>var seq = [];

function fibonacciGenerator(n) {

if (n === 1) {
seq.push(0);

} else if (n === 2) {
seq.push(0, 1);

} else if (n > 2) {
seq.push(0, 1);

var len = seq.length;

while (len < n) {
  seq.push(seq[len-1] + seq[len - 2]);
  len++;
}
}

return seq;
}

console.log(fibonacciGenerator(10));
</code>```

答:
Here is a proper fibonacci module:

function fibonacciGenerator(n){
  var fib = []; // Initialize array!
  fib[0] = 0;
  fib[1] = 1;
  for (var i = 2; i < n; i++) {
    // Next fibonacci number = previous + one before previous
    // Translated to JavaScript:
    fib[i] = fib[i - 2] + fib[i - 1];
  }
  return fib;
}
console.log(fibonacciGenerator(10))```

Hope it will help!

Edit as pinted out my function was doing adding 1 extra line. Fixed by replaceing for (var i = 2; i <= n; i++) { with for (var i = 2; i < n; i++) {

Body:
Why is my code to generate a fibonacci sequence not working? Fibonacci sequence would go like this: [0,1,1,2,3,5,8,13,21,34] when n=10 and so on if greater, where the last two numbers are added to give the next number. I tried this using a while loop as I initially tried using a for loop but I couldn't determine a change to put in the (). I don't think there are any problems in the first 8 lines of the code as I tried them before and they worked so problem is after but I can't figure it out...thanks in advance!

var seq = [];

function fibonacciGenerator(n) {

    if (n === 1) {
      seq.push(0);

    } else if (n === 2) {
      seq.push(0, 1);

    } else if (n > 2) {
      seq.push(0, 1);

      while(len < n) {
 var len = seq.length;
        seq.push(seq[len] + seq[len - 1]);
      }
    }

  return seq;
}

console.log(fibonacciGenerator(10));

Edit: This is the code that works for n=1 and n=2 hence I'm convinced that the problem is in the while loop but I can't figure it out. :

var seq = [];

function fibonacciGenerator(n) {

if (n === 1) {
  seq.push(0);

} else if (n === 2) {
  seq.push(0, 1);

}
return seq;
}

console.log(fibonacciGenerator(2));

Now my console is printing [0,1]

Edit:

Ok guys I fixed the code myself and now it works if anyone wants to know how to use while loop for fib seq here it is:

var seq = [];

function fibonacciGenerator(n) {

if (n === 1) {
seq.push(0);

} else if (n === 2) {
seq.push(0, 1);

} else if (n > 2) {
seq.push(0, 1);

var len = seq.length;

while (len < n) {
  seq.push(seq[len-1] + seq[len - 2]);
  len++;
}
}

return seq;
}

console.log(fibonacciGenerator(10));

Body:
Here is a proper fibonacci module:

function fibonacciGenerator(n){
  var fib = []; // Initialize array!
  fib[0] = 0;
  fib[1] = 1;
  for (var i = 2; i < n; i++) {
    // Next fibonacci number = previous + one before previous
    // Translated to JavaScript:
    fib[i] = fib[i - 2] + fib[i - 1];
  }
  return fib;
}
console.log(fibonacciGenerator(10))

Hope it will help!

Edit as pinted out my function was doing adding 1 extra line. Fixed by replaceing for (var i = 2; i <= n; i++) { with for (var i = 2; i < n; i++) {


问:
How to use IEnumerable function in shared class accross project
I have a common IEnumerable function that I need to use in every controller on my asp,net web mvc application. I have created a SharedClass folder and a public class CommonMethods.

```<code>using System.Collections.Generic; using System.Web.Mvc;
namespace LearnWeb.SharedClass
{
public class CommonMethods
{
    public IEnumerable<SelectListItem> GetSelectListItems(IEnumerable<string> elements)
    {
        // Create an empty list to hold result of the operation
        var selectList = new List<SelectListItem>();

        // For each string in the 'elements' variable, create a new SelectListItem object
        // that has both its Value and Text properties set to a particular value.
        // This will result in MVC rendering each item as:
        //     <option value="State Name">State Name</option>
        foreach (var element in elements)
        {
            selectList.Add(new SelectListItem
            {
                Value = element,
                Text = element
            });
        }
        return selectList;
    }
}
}
</code>```

I have a controller class StockController and I want to use the above common Method inside it. But I'm not able to reference it correctly. Please guide.

```<code>using System.Collections.Generic;
using System.Web.Mvc;
using LearnWeb.Models;
using LearnWeb.SharedClass.CommonMethods;

namespace LearnWeb.Controllers
{
public class StockController : Controller
{
/ GET: Stock
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult NewStock()
    {
        ViewBag.Message = "Enter new stock details.";
        var model = new StockModel();
        model.items = GetSelectListItems(items); //trying to call the commonMethods.GetSelectListItems
        return View(model);
    }
 }
</code>```

I have declared both the class and the function as public and added reference but not able to link in the controller class.

Regards,
NewB

答: this line is wrong using LearnWeb.SharedClass.CommonMethods; it should be using LearnWeb.SharedClass

Body:
I have a common IEnumerable function that I need to use in every controller on my asp,net web mvc application. I have created a SharedClass folder and a public class CommonMethods.

using System.Collections.Generic; using System.Web.Mvc;
namespace LearnWeb.SharedClass
{
public class CommonMethods
{
    public IEnumerable<SelectListItem> GetSelectListItems(IEnumerable<string> elements)
    {
        // Create an empty list to hold result of the operation
        var selectList = new List<SelectListItem>();

        // For each string in the 'elements' variable, create a new SelectListItem object
        // that has both its Value and Text properties set to a particular value.
        // This will result in MVC rendering each item as:
        //     <option value="State Name">State Name</option>
        foreach (var element in elements)
        {
            selectList.Add(new SelectListItem
            {
                Value = element,
                Text = element
            });
        }
        return selectList;
    }
}
}

I have a controller class StockController and I want to use the above common Method inside it. But I'm not able to reference it correctly. Please guide.

using System.Collections.Generic;
using System.Web.Mvc;
using LearnWeb.Models;
using LearnWeb.SharedClass.CommonMethods;

namespace LearnWeb.Controllers
{
public class StockController : Controller
{
/ GET: Stock
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult NewStock()
    {
        ViewBag.Message = "Enter new stock details.";
        var model = new StockModel();
        model.items = GetSelectListItems(items); //trying to call the commonMethods.GetSelectListItems
        return View(model);
    }
 }

I have declared both the class and the function as public and added reference but not able to link in the controller class.

Regards,
NewB


问:
Hi I'm beginner in dart ,I can't find the main.dart
I installed the dart sdk and I did the plugin of dart in the intellij i choose console application ,but i can't find how to do the command line app , it starts the pubspec.yaml not with the main.dart.
(ubuntu linux)
sorry for that kind of question .
help me please</p>

答:
Run the main script in command line</p>

```<code>dart main.dart
</code>```

Body:
Run the main script in command line

dart main.dart


问:
How to use the absolute path of a file on another hard drive with Oracle (sqlplus)?
I am surprised I did not find anything about this anywhere, but how do I execute a file with sqlplus with the absolute path of the file? In the internet it says

```<code>sqlplus databaseURL @sqlFile
</code>```

This works if I use it as relative File and have the SQL File in the same directory. But using a path after the "@" just doesn't work and it says "file does not exist" when I run the command. The file surely is in the specified path and I am on Windows.

How do I make this work?

EDIT: Example of relative path:

```<code>sqlplus -l user/pw@localhost:1521/service @test.sql;
</code>```

Example of absolute path

```<code>sqlplus -l user/pw@localhost:1521/service @D:/folder/test.sql;
</code>```

答:
So to clarify what the problem for me was, it was actually just in the file itself.. I used "\" instead of "/" at the end of the SQL File. After I changed that, it worked for me. My command looked like this in the end:</p>

```<code>sqlplus -l user/pw@localhost:1521/service @D:\folder\test.sql;
</code>```

Body:
I am surprised I did not find anything about this anywhere, but how do I execute a file with sqlplus with the absolute path of the file? In the internet it says

sqlplus databaseURL @sqlFile

This works if I use it as relative File and have the SQL File in the same directory. But using a path after the "@" just doesn't work and it says "file does not exist" when I run the command. The file surely is in the specified path and I am on Windows.

How do I make this work?

EDIT: Example of relative path:

sqlplus -l user/pw@localhost:1521/service @test.sql;

Example of absolute path

sqlplus -l user/pw@localhost:1521/service @D:/folder/test.sql;

Body:
So to clarify what the problem for me was, it was actually just in the file itself.. I used "\" instead of "/" at the end of the SQL File. After I changed that, it worked for me. My command looked like this in the end:

sqlplus -l user/pw@localhost:1521/service @D:\folder\test.sql;


问:
Docker mirror for windows images
Good day!
I have problems with configuring docker private registry. I can create a docker private registry on Linux RHEL. I configured it work as a mirror, and I can pull images from global DOCKER HUB, for Linux without a problem. But when I try to configuration this private registry work as a mirror for Windows machine. I can pull images from mcr.microsoft.com. Can anybody help me?

correct for LINUX:

```<code>version: 0.1
log:
  fields:
    service: registry
storage:
  filesystem:
    rootdirectory: /var/lib/registry
http:
  addr: :5000
proxy:
  remoteurl: https://registry-1.docker.io
</code>```

if I change on

```<code>proxy:
  remoteurl: https://mcr.microsoft.com
</code>```

doesn't work.

答:
Got it to work like this:

My config.yml is in ~/.docker/docker-registry. It looks like this:

```<code>version: 0.1
log:
  fields:
    service: registry
storage:
  cache:
    blobdescriptor: inmemory
  filesystem:
    rootdirectory: /var/lib/registry
http:
  addr: :5000
  headers:
    X-Content-Type-Options: [nosniff]
health:
  storagedriver:
    enabled: true
    interval: 10s
    threshold: 3
proxy:
  remoteurl: https://mcr.microsoft.com
</code>```

I run the registry image like this:

```<code>docker run --restart=always -p 5000:5000 --name v2-mirror -v ~/.docker/docker-registry:/var/lib/registry --detach registry:2 serve /var/lib/registry/config.yml
</code>```

In my case, the container is reachable from a windows machine at 172.16.68.1:5000.

Then I can do a docker pull 172.16.68.1:5000/windows/nanoserver:1809

Note that the "pull-through cache" feature is not available for registries other than the official docker hub, see docker doc:

It’s currently not possible to mirror another private registry. Only
  the central Hub can be mirrored.

Title: Docker mirror for windows images

Body:
Good day!
I have problems with configuring docker private registry. I can create a docker private registry on Linux RHEL. I configured it work as a mirror, and I can pull images from global DOCKER HUB, for Linux without a problem. But when I try to configuration this private registry work as a mirror for Windows machine. I can pull images from mcr.microsoft.com. Can anybody help me?

correct for LINUX:

version: 0.1
log:
  fields:
    service: registry
storage:
  filesystem:
    rootdirectory: /var/lib/registry
http:
  addr: :5000
proxy:
  remoteurl: https://registry-1.docker.io

if I change on

proxy:
  remoteurl: https://mcr.microsoft.com

doesn't work.

Body:
Got it to work like this:

My config.yml is in ~/.docker/docker-registry. It looks like this:

version: 0.1
log:
  fields:
    service: registry
storage:
  cache:
    blobdescriptor: inmemory
  filesystem:
    rootdirectory: /var/lib/registry
http:
  addr: :5000
  headers:
    X-Content-Type-Options: [nosniff]
health:
  storagedriver:
    enabled: true
    interval: 10s
    threshold: 3
proxy:
  remoteurl: https://mcr.microsoft.com

I run the registry image like this:

docker run --restart=always -p 5000:5000 --name v2-mirror -v ~/.docker/docker-registry:/var/lib/registry --detach registry:2 serve /var/lib/registry/config.yml

In my case, the container is reachable from a windows machine at 172.16.68.1:5000.

Then I can do a docker pull 172.16.68.1:5000/windows/nanoserver:1809

Note that the "pull-through cache" feature is not available for registries other than the official docker hub, see docker doc:

It’s currently not possible to mirror another private registry. Only
  the central Hub can be mirrored.


问:
How to return an array of class type and fill?
I have a function which is supposed to return an array of class type.

So from database I picked data and filled datatable. Now from datatable I am picking columns value and assigning to the properties of the class. But problem is that what I am doing will assign a single record only but I want to fill the class type array with multiple record.

My code:

```<code>Private Sub BindGridInfoFunctionalLocation()
        Dim v_ObjDs As New DataSet
        Try
            v_ObjDs = v_ObjBREngine.FetchSqlDS("select FunctionalLocation as 'TagNo', EquipmentDescription as 'TagDescription', Area as 'ParentHeirarchy', EqptType as 'TypeClass' from EngineeringData")

            Dim dtTableFL As DataTable
            dtTableFL.Columns.Add("TagNo", GetType(String))
            dtTableFL.Columns.Add("TagDescription", GetType(String))
            dtTableFL.Columns.Add("ParentHeirarchy", GetType(String))
            dtTableFL.Columns.Add("Class", GetType(String))

            dtTableFL = v_ObjDs.Tables(0)

            Dim AssetsCls As New AssetsDto
            'Dim AssetsClsArray As New AssetsDto()

            If v_ObjDs.Tables(0).Rows.Count > 0 Then
                'v_ObjDs.Tables(0).Rows.Add(v_ObjDs.Tables(0).NewRow())

                For Each Item In dtTableFL.Rows

                    AssetsCls.ASSETTAG = Item("TagNo")
                    AssetsCls.ASSETDESC = Item("TagDescription")
                    AssetsCls.PARENTTAG = Item("ParentHeirarchy")
                    AssetsCls.ASSETTYPE = Item("TypeClass")

                Next

                gv_InfoFunctionalLocation.DataSource = v_ObjDs
                gv_InfoFunctionalLocation.DataBind()
            End If
        Catch ex As Exception
            Throw ex
        End Try
    End Sub
</code>```

Note:

the return type and everything should be like this since I am interacting with the client's web service and it expects it this way only.

答:
This is only an indirect answer, but: ultimately, the thing you are trying to do is a solved problem, with lots of tools existing to do all the work for you. Since this is a simple scenario, "Dapper" would make this trivial. I'll give a C# example here, as my VB level is read-only:

List<AssetsDto> BindGridInfoFunctionalLocation()
{
    // note: column aliases to match properties on AssetsDto
    var results = connection.Query<AssetsDto>(@"
select  FunctionalLocation as 'ASSETTAG',
        EquipmentDescription as 'ASSETDESC',
        Area as 'PARENTTAG',
        EqptType as 'ASSETTYPE'
from    EngineeringData").AsList();

    gv_InfoFunctionalLocation.DataSource = results;
    gv_InfoFunctionalLocation.DataBind()
    return results;
}

```

Body:
I have a function which is supposed to return an array of class type.

So from database I picked data and filled datatable. Now from datatable I am picking columns value and assigning to the properties of the class. But problem is that what I am doing will assign a single record only but I want to fill the class type array with multiple record.

My code:

Private Sub BindGridInfoFunctionalLocation()
        Dim v_ObjDs As New DataSet
        Try
            v_ObjDs = v_ObjBREngine.FetchSqlDS("select FunctionalLocation as 'TagNo', EquipmentDescription as 'TagDescription', Area as 'ParentHeirarchy', EqptType as 'TypeClass' from EngineeringData")

            Dim dtTableFL As DataTable
            dtTableFL.Columns.Add("TagNo", GetType(String))
            dtTableFL.Columns.Add("TagDescription", GetType(String))
            dtTableFL.Columns.Add("ParentHeirarchy", GetType(String))
            dtTableFL.Columns.Add("Class", GetType(String))

            dtTableFL = v_ObjDs.Tables(0)

            Dim AssetsCls As New AssetsDto
            'Dim AssetsClsArray As New AssetsDto()

            If v_ObjDs.Tables(0).Rows.Count > 0 Then
                'v_ObjDs.Tables(0).Rows.Add(v_ObjDs.Tables(0).NewRow())

                For Each Item In dtTableFL.Rows

                    AssetsCls.ASSETTAG = Item("TagNo")
                    AssetsCls.ASSETDESC = Item("TagDescription")
                    AssetsCls.PARENTTAG = Item("ParentHeirarchy")
                    AssetsCls.ASSETTYPE = Item("TypeClass")

                Next

                gv_InfoFunctionalLocation.DataSource = v_ObjDs
                gv_InfoFunctionalLocation.DataBind()
            End If
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

Note:

the return type and everything should be like this since I am interacting with the client's web service and it expects it this way only.


问:
Laravel: Seeding table with several belongs to relationship using factories
tl;dr:

I am using Laravel and Eloquent and trying to seed a database and attach several belongs to relationship to one table, but I get the error:

Call to undefined method
  Illuminate\Database\Eloquent\Relations\BelongsTo::attach()

Detailed explanation:

I am using php 7.1 and Laravel 6 with Eloquent. I am trying to seed a test database. I have the following relationship structure:

one user has several posts / one post belongs to one user

one category has several posts / one post belongs to one category

User model:

```<code>class User extends Model
{
    protected $table = 'users';

    public function posts()
    {
        return $this->hasMany('App\Models\Post');
    }
}
</code>```

Category model:

```<code>class Category extends Model
{
    protected $table = 'categories';

    public function posts()
    {
        return $this->hasMany('App\Models\Category');
    }
}
</code>```

Post model:

```<code>class Post extends Model
{
    protected $table = 'posts';

    public function category()
    {
        return $this->belongsTo('App\Models\Category');
    }

    public function user()
    {
        return $this->belongsTo('App\Models\User');
    }
}
</code>```

User factory:

```<code>$factory->define(User::class, function (Faker $faker) {
    return [
        'id' => $faker->unique()->randomNumber(3),
        'name' => $faker->name(),
    ];
});
</code>```

Category factory:

```<code>$factory->define(Category::class, function (Faker $faker) {
    return [
        'id' => $faker->unique()->randomNumber(3),
        'name' => $faker->word(),
    ];
});
</code>```

Post factory:

```<code>$factory->define(User::class, function (Faker $faker) {
    return [
        'id' => $faker->unique()->randomNumber(3),
        'name' => $faker->realText($maxNbChars = 200, $indexSize = 2),
    ];
});
</code>```

If I only had users and posts, I know that I could seed the database the following way:

```<code>public function seed()
{
    $users = factory(App\User::class, 10)
        ->create()
        ->each(function ($user) {
            $user->posts()->createMany(factory(App\Post::class, 10)->make()->toArray());
        });
}
</code>```

but obviously that won't work in my case. I have tried the following:

```<code>public function seed()
{
    factory(User::class, 10)->create();
    factory(Category::class, 10)->create();
    factory(Post::class, 100)->create()->each(function ($post){
        $post->user()->attach(User::all()->random(1));
        $post->category()->attach(Category::all()->random(1));
    });
}
</code>```

as well as the same function using make/save instead of create:

```<code>public function seed()
    {
        factory(User::class, 10)->create();
        factory(Category::class, 10)->create();
        factory(Post::class, 100)->make()->each(function ($post) {
            $post->user()->attach(User::all()->random(1));
            $post->category()->attach(Category::all()->random(1));
        })->save();
    }
</code>```

but in both cases, I get the error:

Call to undefined method
  Illuminate\Database\Eloquent\Relations\BelongsTo::attach()

答:
You have to use associate():

```<code>public function seed()
{
    factory(User::class, 10)->create();
    factory(Category::class, 10)->create();
    factory(Post::class, 100)->make()->each(function ($post) {
        $post->user()->associate(User::inRandomOrder()->first());
        $post->category()->associate(Category::inRandomOrder()->first());
        $post->save();
    });
}
</code>```

Also User::all()->random(1) will return a collection and not a model, which will throw an exception, I replaced it with Model::inRandomOrder()->first(), which will fetch a random model from the database.

From the docs:

When updating a belongsTo relationship, you may use the associate
  method. This method will set the foreign key on the child model:

```<code>$account = App\Account::find(10);

$user->account()->associate($account);

$user->save();
</code>```

Update

In your Modelfactory:

```<code>/** @var Factory $factory */
$factory->define(Post::class, function (Faker\Generator $faker) {
    return [
        // not sure why you do this, is it not a autoincrement column?
        'id' => $faker->unique()->randomNumber(3),
        'name' => $faker->realText($maxNbChars = 200, $indexSize = 2),
        'category_id' => function () {
            if ($category = Category::inRandomOrder()->first()) {
                return $category->id;
            }

            return factory(Category::class)->create()->id;
        },
        'user_id' => function () {
            if ($user = User::inRandomOrder()->first()) {
                return $user->id;
            }

            return factory(User::class)->create()->id;
        },
    ];
});
</code>```

In your seeder:

```<code>public function seed()
{
    factory(User::class, 10)->create();
    factory(Category::class, 10)->create();
    factory(Post::class, 100)->create();
}
</code>```

Body:
tl;dr:

I am using Laravel and Eloquent and trying to seed a database and attach several belongs to relationship to one table, but I get the error:

Call to undefined method
  Illuminate\Database\Eloquent\Relations\BelongsTo::attach()

Detailed explanation:

I am using php 7.1 and Laravel 6 with Eloquent. I am trying to seed a test database. I have the following relationship structure:

one user has several posts / one post belongs to one user

one category has several posts / one post belongs to one category

User model:

class User extends Model
{
    protected $table = 'users';

    public function posts()
    {
        return $this->hasMany('App\Models\Post');
    }
}

Category model:

class Category extends Model
{
    protected $table = 'categories';

    public function posts()
    {
        return $this->hasMany('App\Models\Category');
    }
}

Post model:

class Post extends Model
{
    protected $table = 'posts';

    public function category()
    {
        return $this->belongsTo('App\Models\Category');
    }

    public function user()
    {
        return $this->belongsTo('App\Models\User');
    }
}

User factory:

$factory->define(User::class, function (Faker $faker) {
    return [
        'id' => $faker->unique()->randomNumber(3),
        'name' => $faker->name(),
    ];
});

Category factory:

$factory->define(Category::class, function (Faker $faker) {
    return [
        'id' => $faker->unique()->randomNumber(3),
        'name' => $faker->word(),
    ];
});

Post factory:

$factory->define(User::class, function (Faker $faker) {
    return [
        'id' => $faker->unique()->randomNumber(3),
        'name' => $faker->realText($maxNbChars = 200, $indexSize = 2),
    ];
});

If I only had users and posts, I know that I could seed the database the following way:

public function seed()
{
    $users = factory(App\User::class, 10)
        ->create()
        ->each(function ($user) {
            $user->posts()->createMany(factory(App\Post::class, 10)->make()->toArray());
        });
}

but obviously that won't work in my case. I have tried the following:

public function seed()
{
    factory(User::class, 10)->create();
    factory(Category::class, 10)->create();
    factory(Post::class, 100)->create()->each(function ($post){
        $post->user()->attach(User::all()->random(1));
        $post->category()->attach(Category::all()->random(1));
    });
}

as well as the same function using make/save instead of create:

public function seed()
    {
        factory(User::class, 10)->create();
        factory(Category::class, 10)->create();
        factory(Post::class, 100)->make()->each(function ($post) {
            $post->user()->attach(User::all()->random(1));
            $post->category()->attach(Category::all()->random(1));
        })->save();
    }

but in both cases, I get the error:

Call to undefined method
  Illuminate\Database\Eloquent\Relations\BelongsTo::attach()

Body:
You have to use associate():

public function seed()
{
    factory(User::class, 10)->create();
    factory(Category::class, 10)->create();
    factory(Post::class, 100)->make()->each(function ($post) {
        $post->user()->associate(User::inRandomOrder()->first());
        $post->category()->associate(Category::inRandomOrder()->first());
        $post->save();
    });
}

Also User::all()->random(1) will return a collection and not a model, which will throw an exception, I replaced it with Model::inRandomOrder()->first(), which will fetch a random model from the database.

From the docs:

When updating a belongsTo relationship, you may use the associate
  method. This method will set the foreign key on the child model:

$account = App\Account::find(10);

$user->account()->associate($account);

$user->save();

Update

In your Modelfactory:

/** @var Factory $factory */
$factory->define(Post::class, function (Faker\Generator $faker) {
    return [
        // not sure why you do this, is it not a autoincrement column?
        'id' => $faker->unique()->randomNumber(3),
        'name' => $faker->realText($maxNbChars = 200, $indexSize = 2),
        'category_id' => function () {
            if ($category = Category::inRandomOrder()->first()) {
                return $category->id;
            }

            return factory(Category::class)->create()->id;
        },
        'user_id' => function () {
            if ($user = User::inRandomOrder()->first()) {
                return $user->id;
            }

            return factory(User::class)->create()->id;
        },
    ];
});

In your seeder:

public function seed()
{
    factory(User::class, 10)->create();
    factory(Category::class, 10)->create();
    factory(Post::class, 100)->create();
}


问:
Getting bash to ignore bash keywords in a script
I have a script in bash which uses the HTK toolkit. One of the files that the HTK tool uses is called do and is present within a directory called hmm_1/. Now, when I need to call a particular tool from within the HTK toolkit, I do it like so:

some HTK command -H hmm_1/do -H hmm_1/<something else> and so on. I just noticed that gvim highlights the do file name in the above command, thinking it is a keyword. However, it is a file name. My question is:

Will bash interpret it as a keyword or does bash know better (it is just a gvim quirk).

How can I get bash to "know" that some variable names, though innocuously named like keywords are not that and are instead filenames?

Note: I cannot change the name of the file now. I will have to backtrack through a large number of steps.

I just don't know how to phrase this question. Help in editing the question line is most welcome.

答:
Other than using the command as part of an explicit path (like Ernest proposed, and what will do in your case), you can also use the command builtin to search commands which are in some directory in the $PATH variable, ignoring aliases, shell functions and shell keywords:

```<code>$ echo '#!/bin/bash
> echo Hello World!' > ~/bin/do

$ chmod u+x ~/bin/do
</code>```

~/bin is in my path, thus this would normally work:

```<code>$ do
bash: Syntaxfehler beim unerwarteten Wort `do'
</code>```

It does not, since it is a reserved word. Prefixing it with command helps:

```<code>$ command do
Hello World!
</code>```

As does using the full path:

```<code>$ ~/bin/do
Hello World!
</code>```

Body:
Other than using the command as part of an explicit path (like Ernest proposed, and what will do in your case), you can also use the command builtin to search commands which are in some directory in the $PATH variable, ignoring aliases, shell functions and shell keywords:

$ echo '#!/bin/bash
> echo Hello World!' > ~/bin/do

$ chmod u+x ~/bin/do

~/bin is in my path, thus this would normally work:

$ do
bash: Syntaxfehler beim unerwarteten Wort `do'

It does not, since it is a reserved word. Prefixing it with command helps:

$ command do
Hello World!

As does using the full path:

$ ~/bin/do
Hello World!


问:
How can I kill a remote process for my app?
Our app uses this method to kill remote process; but can any other plan can be used? I need this because getRunningAppProcesses() may not work.

```<code>public void killChildProcess() {
    ActivityManager actvityManager = (ActivityManager)this.getSystemService( Context.ACTIVITY_SERVICE );
    List<RunningAppProcessInfo> procInfos = actvityManager.getRunningAppProcesses();

    for(RunningAppProcessInfo procInfo : procInfos) {
        if (procInfo.processName != null &&
                procInfo.processName.equals("package:remote")) {

            Process.killProcess(procInfo.pid);
        }
    }
}
</code>```

答:
Check the process name contains <code>:remote</code> then go ahead.  </p>

```<code>    @Override
    public void killRemoteProcess() {
        ActivityManager activityManager =  (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();

        for (ActivityManager.RunningAppProcessInfo appProcessInfo: runningAppProcesses) {
            if (appProcessInfo.processName.contains(getApplicationInfo().processName + ":remote")) {
                Log.d("Killing active process: " + getApplicationInfo().processName + ":remote");
                android.os.Process.killProcess(appProcessInfo.pid);
            }
        }
    }
</code>```

Body:
Our app uses this method to kill remote process; but can any other plan can be used? I need this because getRunningAppProcesses() may not work.

public void killChildProcess() {
    ActivityManager actvityManager = (ActivityManager)this.getSystemService( Context.ACTIVITY_SERVICE );
    List<RunningAppProcessInfo> procInfos = actvityManager.getRunningAppProcesses();

    for(RunningAppProcessInfo procInfo : procInfos) {
        if (procInfo.processName != null &&
                procInfo.processName.equals("package:remote")) {

            Process.killProcess(procInfo.pid);
        }
    }
}

Body:
Check the process name contains :remote then go ahead.

    @Override
    public void killRemoteProcess() {
        ActivityManager activityManager =  (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();

        for (ActivityManager.RunningAppProcessInfo appProcessInfo: runningAppProcesses) {
            if (appProcessInfo.processName.contains(getApplicationInfo().processName + ":remote")) {
                Log.d("Killing active process: " + getApplicationInfo().processName + ":remote");
                android.os.Process.killProcess(appProcessInfo.pid);
            }
        }
    }


问:
How to remove Public render parameter from jsp or render phase of portlet class
I have two portlets :
1. Blog Portlet.
2. Author Portlet.

I used the concept of Public render parameter to send data (say key "urlTitle") from Blog portlet to Author portlet

But after sending "urlTitle" from Blog portlet how can I remove the data from Public render parameter

```<code>In Blog Portlet
EX code: view.jsp

<portlet:renderURL var="viewEntryURL">
    <portlet:param name="struts_action" value="/blogs/view_entry" />
    <portlet:param name="redirect" value="<%= currentURL %>" />
    <portlet:param name="urlTitle" value="<%= entry.getUrlTitle() %>" />
</portlet:renderURL>

<a href="${viewEntryURL}">Send Data</a>

</code>```

Now how I can remove "urlTitle" form the public render parameter after data is sent.

Please give feedback.
-Thanks in advance

答:
You need to set

```<code>javax.portlet.init-param.copy-request-parameters=false
</code>```

in your portlet class.

Body:
I have two portlets :
1. Blog Portlet.
2. Author Portlet.

I used the concept of Public render parameter to send data (say key "urlTitle") from Blog portlet to Author portlet

But after sending "urlTitle" from Blog portlet how can I remove the data from Public render parameter

In Blog Portlet
EX code: view.jsp

<portlet:renderURL var="viewEntryURL">
    <portlet:param name="struts_action" value="/blogs/view_entry" />
    <portlet:param name="redirect" value="<%= currentURL %>" />
    <portlet:param name="urlTitle" value="<%= entry.getUrlTitle() %>" />
</portlet:renderURL>

Send Data

Now how I can remove "urlTitle" form the public render parameter after data is sent.

Please give feedback.
-Thanks in advance

Body:
You need to set

javax.portlet.init-param.copy-request-parameters=false

in your portlet class.


问:
Upgrade to Webpack 5 breaking Storybook 5
In process of upgrading a webpack 4/storybook 5 project to webpack 5 to hopefully take advantage of federated modules. I have regular webpack --config webpack.config.js building working atfer some struggle, but I can't seem to overcome this storybook config issue to get that working. there's not a lot in the storybook webpack.config.js - just some module rules for testing for less files and using the appropriate loaders. It seems the error I'm encountering is typical when upgrading webpack majors, as I've found a number of folks that encountered the same thing going from 3-4, but anything I've tried has failed so far. The specific stacktrace is:

```<code>Cannot read property 'tapAsync' of undefined
    at ExternalModuleFactoryPlugin.apply (/Users/tbullard/Workspace/unify/node_modules/webpack/lib/ExternalModuleFactoryPlugin.js:29:39)
    at compiler.hooks.compile.tap (/Users/tbullard/Workspace/unify/node_modules/webpack/lib/ExternalsPlugin.js:24:63)
    at SyncHook.eval [as call] (eval at create (/Users/tbullard/Workspace/unify/node_modules/tapable/lib/HookCodeFactory.js:19:10), <anonymous>:7:1)
    at SyncHook.lazyCompileHook (/Users/tbullard/Workspace/unify/node_modules/tapable/lib/Hook.js:154:20)
    at hooks.beforeCompile.callAsync.err (/Users/tbullard/Workspace/unify/node_modules/@storybook/core/node_modules/webpack/lib/Compiler.js:665:23)
    at _err0 (eval at create (/Users/tbullard/Workspace/unify/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:11:1)
    at compiler.inputFileSystem.readFile (/Users/tbullard/Workspace/unify/node_modules/@storybook/core/node_modules/webpack/lib/DllReferencePlugin.js:72:15)
    at process.nextTick (/Users/tbullard/Workspace/unify/node_modules/@storybook/core/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:85:15)
    at process._tickCallback (internal/process/next_tick.js:61:11)
</code>```

Leads me to believe there's a plugin incompatibility ♂ TIA!

答:
Storybook is not yet ready to work with Webpack 5 but it is on their roadmap for version 7.0.

More context in this GitHub issue.

Body:
In process of upgrading a webpack 4/storybook 5 project to webpack 5 to hopefully take advantage of federated modules. I have regular webpack --config webpack.config.js building working atfer some struggle, but I can't seem to overcome this storybook config issue to get that working. there's not a lot in the storybook webpack.config.js - just some module rules for testing for less files and using the appropriate loaders. It seems the error I'm encountering is typical when upgrading webpack majors, as I've found a number of folks that encountered the same thing going from 3-4, but anything I've tried has failed so far. The specific stacktrace is:

Cannot read property 'tapAsync' of undefined
    at ExternalModuleFactoryPlugin.apply (/Users/tbullard/Workspace/unify/node_modules/webpack/lib/ExternalModuleFactoryPlugin.js:29:39)
    at compiler.hooks.compile.tap (/Users/tbullard/Workspace/unify/node_modules/webpack/lib/ExternalsPlugin.js:24:63)
    at SyncHook.eval [as call] (eval at create (/Users/tbullard/Workspace/unify/node_modules/tapable/lib/HookCodeFactory.js:19:10), <anonymous>:7:1)
    at SyncHook.lazyCompileHook (/Users/tbullard/Workspace/unify/node_modules/tapable/lib/Hook.js:154:20)
    at hooks.beforeCompile.callAsync.err (/Users/tbullard/Workspace/unify/node_modules/@storybook/core/node_modules/webpack/lib/Compiler.js:665:23)
    at _err0 (eval at create (/Users/tbullard/Workspace/unify/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:11:1)
    at compiler.inputFileSystem.readFile (/Users/tbullard/Workspace/unify/node_modules/@storybook/core/node_modules/webpack/lib/DllReferencePlugin.js:72:15)
    at process.nextTick (/Users/tbullard/Workspace/unify/node_modules/@storybook/core/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:85:15)
    at process._tickCallback (internal/process/next_tick.js:61:11)

Leads me to believe there's a plugin incompatibility ♂ TIA!


问:
Android fragments vs compound controls
Why should Android 3.0 fragments be used instead of compound controls? One can create a View inheritor or compound control once and use it everywhere.

I've read http://android-developers.blogspot.com/2011/02/android-30-fragments-api.html but did not find the answer.

答: The reason would be to have the same code work on tablets and phones.  There are different layout considerations for these devices and Fragments allow you to take that into consideration and have your app behave differently without having to rewrite any code.</p>

Title: Android fragments vs compound controls


问:
Java 8 optional .map().orElse always returns orElse
I'm trying to get the version from a package and am having trouble implementing it.
This code returns the correct package:

```<code>private String getVersion(){
    Optional<Class<?>> optional = Arrays.stream(getClass().getInterfaces())
            .filter(cl -> isCorrectClass(cl))
            .findFirst();
    return optional.isPresent() ? optional.get().getPackage().getImplementationVersion() : "";
}

</code>```

But I think it would be neater to do

```<code>private String getVersionWithMap() {
    return Arrays.stream(getClass().getInterfaces())
            .filter(cl -> isCorrectClass(cl))
            .findFirst()
            .map(cl -> cl.getPackage().getImplementationVersion())
            .orElse("");
}

</code>```

However, getVersionWithMap() always returns the empty string "".

EDIT:
SOLVED. It ended up being the frontend that was wrong. Found this after going back to using getVersion() and having the same issue of no visible version in the frontend.

答:
If cl.getPackage().getImplementationVersion() returns a null value your  second code will invoke orElse() because the result of map() is an empty Optional.

In the first code that's not the case, you will return null directly from the method. You are comparing two different codes.

Body:
I'm trying to get the version from a package and am having trouble implementing it.
This code returns the correct package:

private String getVersion(){
    Optional<Class<?>> optional = Arrays.stream(getClass().getInterfaces())
            .filter(cl -> isCorrectClass(cl))
            .findFirst();
    return optional.isPresent() ? optional.get().getPackage().getImplementationVersion() : "";
}

But I think it would be neater to do

private String getVersionWithMap() {
    return Arrays.stream(getClass().getInterfaces())
            .filter(cl -> isCorrectClass(cl))
            .findFirst()
            .map(cl -> cl.getPackage().getImplementationVersion())
            .orElse("");
}

However, getVersionWithMap() always returns the empty string "".

EDIT:
SOLVED. It ended up being the frontend that was wrong. Found this after going back to using getVersion() and having the same issue of no visible version in the frontend.


问:
Google sheets Import Range
I don't think that importrange is a real formula I have spent hours on this and it doesn't work full stop.

The sheet name of the data I wish to import is Fire Safety Audit but it was originally sheet 1

```<code>=importrange(https://docs.google.com/spreadsheets/d/18B8KclREhEvOm9ZeOEEfpFSkTol1uxwlCt8kVfptO6I/edit#gid=2093530965";"fire safety audit"!A1:w1000")

=importrange(https://docs.google.com/spreadsheets/d/18B8KclREhEvOm9ZeOEEfpFSkTol1uxwlCt8kVfptO6I/edit#gid=2093530965";"sheet1"!A1:w1000")
</code>```

I have tried so many different types of formulas with colons, commas and semi colons.

Every time no matter what I try the number 2093530965 remains in blue font and it says I have parse error. Not quite sure why Google make this so complicated and do not have any help for it whatsoever. In summary its crap.

答:
Try using the formula with the syntax in the documentation:

Syntax
  IMPORTRANGE(spreadsheet_url, range_string)

So, if your Sheet is named Sheet1 change from this:

```<code>=importrange(https://docs.google.com/spreadsheets/d/18B8KclREhEvOm9ZeOEEfpFSkTol1uxwlCt8kVfptO6I/edit#gid=2093530965";"sheet1"!A1:w1000")
</code>```

To this:

```<code>=importrange("https://docs.google.com/spreadsheets/d/18B8KclREhEvOm9ZeOEEfpFSkTol1uxwlCt8kVfptO6I/edit#gid=2093530965";"sheet1!A1:w1000")
</code>```

Title: Google sheets Import Range

Body:
I don't think that importrange is a real formula I have spent hours on this and it doesn't work full stop.

The sheet name of the data I wish to import is Fire Safety Audit but it was originally sheet 1

=importrange(https://docs.google.com/spreadsheets/d/18B8KclREhEvOm9ZeOEEfpFSkTol1uxwlCt8kVfptO6I/edit#gid=2093530965";"fire safety audit"!A1:w1000")

=importrange(https://docs.google.com/spreadsheets/d/18B8KclREhEvOm9ZeOEEfpFSkTol1uxwlCt8kVfptO6I/edit#gid=2093530965";"sheet1"!A1:w1000")

I have tried so many different types of formulas with colons, commas and semi colons.

Every time no matter what I try the number 2093530965 remains in blue font and it says I have parse error. Not quite sure why Google make this so complicated and do not have any help for it whatsoever. In summary its crap.

Body:
Try using the formula with the syntax in the documentation:

Syntax
  IMPORTRANGE(spreadsheet_url, range_string)

So, if your Sheet is named Sheet1 change from this:

=importrange(https://docs.google.com/spreadsheets/d/18B8KclREhEvOm9ZeOEEfpFSkTol1uxwlCt8kVfptO6I/edit#gid=2093530965";"sheet1"!A1:w1000")

To this:

=importrange("https://docs.google.com/spreadsheets/d/18B8KclREhEvOm9ZeOEEfpFSkTol1uxwlCt8kVfptO6I/edit#gid=2093530965";"sheet1!A1:w1000")


问:
Image cropRelationship for srcset
If Implemented successful the srcset attribute for img tags regarding this question about responsive images in apostrophe. I followed the suggestion to include only img elements and not mutliple img and div's with background-image styles. I used the object-position style to position elements with values from focalPointToBackgroundPosition that works pretty good for focal points.

Unfortunately I was not able to pass the cropping values to the image url's in srcset attribute. I mean the numbers and the end of an image name when the image is shown by the default src attribute with apos.attachments.url helper.

/uploads/attachments/imagename.93.10.1745.873.full.jpg

As far as I understood the code in apostrophe-images/lib/api.js it should be possible because you made this function already available with cropRelationship so I think there is something wrong in my code.

```

<pre class="lang-js prettyprint-override"><code>{{ apos.area(piece, 'content', {
    limit: 2,
    widgets: {
      'card': {
        size: 'full'
        aspectRatio: [ 2, 1 ],
        controls: {
          cloneable: false,
          removable: true,
          position: 'top-right'
        }
      }
    }
}) }}
</code>```

答:
I figured the solution. So if you want to use cropping for images with srcset you need to add relationship to srcset attribute like this:

```<code>srcset="{{ apos.images.srcset(image.attachment, relationshiop) }}"
</code>```

Title: Image cropRelationship for srcset

Body:
If Implemented successful the srcset attribute for img tags regarding this question about responsive images in apostrophe. I followed the suggestion to include only img elements and not mutliple img and div's with background-image styles. I used the object-position style to position elements with values from focalPointToBackgroundPosition that works pretty good for focal points.

Unfortunately I was not able to pass the cropping values to the image url's in srcset attribute. I mean the numbers and the end of an image name when the image is shown by the default src attribute with apos.attachments.url helper.

/uploads/attachments/imagename.93.10.1745.873.full.jpg

As far as I understood the code in apostrophe-images/lib/api.js it should be possible because you made this function already available with cropRelationship so I think there is something wrong in my code.

{{ apos.area(piece, 'content', {
    limit: 2,
    widgets: {
      'card': {
        size: 'full'
        aspectRatio: [ 2, 1 ],
        controls: {
          cloneable: false,
          removable: true,
          position: 'top-right'
        }
      }
    }
}) }}

Body:
I figured the solution. So if you want to use cropping for images with srcset you need to add relationship to srcset attribute like this:

srcset="{{ apos.images.srcset(image.attachment, relationshiop) }}"


问:
bash - loop through subdirectories, cat files and rename with directory name
I have a folder structure like this ...

```<code>data/
---B1/
name_x_1.gz
name_y_1.gz
name_z_2.gz
name_p_2.gz
---C1
name_s_1.gz
name_t_1.gz
name_u_2.gz
name_v_2.gz
</code>```

I need to go in to each subdirectory (e.g. B1) and perform the following:

```<code>cat *_1.gz > B1_1.gz
cat *_2.gz > B1_2.gz
</code>```

I'm having problems with the file naming part. I can get in directories using the following:

```<code>for d in */; do
cat *_1.gz > $d_1.gz
cat *_2.gz > $d_2.gz
done
</code>```

However I get an error that $d is a directory -- how do I strip the name to create the concatenated filename?

Thanks

答:
If you're calling bash, you can use parameter expansion and do everything natively in the shell without creating a sub-shell to another process.  This is POSIX compliant</p>

```<code>#!/bin/bash

for dir in data/*; do
  cat "$dir/"*_1.gz > "$dir/${dir##*/}_1.gz"
  cat "$dir/"*_2.gz > "$dir/${dir##*/}_2.gz"
done
</code>```

Body:
I have a folder structure like this ...

data/
---B1/
name_x_1.gz
name_y_1.gz
name_z_2.gz
name_p_2.gz
---C1
name_s_1.gz
name_t_1.gz
name_u_2.gz
name_v_2.gz

I need to go in to each subdirectory (e.g. B1) and perform the following:

cat *_1.gz > B1_1.gz
cat *_2.gz > B1_2.gz

I'm having problems with the file naming part. I can get in directories using the following:

for d in */; do
cat *_1.gz > $d_1.gz
cat *_2.gz > $d_2.gz
done

However I get an error that $d is a directory -- how do I strip the name to create the concatenated filename?

Thanks

Body:
If you're calling bash, you can use parameter expansion and do everything natively in the shell without creating a sub-shell to another process.  This is POSIX compliant

#!/bin/bash

for dir in data/*; do
  cat "$dir/"*_1.gz > "$dir/${dir##*/}_1.gz"
  cat "$dir/"*_2.gz > "$dir/${dir##*/}_2.gz"
done